0% found this document useful (0 votes)
59 views30 pages

Cypto File

Uploaded by

Swan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
59 views30 pages

Cypto File

Uploaded by

Swan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

S.

NO PROGRAM DATE REMARK

1 Program to find GCD of any two


numbers a and b mod n by Generalized
Euclidean Algorithm
2 Program to find Multiplicative Inverse of
b in Zp, p prime by Generalized
Euclidean Algorithm
3 Program to encrypt and decrypt by
Ceaser Cipher

4 Program to Encrypt and Decrypt by


Affine Cipher

5 Program to encrypt plaintext by Playfair


Cipher

6 Program to generate addition and


multiplication table for GF(22 ) Field
7 Program for key expansion algorithm of
DES

8 Program to implement 4*4 S-box and


perform two functionalities:
a.) Check given table of S-box and
inverse S-box are invertible to each
other.
b.) Ask the user to enter input to be
given in S-box and return its output.

9 Program to implement encryption and


decryption of RSA algorithm

INDEX
PROGRAM 1

Aim:- Program to find GCD of any two numbers a and b mod n by Generalized Euclidean
Algorithm

CODE:-
def extended_gcd(a, b):

if a == 0:

return b, 0, 1

else:

gcd, x, y = extended_gcd(b % a, a)

return gcd, y - (b // a) * x, x

def gcd_mod(a, b, n):

gcd, x, y = extended_gcd(a, b)

if gcd != 1:

return None # Modular inverse does not exist

else:

return (x % n + n) % n

a = int(input("Enter first number: "))

b = int(input("Enter second number: "))

n = int(input("Enter modulo value: "))

gcd_modulus = gcd_mod(a, b, n)

if gcd_modulus is None:

print("Modular inverse does not exist.")

else:
print("GCD of", a, "and", b, "modulo", n, "is", gcd_modulus)

OUTPUT:-
PROGRAM 2

AIM:- Program to find Multiplicative Inverse of b in Zp, p prime by Generalized


Euclidean Algorithm

CODE:-
def extended_gcd(a, b):

if a == 0:

return b, 0, 1

else:

gcd, x, y = extended_gcd(b % a, a)

return gcd, y - (b // a) * x, x

def multiplicative_inverse(b, p):

gcd, x, y = extended_gcd(b, p)

if gcd != 1:

return None # Multiplicative inverse does not exist

else:

return (x % p + p) % p

b = int(input("Enter the number: "))

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

inverse = multiplicative_inverse(b, p)

if inverse is None:

print("Multiplicative inverse does not exist.")

else:

print("Multiplicative inverse of", b, "in Z", p, "is", inverse)


OUTPUT:-
PROGRAM 3

AIM:- Program to encrypt and decrypt by Ceaser Cipher

CODE:-
def encrypt(text, shift):

result = ""

for char in text:

if char.isupper():

result += chr((ord(char) + shift - 65) % 26 + 65)

elif char.islower():

result += chr((ord(char) + shift - 97) % 26 + 97)

else:

result += char

return result

def decrypt(text, shift):

return encrypt(text, -shift)

text = input("Enter the message: ")

shift = int(input("Enter the shift value: "))

encrypted_text = encrypt(text, shift)

print("Encrypted message:", encrypted_text)

decrypted_text = decrypt(encrypted_text, shift)

print("Decrypted message:", decrypted_text)


OUTPUT:-
PROGRAM 4

AIM:- Program to Encrypt and Decrypt by Affine Cipher

CODE:-
def egcd(a, b):

if a == 0:

return (b, 0, 1)

else:

g, y, x = egcd(b % a, a)

return (g, x - (b // a) * y, y)

def modinv(a, m):

g, x, y = egcd(a, m)

if g != 1:

raise Exception('Modular inverse does not exist')

else:

return x % m

def encrypt(text, a, b):

result = ""

for char in text:

if char.isalpha():

if char.isupper():

result += chr((a * (ord(char) - 65) + b) % 26 + 65)

elif char.islower():

result += chr((a * (ord(char) - 97) + b) % 26 + 97)

else:
result += char

return result

def decrypt(text, a, b):

inv_a = modinv(a, 26)

result = ""

for char in text:

if char.isalpha():

if char.isupper():

result += chr((inv_a * (ord(char) - 65 - b)) % 26 + 65)

elif char.islower():

result += chr((inv_a * (ord(char) - 97 - b)) % 26 + 97)

else:

result += char

return result

text = input("Enter the message: ")

a = int(input("Enter the value of 'a' (must be coprime with 26): "))

b = int(input("Enter the value of 'b': "))

encrypted_text = encrypt(text, a, b)

print("Encrypted message:", encrypted_text)

decrypted_text = decrypt(encrypted_text, a, b)

print("Decrypted message:", decrypted_text)


OUTPUT:-
PROGRAM 5

AIM:- Program to encrypt plaintext by Playfair Cipher

CODE:-
def generate_key_square(key):

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

key_square = ""

for char in key:

if char not in key_square:

key_square += char

for i in range(65, 91):

if chr(i) not in key_square:

key_square += chr(i)

return key_square

def prepare_text(plaintext):

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

plaintext = plaintext.replace("J", "I")

prepared_text = ""

i=0

while i < len(plaintext):

prepared_text += plaintext[i]

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

prepared_text += "X"

i += 1

if len(prepared_text) % 2 != 0:

prepared_text += "X"
return prepared_text

def find_position(key_square, letter):

row = 0

col = 0

for i in range(5):

for j in range(5):

if key_square[5 * i + j] == letter:

row = i

col = j

break

return row, col

def encrypt(plaintext, key):

key_square = generate_key_square(key)

plaintext = prepare_text(plaintext)

ciphertext = ""

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

char1 = plaintext[i]

char2 = plaintext[i + 1]

row1, col1 = find_position(key_square, char1)

row2, col2 = find_position(key_square, char2)

if row1 == row2:

ciphertext += key_square[row1 * 5 + (col1 + 1) % 5]

ciphertext += key_square[row2 * 5 + (col2 + 1) % 5]

elif col1 == col2:

ciphertext += key_square[((row1 + 1) % 5) * 5 + col1]

ciphertext += key_square[((row2 + 1) % 5) * 5 + col2]

else:
ciphertext += key_square[row1 * 5 + col2]

ciphertext += key_square[row2 * 5 + col1]

return ciphertext

plaintext = input("Enter the plaintext: ")

key = input("Enter the key: ")

ciphertext = encrypt(plaintext, key)

print("Encrypted text:", ciphertext)

OUTPUT:-
PROGRAM 6

AIM:- Program to generate addition and multiplication table for GF(22 ) Field

CODE:-
def add_GF2(x, y):

return x ^ y

def mul_GF2(x, y):

result = 0

while y:

if y & 1:

result ^= x

y >>= 1

x <<= 1

if x & 0b100:

x ^= 0b101

return result

def generate_addition_table():

print("Addition Table for GF(2^2):")

print("| + | 0 | 1 | a | b |")

print("|---|----|----|----|----|")

for i in range(4):

print(f"| {format(i, 'x')} |", end=" ")

for j in range(4):

print(format(add_GF2(i, j), 'x').rjust(2), "|", end=" ")

print()
def generate_multiplication_table():

print("\nMultiplication Table for GF(2^2):")

print("| x | 0 | 1 | a | b |")

print("|---|----|----|----|----|")

for i in range(4):

print(f"| {format(i, 'x')} |", end=" ")

for j in range(4):

print(format(mul_GF2(i, j), 'x').rjust(2), "|", end=" ")

print()

generate_addition_table()

generate_multiplication_table()

OUTPUT:-
PROGRAM 7

AIM:- Program for key expansion algorithm of DES

CODE:-
def left_shift(key, bits):
shifted_key = (key << bits) & 0xFFFFFFFFFFFFFFFF
overflow = shifted_key >> 56
return (shifted_key | overflow) & 0xFFFFFFFFFFFFFFFF

def generate_subkeys(key):
# PC-1
pc1_table = [
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4
]

# PC-2
pc2_table = [
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
]

# Apply PC-1
key_permuted = 0
for i in range(56):
key_permuted |= (key >> (64 - pc1_table[i])) & 0x01
key_permuted <<= 1

key_permuted >>= 1

# Split key into left and right halves


c = (key_permuted >> 28) & 0x0FFFFFFF
d = key_permuted & 0x0FFFFFFF

subkeys = []
for i in range(16):
c = left_shift(c, 2 if i in [0, 1, 8, 15] else 1)
d = left_shift(d, 2 if i in [0, 1, 8, 15] else 1)
# Apply PC-2
subkey = 0
for j in range(48):
subkey |= ((c if j < 28 else d) >> (56 - pc2_table[j])) & 0x01
subkey <<= 1

subkey >>= 1
subkeys.append(subkey)

return subkeys

def main():
key = int(input("Enter the 64-bit key in hexadecimal: "), 16)

subkeys = generate_subkeys(key)

print("\nGenerated 16 Round Keys:")


for i, subkey in enumerate(subkeys):
print(f"Round {i + 1}: {format(subkey, '048b')} (hex: {format(subkey,
'012x')})")

if __name__ == "__main__":
main()
OUTPUT:-
PROGRAM 8

AIM:- Program to implement 4*4 S-box and perform two functionalities:


a.) Check given table of S-box and inverse S-box are invertible to each other.
b.) Ask the user to enter input to be given in S-box and return its output.

