Crypto

Download as pdf or txt
Download as pdf or txt
You are on page 1of 13

1.

Playfair Cipher

def generate_key_matrix(key):

matrix = []

key = key.upper().replace("J", "I")

key_string = ''.join(sorted(set(key), key=key.index))

alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"

for char in alphabet:

if char not in key_string:

key_string += char

matrix = [list(key_string[i:i+5]) for i in range(0, 25, 5)]

return matrix

def format_message(message):

message = message.upper().replace("J", "I").replace(" ", "")

formatted_message = ""

i=0

while i < len(message):

formatted_message += message[i]

if i + 1 < len(message) and message[i] == message[i + 1]:

formatted_message += "X"

if i + 1 < len(message):

formatted_message += message[i + 1]

i += 2

if len(formatted_message) % 2 != 0:

formatted_message += "X"

return formatted_message

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 playfair_encrypt(key, message):

matrix = generate_key_matrix(key)

message = format_message(message)

cipher_text = ""

for i in range(0, len(message), 2):

row1, col1 = find_position(matrix, message[i])

row2, col2 = find_position(matrix, message[i + 1])

if row1 == row2:

cipher_text += matrix[row1][(col1 + 1) % 5] + matrix[row2][(col2 + 1) % 5]

elif col1 == col2:

cipher_text += matrix[(row1 + 1) % 5][col1] + matrix[(row2 + 1) % 5][col2]

else:

cipher_text += matrix[row1][col2] + matrix[row2][col1]

return cipher_text

key = input("Enter the Playfair Cipher key: ")

message = input("Enter the message to encrypt: ")

encrypted_message = playfair_encrypt(key, message)

print(f"Playfair Encrypted Message: {encrypted_message}")

2. Hill Cipher

import numpy as np

def create_matrix_of_integers_from_string(string, n):

string = string.upper().replace(" ", "")

integers = [ord(char) - 65 for char in string]

matrix = [integers[i:i + n] for i in range(0, len(integers), n)]

return matrix

def hill_encrypt(key, message):

n = int(len(key) ** 0.5)

key_matrix = create_matrix_of_integers_from_string(key, n)
message_matrix = create_matrix_of_integers_from_string(message, n)

encrypted_message = ""

for row in message_matrix:

row_vector = np.dot(key_matrix, row) % 26

encrypted_message += ''.join([chr(int(num) + 65) for num in row_vector])

return encrypted_message

key = input("Enter the Hill Cipher key (perfect square length): ")

message = input("Enter the message to encrypt (length should match key size): ")

encrypted_message = hill_encrypt(key, message)

print(f"Hill Encrypted Message: {encrypted_message}")

3. Vigenère Cipher

def vigenere_encrypt(plain_text, key):

plain_text = plain_text.upper().replace(" ", "")

key = key.upper()

cipher_text = ""

key_length = len(key)

key_as_int = [ord(i) for i in key]

plaintext_int = [ord(i) for i in plain_text]

for i in range(len(plain_text)):

value = (plaintext_int[i] + key_as_int[i % key_length]) % 26

cipher_text += chr(value + 65)

return cipher_text

message = input("Enter the message to encrypt: ")

key = input("Enter the Vigenère Cipher key: ")

encrypted_message = vigenere_encrypt(message, key)

print(f"Vigenère Encrypted Message: {encrypted_message}")

4. fast exponentiation modulo n.

def fast_exponentiation_modulo(base, exponent, mod):

result = 1

base = base % mod

while exponent > 0:


if exponent % 2 == 1:

result = (result * base) % mod

exponent = exponent // 2

base = (base * base) % mod

return result

base = int(input("Enter the base: "))

exponent = int(input("Enter the exponent: "))

mod = int(input("Enter the modulus: "))

result = fast_exponentiation_modulo(base, exponent, mod)

print(f"Result of {base}^{exponent} mod {mod} is: {result}")

5. S-box (DES)

def s_box_substitution(input_bits):

