OneCompiler

popo

131

AES
from cryptography.fernet import Fernet

Step 1: Generate a key (do this once and save it securely)

key = Fernet.generate_key()
print("Secret Key:", key.decode()) # Share this key securely with the server

Step 2: Create a Fernet object

cipher = Fernet(key)

Step 3: Sample attendance data

attendance_data = "StudentID: 202501, Present: 5, Absent: 2"
print("Original Data:", attendance_data)

Step 4: Encrypt the data

encrypted_data = cipher.encrypt(attendance_data.encode())
print("Encrypted Data:", encrypted_data.decode())

Step 5: Decrypt the data

decrypted_data = cipher.decrypt(encrypted_data).decode()
print("Decrypted Data:", decrypted_data)

DES
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
import binascii

Generate RSA keys

key = RSA.generate(2048)
private_key = key.export_key()
public_key = key.publickey().export_key()

print("🔑 Private Key:")
print(private_key.decode())
print("🔓 Public Key:")
print(public_key.decode())

Encrypt message

message = "Hello RSA Encryption!"
recipient_key = RSA.import_key(public_key)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
encrypted_message = cipher_rsa.encrypt(message.encode())
print("🔒 Encrypted Message (Hex):")
print(binascii.hexlify(encrypted_message))

Decrypt message

private_key_import = RSA.import_key(private_key)
decrypt_cipher = PKCS1_OAEP.new(private_key_import)
decrypted_message = decrypt_cipher.decrypt(encrypted_message)
print("✅ Decrypted Message:")
print(decrypted_message.decode())

CAESAR
def encrypt(text, shift):
encrypted = ""
for char in text:
if char.isalpha():
base = ord('A')
encrypted_char = chr((ord(char) - base + shift) % 26 + base)
elif char.isdigit():
base = ord('0')
encrypted_char = chr((ord(char) - base + shift) % 10 + base)
else:
encrypted_char = char
encrypted += encrypted_char
return encrypted

text = "STD12345"
shift = 5
encrypted_ans = encrypt(text, shift)
print(encrypted_ans)

playfair
def generate_matrix(key):
key = key.upper().replace('I', 'J') # Fix to update the key
result = []
for char in key:
if char not in result and char.isalpha():
result.append(char)
for char in "ABCDEFGHIKLMNOPQRSTUVWXYZ":
if char not in result:
result.append(char)
matrix = [result[i:i+5] for i in range(0, 25, 5)] # Fix variable name from matix to matrix
return matrix

def find_position(matrix, char):
for i in range(5):
for j in range(5): # Fix inner loop variable from i to j
if matrix[i][j] == char:
return i, j

def prepare_text(text):
text = text.upper().replace('I', 'J').replace(" ", "")
prepared = ""
i = 0
while i < len(text):
a = text[i]
if i + 1 < len(text): # Ensure we don't go out of bounds
b = text[i+1]
else:
b = 'X' # Add 'X' if odd number of characters
if a == b:
prepared += a + 'X'
i += 1
else:
prepared += a + b
i += 2
if len(prepared) % 2 != 0:
prepared += 'X' # Make sure the text length is even
return prepared

def encrypt_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 decrypt_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 encrypt(text, key):
matrix = generate_matrix(key)
text = prepare_text(text)
result = ""
for i in range(0, len(text), 2):
result += encrypt_pair(text[i], text[i+1], matrix)
return result

def decrypt(text, key):
matrix = generate_matrix(key)
result = ""
for i in range(0, len(text), 2):
result += decrypt_pair(text[i], text[i+1], matrix)
return result

Example usage

key = "monarchy"
plaintext = "hello world"
ciphertext = encrypt(plaintext, key)
decrypted = decrypt(ciphertext, key)

print("Plaintext :", plaintext)
print("Ciphertext:", ciphertext)
print("Decrypted :", decrypted)

hilfair
import numpy as np

Convert character to number (A=0, B=1, ..., Z=25)

def char_to_num(c):
return ord(c.upper()) - ord('A')

Convert number back to character

def num_to_char(n):
return chr(int(n % 26) + ord('A'))

Create matrix from text

def create_matrix(text, size):
nums = [char_to_num(c) for c in text]
while len(nums) % size != 0:
nums.append(char_to_num('X')) # Padding with 'X'
return np.array(nums).reshape(-1, size)

Encrypt

def encrypt(plaintext, key_matrix):
size = key_matrix.shape[0]
text_matrix = create_matrix(plaintext, size)
encrypted = np.dot(text_matrix, key_matrix) % 26
return ''.join(num_to_char(n) for row in encrypted for n in row)

Modular inverse of matrix

def matrix_mod_inv(matrix, mod):
det = int(np.round(np.linalg.det(matrix)))
det_inv = pow(det, -1, mod)
matrix_adj = np.round(det * np.linalg.inv(matrix)).astype(int)
return (det_inv * matrix_adj) % mod