a.) Check given table of S-box and inverse S-box are invertible to each other.
CODE:-
def create_s_box():

s_box = [

[0x9, 0x4, 0xa, 0xb],

[0xd, 0x1, 0x8, 0x5],

[0x6, 0x2, 0x0, 0x3],

[0xc, 0xe, 0xf, 0x7]

return s_box

def create_inverse_s_box():

s_box = create_s_box()

inverse_s_box = [[0] * 4 for _ in range(4)]

for i in range(4):

for j in range(4):

inverse_s_box[s_box[i][j] >> 2][s_box[i][j] & 0x3] = i << 2 | j

return inverse_s_box

def check_invertibility(s_box, inverse_s_box):

for i in range(4):

for j in range(4):
if s_box[i][j] != inverse_s_box[i][j]:

return False

return True

def main():

s_box = create_s_box()

inverse_s_box = create_inverse_s_box()

print("S-box:")

for row in s_box:

print(row)

print("\nInverse S-box:")

for row in inverse_s_box:

print(row)

if check_invertibility(s_box, inverse_s_box):

print("\nThe given S-box and its inverse are invertible to each other.")

else:

print("\nThe given S-box and its inverse are not invertible to each other.")

if __name__ == "__main__":

main()
OUTPUT:-
B)Ask the user to enter input to be given in S-box and return its output.

