Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions Cyber Security/stego LSB and RAS/RSA2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import random


#Euclid's Algo for greatest common divisor
#used to make ot faster for larger intgers
def gcd(a,b):
while b!=0:
a,b = b,a%b
return a

#Euclid's extended algo for multiplicative inverse
#calcultion

def m_inv(e,phi):
d=0
x1=0
x2=1
y1=1
temp_phi=phi

while e>0:
temp1=temp_phi//e
temp2=temp_phi - temp1*e
temp_phi = e
e= temp2

x=x2 - temp1*x1
y=d - temp1*y1

x2=x1
x1=x
d=y1
y1=y

if temp_phi == 1:
return d+phi


#prime test
def is_prime(num):
if num==2:
return True
if num<2 or num%2==0:
return False
for n in range(3,int(num**0.5)+2,2):
if num %n ==0:
return False
return True

def gen_keypair(p,q):
if not(is_prime(p) and is_prime(q)):
raise ValueError('Enter both number as prime.')
elif p==q:
raise ValueError('Both prime numbers cannot be equal')

n=p*q
#phi is totient of num
phi = (p-1)*(q-1)
#Choose e st e and phi(n) are coprime
e=random.randrange(1,phi)
# to ensure e anf phi(n) are coprime
g=gcd(e,phi)
while g!=1:
e=random.randrange(1,phi)
g=gcd(e,phi)

#To genertae private key
d=m_inv(e,phi)

#public key -> (e,n)
#private key -> (d,n)
return ((e,n),(d,n))

def encrypt(pk,txt):
#unpack key in it's component
key,n=pk
#convert each letter in plaintext to num based on
#characters using a^b mod m
cipher = [pow(ord(char),key,n) for char in txt]
#cipher is array of bytes
return cipher


def decrypt(pk, ciphertxt):
# unpack key in it's component
key, n = pk
#geenrater plaintext based on ciphertext and key
#using a^b mod m
aux=[str(pow(char,key,n)) for char in ciphertxt]
plain=[chr(int(char2)) for char2 in aux]
return ''.join(plain)

if __name__=='__main__':
print ("--->RSA ENCRYPTION/DECRYPTION<---")
p=int(input("Enter prime number 1 : "))
q=int(input("Enter prime number 2 : "))
print ("Generating Public/Private keypairs...")
public,private=gen_keypair(p,q)
print ("Public key : ",public," and private key : ",private)
msg=input("Enter mwssage to be encrypted : ")
enc_msg=encrypt(private,msg)
print ("Encrypted message : ")
print (''.join(map(lambda x: str(x), enc_msg)))
print ("Decrypting msf with public key", public, "...")
print ("YOur message : ")
print (decrypt(public, enc_msg))


13 changes: 13 additions & 0 deletions Cyber Security/stego LSB and RAS/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
#Stegonometry

##This technique is used to hide a text or image or visusal data into an image
##I have provided code for LSB text strgnography

#Cryptography

##This technique is used to change a text into a non recognizable text meassage
##Provides a code for RAS algorithm. (It can be easily cahnged according to the OS used for easy use)

#Basic Idea

##we can embedd them both to make a 2-layer crypted text app
115 changes: 115 additions & 0 deletions Cyber Security/stego LSB and RAS/stego_file3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
#numpy is numerical python an excent way to deal with array and large amout of data
from statistics import mode

from PIL import Image
import numpy as np

#code to convert the source image into NumPy array of pixels
#and store the size
def encode_img(src,msg,dest):
img= Image.open(src, 'r')
width,height=img.size
array=np.array(list(img.getdata()))

if img.mode == 'RGB':
n=3
elif img.mode =='RGBA':
n=4
total_pix=array.size//n

#delimiter adding and then
#tconverting updated message to binary form and calculate
#required pixels

msg += "$t3g0"
b_msg=''.join([format(ord(i),"08b") for i in msg])
req_pix=len(b_msg)

#check total pixel sufficient for secret message
#if yes, modify pixels' lsb to bits of secret message
#untill complete message with delimiter got hide

if req_pix>total_pix:
print("Error : Need larger file size")
else:
ind=0
for p in range(total_pix):
for q in range(0,3):
if ind<req_pix:
array[p][q] = int(bin(array[p][q]) [2:9] + b_msg[ind], 2)
ind+=1

#update pixel array and usr this to create and save it in destination provided

