cns_code_get_random_bytes
Following is sample hill_cipher code.
import numpy as np
def mod_inverse(a,m):
a = a%m
for x in range(1,m):
if((a*x)% m ==1):
return x
return None
#K^-1
def matrix_mod_inv(matrix, mod):
det = int(np.round(np.linalg.det(matrix)))
det_inv = mod_inverse(det%mod , mod)
adj = np.array([[matrix[1][1],-matrix[0][1]],[-matrix[1][0],matrix[0][0]]])
key_inv = (det_inv *adj)%mod
return key_inv
def text_to_vec(text):
return([ord(char)-ord('A') for char in text])
def vec_to_text(vec):
return ''.join([chr(int(num)+ord('A')) for num in vec ])
def encrypt(plaintxt, key):
plaintxt = plaintxt.upper().replace(' ','')
if len(plaintxt)%2!=0:
plaintxt += 'X'
result = ''
for i in range(0, len(plaintxt),2):
pair = text_to_vec(plaintxt[i:i+2])
vector = np.dot(key,pair)%26
result += vec_to_text(vector)
return result
def decrypt(cipher, key):
key_inv = matrix_mod_inv(key,26)
result = ''
for i in range(0, len(cipher),2):
pair = text_to_vec(cipher[i:i+2])
vector = np.dot(key_inv,pair)%26
result += vec_to_text(vector)
return result
print("Enter key matrix: ")
key_values = []
for i in range(4):
val = int(input(f"Enter value {i+1}: "))
key_values.append(val)
key = np.array(key_values).reshape(2,2)
plaintext = input("Enter plaintext: ")
ciphertext = encrypt(plaintext,key)
decrypted = decrypt(ciphertext,key)
print("Encrypted : ",ciphertext)
print("Decrypted : ",decrypted)
Following is single and double columnar cipher
def get_order(key):
# Get the alphabetical order of key letters
key = key.upper()
order = sorted(list(enumerate(key)), key=lambda x: x[1])
return [i[0] for i in order]
def encrypt_columnar(message, key):
message = message.upper()
key_length = len(key)
order = get_order(key)
# Padding
while len(message) % key_length != 0:
message += 'X'
# Create grid
rows = [message[i:i + key_length] for i in range(0, len(message), key_length)]
# Read columns in order of key
cipher = ''
for index in order:
for row in rows:
cipher += row[index]
return cipher
def decrypt_columnar(cipher, key):
cipher = cipher.upper()
key_length = len(key)
order = get_order(key)
# Number of rows
num_rows = len(cipher) // key_length
# Prepare empty grid
grid = [''] * key_length
print(grid)
start = 0
# Fill columns in correct order
for i in order:
grid[i] = cipher[start:start + num_rows]
start += num_rows
print(grid)
# Rebuild message row by row
message = ''
for i in range(num_rows):
for j in range(key_length):
message += grid[j][i]
return message
# -------- Main Code Starts Here --------
message = input("Enter your message: ")
key = input("Enter your key (string): ")
# --- Single Columnar Encryption ---
single_encrypted = encrypt_columnar(message, key)
print("\nš Single Columnar Encrypted:")
print(single_encrypted)
# --- Single Columnar Decryption ---
single_decrypted = decrypt_columnar(single_encrypted, key)
print("\nš Single Columnar Decrypted:")
print(single_decrypted)
# --- Double Columnar Encryption ---
double_encrypted = encrypt_columnar(single_encrypted, key)
print("\nšš Double Columnar Encrypted:")
print(double_encrypted)
# --- Double Columnar Decryption ---
double_decrypted = decrypt_columnar(double_encrypted, key)
# Decrypt again to get original
original_message = decrypt_columnar(double_decrypted, key)
print("\nšš Double Columnar Decrypted (Original Message):")
print(original_message)
here is rsa code
import math
# Step 1: Choose two prime numbers
p = 3
q = 5
# Step 2: Compute n
n = p * q
print("n =", n)
# Step 3: Compute phi(n)
phi = (p - 1) * (q - 1)
# Step 4: Choose public key e such that 1 < e < phi and gcd(e, phi) = 1
e = 2
while e < phi:
if math.gcd(e, phi) == 1:
break
e += 1
print("e =", e)
# Step 5: Calculate d such that (d * e) % phi = 1
# This finds the modular inverse of e modulo phi
d = pow(e, -1, phi)
print("d =", d)
# Public and Private Keys
print(f'Public key: ({e}, {n})')
print(f'Private key: ({d}, {n})')
# Step 6: Encryption
msg = 8
print(f'Original message: {msg}')
C = pow(msg, e, n)
print(f'Encrypted message: {C}')
# Step 7: Decryption
M = pow(C, d, n)
print(f'Decrypted message: {M}')
rail fence
def railfencencyption(plaintext , numrails):
fence = [["" for _ in range(len(plaintext))] for _ in range(numrails)]
rail = 0
down = True
for i in range(len(plaintext)):
fence[rail][i] = plaintext[i]
if down:
rail += 1
else:
rail -= 1
if rail == numrails - 1:
down = False
elif rail == 0:
down = True
ciphertext = ""
for row in fence:
ciphertext += "".join(row)
return ciphertext.replace(" ","")
def railfencedecrption(ciphertext , numrails):
fence = [["" for _ in range(len(ciphertext))] for _ in range(numrails)]
down = True
rail = 0
index = 0
for i in range(len(ciphertext)):
fence[rail][i] = "*"
if down:
rail += 1
else:
rail -= 1
if rail == numrails - 1:
down = False
elif rail == 0:
down = True
for row in fence:
for i in range(len(row)):
if row[i]=="*":
row[i] = ciphertext[index]
index += 1
plaintext = ""
rail = 0
down = True
for i in range(len(ciphertext)):
plaintext += fence[rail][i]
if down:
rail += 1
else:
rail -= 1
if rail == numrails - 1:
down = False
elif rail == 0:
down = True
return plaintext
text = input("Enter message : ")
numrails = int(input("Enter number of rails: "))
encrypted = encryption(text,numrails)
decrypted = decryption(encrypted,numrails)
print("encrypted : ",encrypted)
print("decrypted: ",decrypted)
ceaser cipher
def encrypt(text,shift):
result =""
for char in text:
if char.isupper():
result += chr((ord(char)- 65 + shift) % 26 + 65)
elif char.islower():
result += chr((ord(char) -97 + shift) % 26 + 97)
elif char.isdigit():
result += chr((ord(char) - 48 + shift)% 10 + 48)
else:
result += char
return result
def decrypt(cipher,shift):
return encrypt(cipher, -shift)
text = input("enter message: ")
shift = int(input("Enter shift: "))
cipher = encrypt(text,shift)
print("Encrypted : ",cipher)
print("Decrypted : ",decrypt(cipher,shift))
AES
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
# AES requires key of length 16, 24, or 32 bytes
key = get_random_bytes(16)
cipher = AES.new(key, AES.MODE_CBC)
data = b"Hello, AES Encryption!"
ciphertext = cipher.encrypt(pad(data, AES.block_size))
# Decryption
decipher = AES.new(key, AES.MODE_CBC, cipher.iv)
plaintext = unpad(decipher.decrypt(ciphertext), AES.block_size)
print("AES Encrypted:", ciphertext)
print("AES Decrypted:", plaintext)
DES
from Crypto.Cipher import DES
from Crypto.Random import get_random_bytes
from Crypto.Util.Padding import pad, unpad
# DES requires 8-byte key
key = get_random_bytes(8)
cipher = DES.new(key, DES.MODE_CBC)
data = b"Hello, DES!"
ciphertext = cipher.encrypt(pad(data, DES.block_size))
# Decryption
decipher = DES.new(key, DES.MODE_CBC, cipher.iv)
plaintext = unpad(decipher.decrypt(ciphertext), DES.block_size)
print("DES Encrypted:", ciphertext)
print("DES Decrypted:", plaintext)
play_fair
def generate_key_matrix(key):
key = key.upper().replace("J","I").replace(" ","")
matrix = []
visited = set()
for char in key:
if char not in visited and char.isalpha():
visited.add(char)
matrix.append(char)
for char in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
if char not in visited:
matrix.append(char)
visited.add(char)
return [ matrix[i:i+5] for i in range(0,25,5)]
def transform(text):
text= text.upper().replace("J","I").replace(" ","")
transformed = ""
i = 0
while i<len(text):
a = text[i]
b = text[i+1] if i+1<len(text) else 'X'
if a == b:
transformed += a + "X"
i+=1
else:
transformed += a+b
i+=2
if len(transformed)%2 !=0:
transformed += 'X'
return transformed
def find_position(matrix , char):
for i in range(5):
for j in range(5):
if matrix[i][j] == char:
return i,j
return None
def find_encrypted_pair(a,b,matrix):
row1 , col1 = find_position(matrix , a)
row2, col2 = find_position(matrix , b)
if row1 == row2:
return matrix[row1][(col1+1)%5]+matrix[row2][(col2+1)%5]
elif col1 == col2:
return matrix[(row1+1)%5][col1] + matrix[(row2+1)%5][col2]
else:
return matrix[row1][col2] + matrix[row2][col1]
def playfair_encrypt(text , key):
matrix = generate_key_matrix(key)
text = transform(text)
encyrpyted = ""
for i in range(0 , len(text) , 2):
encyrpyted += find_encrypted_pair(text[i],text[i+1],matrix)
return encyrpyted
def find_decrypted_pair(a,b,matrix):
row1 , col1 = find_position(matrix , a)
row2, col2 = find_position(matrix , b)
if row1 == row2:
return matrix[row1][(col1-1)%5]+matrix[row2][(col2-1)%5]
elif col1 == col2:
return matrix[(row1-1)%5][col1] + matrix[(row2-1)%5][col2]
else:
return matrix[row1][col2] + matrix[row2][col1]
def playfair_decrypt(cipher , key):
matrix = generate_key_matrix(key)
decrypt = ""
for i in range(0 , len(cipher) , 2):
decrypt += find_decrypted_pair(cipher[i],cipher[i+1],matrix)
return decrypt
key = input('enter key')
plain_text = input('enter plaintext')
print(playfair_encrypt(plain_text , key))