CODE:-
# Define the S-box

s_box = [

[0b1100, 0b0000, 0b0011, 0b1111],

[0b1101, 0b0111, 0b1110, 0b0010],

[0b0001, 0b1010, 0b1000, 0b0100],

[0b0110, 0b1001, 0b0101, 0b1011]

def s_box_lookup(input):

row = (input & 0b1100) >> 2

col = input & 0b0011

return s_box[row][col]

def main():

input_value = int(input("Enter 4-bit input (in binary): "), 2)

output_value = s_box_lookup(input_value)

print("Output from S-box:", format(output_value, '04b'))

if __name__ == "__main__":

main()
OUTPUT:-
PROGRAM 9

AIM:- Program to implement encryption and decryption of RSA algorithm

CODE:-
import random
def is_prime(n, k=5):
if n <= 1:
return False
if n <= 3:
return True
for _ in range(k):
a = random.randint(2, n - 1)
if pow(a, n - 1, n) != 1:
return False
return True
def generate_prime(bits):
while True:
p = random.getrandbits(bits)
if is_prime(p):
return p
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def multiplicative_inverse(e, phi):
d=0
x1, x2 = 0, 1
y1, y2 = 1, 0
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 = y2 - temp1 * y1
x2 = x1
x1 = x
y2 = y1
y1 = y
if temp_phi == 1:
return y2 + phi

def generate_keypair(p, q):


n=p*q
phi = (p - 1) * (q - 1)
e = random.randrange(1, phi)
g = gcd(e, phi)
while g != 1:
e = random.randrange(1, phi)
g = gcd(e, phi)
d = multiplicative_inverse(e, phi)
return ((e, n), (d, n))
def encrypt(public_key, plaintext):
key, n = public_key
cipher = [pow(ord(char), key, n) for char in plaintext]
return cipher
def decrypt(private_key, ciphertext):
key, n = private_key
plain = [chr(pow(char, key, n)) for char in ciphertext]
return ''.join(plain)
def main():
# Generate two random prime numbers
p = generate_prime(64)
q = generate_prime(64)
# Generate public and private keys
public_key, private_key = generate_keypair(p, q)
print("Public Key:", public_key)
print("Private Key:", private_key)
# Input plaintext message
message = input("Enter the message to be encrypted: ")
# Encrypt the message
encrypted_message = encrypt(public_key, message)
print("Encrypted message:", encrypted_message)
# Decrypt the message
decrypted_message = decrypt(private_key, encrypted_message)
print("Decrypted message:", decrypted_message)
if __name__ == "__main__":
main()

OUTPUT:-

You might also like