array=array.reshape(height, width, n)
enc_img=Image.fromarray(array.astype('uint8'), img.mode)
enc_img.save(dest)
print("Image Encoded Successfully")


def decode_img(src):
# saving pixels of source image as array
# figure out mode
# calculating total pixels

img=Image.open(src, 'r')
array = np.array(list(img.getdata()))

if img.mode == 'RGB':
n=3
elif img.mode == 'RGBA':
n=4
total_pix = array.size//n

#extract lsb from each pix from top-left and store in group of 8
#convert these grpups into ASCII cahracters to find hidden message
#utill we read delimiter

hidden_bits = ""
for p in range (total_pix):
for q in range(0,3):
hidden_bits += (bin(array[p][q])[2:][-1])

hidden_bits = [hidden_bits[i:i+8] for i in range(0,len(hidden_bits),8)]
msg=""
for i in range(len(hidden_bits)):
if msg[-5:] == "$t3g0":
break
else:
msg += chr(int(hidden_bits[i],2))

#check if delimiter found. If not -> no hidden message
if "$t3g0" in msg:
print("Hidden Message: ",msg[:-5])
else:
print("No Hidden Message Found")


def stego():
print("---> Welcome to stego <---")
print("1: Encode")
print("2: Decode")

func=input()

if func=='1':
print("Enter Source Image Path")
src =input()
print("Enter Message to Hide")
msg=input()
print("Enter Destination Image Path")
dest=input()
print("Encoding...")
encode_img(src,msg,dest)

elif func=='2':
print("Enter Source Image Path")
src = input()
print("Decoding..")
decode_img(src)
else:
print("Error : Invalid Option Chosen")

stego()


108 changes: 108 additions & 0 deletions stego LSB and RAS/RSA2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,108 @@
import random


#Euclid's Algo for greatest common divisor
#used to make ot faster for larger intgers
def gcd(a,b):
while b!=0:
a,b = b,a%b
return a

#Euclid's extended algo for multiplicative inverse
#calcultion

def m_inv(e,phi):
d=0
x1=0
x2=1
y1=1
temp_phi=phi

while e>0:
temp1=temp_phi//e
temp2=temp_phi - temp1*e
temp_phi = e
e= temp2

x=x2 - temp1*x1
y=d - temp1*y1

x2=x1
x1=x
d=y1
y1=y

if temp_phi == 1:
return d+phi


#prime test
def is_prime(num):
if num==2:
return True
if num<2 or num%2==0:
return False
for n in range(3,int(num**0.5)+2,2):
if num %n ==0:
return False
return True

def gen_keypair(p,q):
if not(is_prime(p) and is_prime(q)):
raise ValueError('Enter both number as prime.')
elif p==q:
raise ValueError('Both prime numbers cannot be equal')

n=p*q
#phi is totient of num
phi = (p-1)*(q-1)
#Choose e st e and phi(n) are coprime
e=random.randrange(1,phi)
# to ensure e anf phi(n) are coprime
g=gcd(e,phi)
while g!=1:
e=random.randrange(1,phi)
g=gcd(e,phi)

#To genertae private key
d=m_inv(e,phi)

#public key -> (e,n)
#private key -> (d,n)
return ((e,n),(d,n))

def encrypt(pk,txt):
#unpack key in it's component
key,n=pk
#convert each letter in plaintext to num based on
#characters using a^b mod m
cipher = [pow(ord(char),key,n) for char in txt]
#cipher is array of bytes
return cipher


def decrypt(pk, ciphertxt):
# unpack key in it's component
key, n = pk
#geenrater plaintext based on ciphertext and key
#using a^b mod m
aux=[str(pow(char,key,n)) for char in ciphertxt]
plain=[chr(int(char2)) for char2 in aux]
return ''.join(plain)

if __name__=='__main__':
print ("--->RSA ENCRYPTION/DECRYPTION<---")
p=int(input("Enter prime number 1 : "))
q=int(input("Enter prime number 2 : "))
print ("Generating Public/Private keypairs...")
public,private=gen_keypair(p,q)
print ("Public key : ",public," and private key : ",private)
msg=input("Enter mwssage to be encrypted : ")
enc_msg=encrypt(private,msg)
print ("Encrypted message : ")
print (''.join(map(lambda x: str(x), enc_msg)))
print ("Decrypting msf with public key", public, "...")
print ("YOur message : ")
print (decrypt(public, enc_msg))


Loading