Decrypt

def decrypt(ciphertext, key_matrix):
size = key_matrix.shape[0]
cipher_matrix = create_matrix(ciphertext, size)
key_inv = matrix_mod_inv(key_matrix, 26)
decrypted = np.dot(cipher_matrix, key_inv) % 26
return ''.join(num_to_char(n) for row in decrypted for n in row)

Example Usage

key = np.array([[3, 3], [2, 5]]) # Make sure this matrix is invertible mod 26
plaintext = "HELLO"

encrypted_text = encrypt(plaintext, key)
print("Encrypted:", encrypted_text)

decrypted_text = decrypt(encrypted_text, key)
print("Decrypted:", decrypted_text)

railfence
def encrypt_rail_fence(text, key):
rail = [['\n' for _ in range(len(text))] for _ in range(key)]

dir_down = False
row, col = 0, 0

for char in text:
    # Check the direction
    if row == 0 or row == key - 1:
        dir_down = not dir_down

    rail[row][col] = char
    col += 1

    row += 1 if dir_down else -1

# Collect encrypted text
result = []
for i in range(key):
    for j in range(len(text)):
        if rail[i][j] != '\n':
            result.append(rail[i][j])
return "".join(result)

def decrypt_rail_fence(cipher, key):
rail = [['\n' for _ in range(len(cipher))] for _ in range(key)]

# Mark positions with '*'
dir_down = None
row, col = 0, 0

for _ in range(len(cipher)):
    if row == 0:
        dir_down = True
    if row == key - 1:
        dir_down = False

    rail[row][col] = '*'
    col += 1
    row += 1 if dir_down else -1

# Fill in the characters
index = 0
for i in range(key):
    for j in range(len(cipher)):
        if rail[i][j] == '*' and index < len(cipher):
            rail[i][j] = cipher[index]
            index += 1

# Read the matrix in zigzag
result = []
row, col = 0, 0
for _ in range(len(cipher)):
    if row == 0:
        dir_down = True
    if row == key - 1:
        dir_down = False

    if rail[row][col] != '\n':
        result.append(rail[row][col])
        col += 1

    row += 1 if dir_down else -1

return "".join(result)

🔄 Example usage

plain_text = "HELLOPYTHON"
key = 3

encrypted = encrypt_rail_fence(plain_text, key)
print("Encrypted:", encrypted)

decrypted = decrypt_rail_fence(encrypted, key)
print("Decrypted:", decrypted)

rsa
import random

Function to compute GCD

def gcd(a, b):
while b != 0:
a, b = b, a % b
return a

Function to find modular inverse

def mod_inverse(e, phi):
for d in range(1, phi):
if (d * e) % phi == 1:
return d
return None

Function to generate RSA keys

def generate_keys():
# For simplicity, using small primes
p = 17
q = 23
n = p * q
phi = (p - 1) * (q - 1)

# Choose e
e = 3
while gcd(e, phi) != 1:
    e += 2  # Try next odd number

# Compute d
d = mod_inverse(e, phi)
return ((e, n), (d, n))  # public and private keys

Encryption function

def encrypt(msg, public_key):
e, n = public_key
cipher = [(ord(char) ** e) % n for char in msg]
return cipher

Decryption function

def decrypt(cipher, private_key):
d, n = private_key
plain = [chr((char ** d) % n) for char in cipher]
return ''.join(plain)

▶️ Example usage

public, private = generate_keys()
message = "HELLO"
print("Original:", message)

encrypted_msg = encrypt(message, public)
print("Encrypted:", encrypted_msg)

decrypted_msg = decrypt(encrypted_msg, private)
print("Decrypted:", decrypted_msg)

single columnardef single_columnar_encrypt(plaintext, key):
# Remove spaces and convert to uppercase
plaintext = plaintext.replace(" ", "").upper()
num_cols = len(key)
num_rows = -(-len(plaintext) // num_cols) # Ceiling division

# Fill the matrix row-wise
matrix = [['' for _ in range(num_cols)] for _ in range(num_rows)]
k = 0
for i in range(num_rows):
    for j in range(num_cols):
        if k < len(plaintext):
            matrix[i][j] = plaintext[k]
            k += 1

# Read the matrix column-wise in the order of key
sorted_key = sorted(list(key))
ciphertext = ''
for ch in sorted_key:
    col_idx = key.index(ch)
    for row in matrix:
        if row[col_idx] != '':
            ciphertext += row[col_idx]
return ciphertext

double columnar
def double_columnar_encrypt(plaintext, key1, key2):
# First columnar encryption
first_pass = single_columnar_encrypt(plaintext, key1)
# Second columnar encryption
second_pass = single_columnar_encrypt(first_pass, key2)
return second_pass