s_box = [

[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],

[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],

[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],

[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13]

row_bits = input_bits[0] + input_bits[5]

row = int(row_bits, 2)

col_bits = input_bits[1:5]

col = int(col_bits, 2)

s_box_value = s_box[row][col]

s_box_result = format(s_box_value, '04b')

return s_box_result

input_bits = input("Enter a 6-bit binary string: ")

if len(input_bits) != 6 or not all(bit in '01' for bit in input_bits):

print("Invalid input. Please enter a valid 6-bit binary string.")

else:

result = s_box_substitution(input_bits)

print(f"S-Box substitution result: {result}")

6. round key generation in S DES.

def apply_permutation(key, permutation_table):


return ''.join([key[i - 1] for i in permutation_table])

def left_shift(bits, shift_amount):

return bits[shift_amount:] + bits[:shift_amount]

def s_des_round_key_generation(key):

P10 = [3, 5, 2, 7, 4, 10, 1, 9, 8, 6]

P8 = [6, 3, 7, 4, 8, 5, 10, 9]

permuted_key = apply_permutation(key, P10)

left_half = permuted_key[:5]

right_half = permuted_key[5:]

left_half_ls1 = left_shift(left_half, 1)

right_half_ls1 = left_shift(right_half, 1)

combined_ls1 = left_half_ls1 + right_half_ls1

K1 = apply_permutation(combined_ls1, P8)

left_half_ls2 = left_shift(left_half_ls1, 2)

right_half_ls2 = left_shift(right_half_ls1, 2)

combined_ls2 = left_half_ls2 + right_half_ls2

K2 = apply_permutation(combined_ls2, P8)

return K1, K2

key = input("Enter a 10-bit binary key: ")

if len(key) != 10 or not all(bit in '01' for bit in key):

print("Invalid input. Please enter a valid 10-bit binary key.")

else:

K1, K2 = s_des_round_key_generation(key)

print(f"Round Key 1 (K1): {K1}")

print(f"Round Key 2 (K2): {K2}")

7. encryption and decryption in S-DES.

def apply_permutation(data, perm_table):

return ''.join([data[i - 1] for i in perm_table])

def xor(a, b):

return ''.join(['1' if a_bit != b_bit else '0' for a_bit, b_bit in zip(a, b)])

def s_box_substitution(expanded_half):

S0 = [[1, 0, 3, 2], [3, 2, 1, 0], [0, 2, 1, 3], [3, 1, 3, 2]]

S1 = [[0, 1, 2, 3], [2, 0, 1, 3], [3, 0, 1, 0], [2, 1, 0, 3]]


row0 = int(expanded_half[0] + expanded_half[3], 2)

col0 = int(expanded_half[1:3], 2)

s0_output = format(S0[row0][col0], '02b')

row1 = int(expanded_half[4] + expanded_half[7], 2)

col1 = int(expanded_half[5:7], 2)

s1_output = format(S1[row1][col1], '02b')

return s0_output + s1_output

def f_function(right_half, key):

ep_table = [4, 1, 2, 3, 2, 3, 4, 1]

ep_half = apply_permutation(right_half, ep_table)

xor_result = xor(ep_half, key)

s_box_result = s_box_substitution(xor_result)

p4_table = [2, 4, 3, 1]

p4_result = apply_permutation(s_box_result, p4_table)

return p4_result

def s_des_one_round(half_left, half_right, key):

f_output = f_function(half_right, key)

new_right = xor(half_left, f_output)

return half_right, new_right

def s_des_encrypt(plaintext, key1, key2):

ip_table = [2, 6, 3, 1, 4, 8, 5, 7]

ip_plaintext = apply_permutation(plaintext, ip_table)

left_half = ip_plaintext[:4]

right_half = ip_plaintext[4:]

left_half, right_half = s_des_one_round(left_half, right_half, key1)

left_half, right_half = right_half, left_half

left_half, right_half = s_des_one_round(left_half, right_half, key2)

combined = left_half + right_half

ip_inv_table = [4, 1, 3, 5, 7, 2, 8, 6]

ciphertext = apply_permutation(combined, ip_inv_table)

return ciphertext

def s_des_decrypt(ciphertext, key1, key2):

ip_table = [2, 6, 3, 1, 4, 8, 5, 7]
ip_ciphertext = apply_permutation(ciphertext, ip_table)

left_half = ip_ciphertext[:4]

right_half = ip_ciphertext[4:]

left_half, right_half = s_des_one_round(left_half, right_half, key2)

left_half, right_half = right_half, left_half

left_half, right_half = s_des_one_round(left_half, right_half, key1)

combined = left_half + right_half

ip_inv_table = [4, 1, 3, 5, 7, 2, 8, 6]

plaintext = apply_permutation(combined, ip_inv_table)

return plaintext

plaintext = "10101010"

key1 = "10100100"

key2 = "01010011"

ciphertext = s_des_encrypt(plaintext, key1, key2)

print(f"Ciphertext: {ciphertext}")

decrypted_text = s_des_decrypt(ciphertext, key1, key2)

print(f"Decrypted Text: {decrypted_text}")

8. RSA key generation.

def gcd(a, b):

while b:

a, b = b, a % b

return a

def mod_inverse(e, phi):

d_old, d_new = 0, 1

r_old, r_new = phi, e

while r_new != 0:

quotient = r_old // r_new

d_old, d_new = d_new, d_old - quotient * d_new

r_old, r_new = r_new, r_old - quotient * r_new

if r_old > 1:

raise Exception("No modular inverse found")

if d_old < 0:

d_old += phi
return d_old

p = int(input("Enter a prime number (p): "))

q = int(input("Enter another prime number (q): "))

n=p*q

print(f"n = {p} * {q} = {n}")

phi = (p - 1) * (q - 1)

print(f"φ(n) = ({p} - 1) * ({q} - 1) = {phi}")

while True:

e = int(input(f"Enter an integer e such that 1 < e < {phi} and gcd(e, {phi}) = 1: "))

if 1 < e < phi and gcd(e, phi) == 1:

break

else:

print(f"Invalid value for e. Make sure 1 < e < {phi} and gcd(e, {phi}) = 1.")

print(f"Public exponent e = {e}")

d = mod_inverse(e, phi)

print(f"Private exponent d = {d}")

public_key = (e, n) # Public Key (e, n)

private_key = (d, n) # Private Key (d, n)

print(f"Public Key PUK = {public_key}")

print(f"Private Key PRK = {private_key}")

9. RSA encryption and decryption

def gcd(a, b):

while b:

a, b = b, a % b

return a

def mod_inverse(e, phi):

d_old, d_new = 0, 1

r_old, r_new = phi, e

while r_new != 0:

quotient = r_old // r_new

d_old, d_new = d_new, d_old - quotient * d_new

r_old, r_new = r_new, r_old - quotient * r_new

if r_old > 1:
raise Exception("No modular inverse found")

if d_old < 0:

d_old += phi

return d_old

def generate_rsa_keys():

p = int(input("Enter a prime number (p): "))

q = int(input("Enter another prime number (q): "))

n=p*q

print(f"n = {p} * {q} = {n}")

phi = (p - 1) * (q - 1)

print(f"φ(n) = ({p} - 1) * ({q} - 1) = {phi}")

while True:

e = int(input(f"Enter an integer e such that 1 < e < {phi} and gcd(e, {phi}) = 1: "))

if 1 < e < phi and gcd(e, phi) == 1:

break

else:

print(f"Invalid value for e. Make sure 1 < e < {phi} and gcd(e, {phi}) = 1.")

print(f"Public exponent e = {e}")

d = mod_inverse(e, phi)

print(f"Private exponent d = {d}")

public_key = (e, n)

private_key = (d, n)

print(f"Public Key PUK = {public_key}")

print(f"Private Key PRK = {private_key}")

return public_key, private_key

def encrypt_message(message, public_key):

e, n = public_key

encrypted_message = [pow(ord(char), e, n) for char in message]

return encrypted_message

def decrypt_message(encrypted_message, private_key):

d, n = private_key

decrypted_message = ''.join([chr(pow(char, d, n)) for char in encrypted_message])

return decrypted_message
if __name__ == "__main__":

public_key, private_key = generate_rsa_keys()

message = input("Enter the message to encrypt: ")

encrypted_message = encrypt_message(message, public_key)

print(f"Encrypted message: {encrypted_message}")

decrypted_message = decrypt_message(encrypted_message, private_key)

print(f"Decrypted message: {decrypted_message}")

10. chosen ciphertext attacks on the RSA algorithm.

def gcd(a, b):

while b:

a, b = b, a % b

return a

def mod_inverse(e, phi):

d_old, d_new = 0, 1

r_old, r_new = phi, e

while r_new != 0:

quotient = r_old // r_new

d_old, d_new = d_new, d_old - quotient * d_new

r_old, r_new = r_new, r_old - quotient * r_new

if r_old > 1:

raise Exception("No modular inverse found")

if d_old < 0:

d_old += phi

return d_old

def generate_rsa_keys():

p = int(input("Enter a prime number (p): "))

q = int(input("Enter another prime number (q): "))

n=p*q

print(f"n = {p} * {q} = {n}")

phi = (p - 1) * (q - 1)

print(f"φ(n) = ({p} - 1) * ({q} - 1) = {phi}")

while True:

e = int(input(f"Enter an integer e such that 1 < e < {phi} and gcd(e, {phi}) = 1: "))
if 1 < e < phi and gcd(e, phi) == 1:

break

else:

print(f"Invalid value for e. Make sure 1 < e < {phi} and gcd(e, {phi}) = 1.")

print(f"Public exponent e = {e}")

d = mod_inverse(e, phi)

print(f"Private exponent d = {d}")

public_key = (e, n)

private_key = (d, n)

print(f"Public Key PUK = {public_key}")

print(f"Private Key PRK = {private_key}")

return public_key, private_key

def encrypt_message(message, public_key):

e, n = public_key

encrypted_message = [pow(ord(char), e, n) for char in message]

return encrypted_message

def decrypt_message(encrypted_message, private_key):

d, n = private_key

decrypted_message = ''.join([chr(pow(char, d, n)) for char in encrypted_message])

return decrypted_message

def chosen_ciphertext_attack(public_key, private_key, encrypted_message):

e, n = public_key

s = int(input("Attacker chooses a number s: "))

modified_ciphertext = [(s ** e * c) % n for c in encrypted_message]

print(f"Modified ciphertext: {modified_ciphertext}")

modified_plaintext = decrypt_message(modified_ciphertext, private_key)

print(f"Decrypted modified message (by victim): {modified_plaintext}")

original_plaintext = ''.join([chr((ord(char) * mod_inverse(s, n)) % n) for char in

modified_plaintext])

return original_plaintext

if __name__ == "__main__":

public_key, private_key = generate_rsa_keys()

message = input("Enter the message to encrypt: ")


encrypted_message = encrypt_message(message, public_key)

print(f"Encrypted message: {encrypted_message}")

recovered_message = chosen_ciphertext_attack(public_key, private_key,

encrypted_message)

print(f"Recovered original message: {recovered_message}")

11. Elgamal key generation, encryption and decryption.

import random

def mod_exp(base, exp, mod):

result = 1

while exp > 0:

if exp % 2 == 1:

result = (result * base) % mod

base = (base * base) % mod

exp = exp // 2

return result

def generate_large_prime():

primes = [17, 23, 47, 59, 61, 71, 89, 101, 103, 107]

return random.choice(primes)

def elgamal_key_generation():

p = generate_large_prime()

g = random.randint(2, p - 1)

x = random.randint(1, p - 2)

y = mod_exp(g, x, p)

public_key = (p, g, y)

private_key = x

print(f"Public Key: (p={p}, g={g}, y={y})")

print(f"Private Key: (x={x})")

return public_key, private_key

def elgamal_encrypt(message, public_key):

p, g, y = public_key

k = random.randint(1, p - 2)

c1 = mod_exp(g, k, p)

c2 = (message * mod_exp(y, k, p)) % p


ciphertext = (c1, c2)

print(f"Encrypted message (ciphertext): {ciphertext}")

return ciphertext

def elgamal_decrypt(ciphertext, private_key, p):

c1, c2 = ciphertext

x = private_key

s = mod_exp(c1, x, p)

s_inv = mod_exp(s, p - 2, p)

decrypted_message = (c2 * s_inv) % p

print(f"Decrypted message: {decrypted_message}")

return decrypted_message

if __name__ == "__main__":

public_key, private_key = elgamal_key_generation()

message = int(input(f"Enter the message to encrypt (an integer less than {public_key[0]}): "))

if message >= public_key[0]:

raise ValueError(f"The message must be less than {public_key[0]}.")

ciphertext = elgamal_encrypt(message, public_key)

decrypted_message = elgamal_decrypt(ciphertext, private_key, public_key[0])

You might also like