Index
S. Page Sign &
Name of program Date
No. no. Remarks
Write a python program to implement Caesar
1
Cipher.
Write a python program to implement Playfair
2
Cipher.
Write a python program to implement Hill
3
Cipher.
Write a python program to implement Vigenere
4
Cipher.
Write a python program to implement Rail
5
fence – row & Column Transformation.
Write a python program to implement RSA
6
Algorithm.
7 Write a python program to implement MD5.
8 Write a python program to implement SHA-1.
Write a python program to implement
9
Diffie-Hellman.
10 Write a python program to implement AES.
Program-01
Object: Write a python program to implement Caesar Cipher.
Algorithm:
STEP-1: Read the plain text from the user.
STEP-2: Read the key value from the user.
STEP-3: If the key is positive then encrypt the text by adding the key with each
character in the plain text.
STEP-4: Else subtract the key from the plain text.
STEP-5: Display the cipher text obtained above.
Code:
def main():
input_text = input("\n Enter the plain text:")
key = int(input("\n Enter the key value:"))
length = len(input_text)
print("\n \n \t INPUT TEXT:", input_text)
encrypted_text = ""
for i in range(length):
encrypted_char = chr(ord(input_text[i]) + key)
if input_text[i].isupper() and encrypted_char > 'Z':
encrypted_char = chr(ord(encrypted_char) - 26)
elif input_text[i].islower() and encrypted_char > 'z':
encrypted_char = chr(ord(encrypted_char) - 26)
encrypted_text += encrypted_char
print(encrypted_char, end="")
print("\n \n \t ENCRYPTED TEXT:", encrypted_text)
print("\n \n \t AFTER DECRYPTION : ", end="")
for i in range(length):
decrypted_char = chr(ord(encrypted_text[i]) - key)
if encrypted_text[i].isupper() and decrypted_char < 'A':
decrypted_char = chr(ord(decrypted_char) + 26)
elif encrypted_text[i].islower() and decrypted_char < 'a':
decrypted_char = chr(ord(decrypted_char) + 26)
print(decrypted_char, end="")
if __name__ == "__main__":
main()
Output:
Enter the plain text: World
Enter the key value: 2
INPUT TEXT: World
Yqtnf
ENCRYPTED TEXT: Yqtnf
AFTER DECRYPTION : World
Program-02
Object: Write a python program to implement Playfair Cipher.
Algorithm:
STEP-1: Read the plain text from the user.
STEP-2: Read the key value from the user.
STEP-3: Arrange the keyword without duplicates in a 5*5 matrix in the row order and
fill the remaining cells with missed out letters in alphabetical order. Note that ‘i’ and ‘j’
takes the same cell.
STEP-4: Group the plain text in pairs and match the corresponding corner letters by
forming a rectangular grid.
STEP-5: Display the cipher text obtained above.
Code:
def playfair_encrypt(char1, char2, key_matrix):
for i in range(5):
for j in range(5):
if char1 == key_matrix[i][j]:
row1, col1 = i, j
elif char2 == key_matrix[i][j]:
row2, col2 = i, j
if row1 == row2:
col1 = (col1 + 1) % 5
col2 = (col2 + 1) % 5
print(key_matrix[row1][col1] + key_matrix[row2][col2], end='')
elif col1 == col2:
row1 = (row1 + 1) % 5
row2 = (row2 + 1) % 5
print(key_matrix[row1][col1] + key_matrix[row2][col2], end='')
else:
print(key_matrix[row1][col2] + key_matrix[row2][col1], end='')
def main():
key_string = input("Enter key: ").upper().replace('J', 'I')
plaintext = input("Enter the plain text: ").upper().replace('J', 'I')
key_remaining = [ch for ch in "ABCDEFGHIKLMNOPQRSTUVWXYZ" if ch not
in key_string]
k=0
key_matrix = [['' for _ in range(5)] for _ in range(5)]
for i in range(5):
for j in range(5):
if k < len(key_string):
key_matrix[i][j] = key_string[k]
k += 1
else:
key_matrix[i][j] = key_remaining.pop(0)
print("\nEntered text:", plaintext)
print("Cipher Text:", end='')
for i in range(len(plaintext)):
if i + 1 == len(plaintext):
playfair_encrypt(plaintext[i], 'X', key_matrix)
else:
if plaintext[i] == plaintext[i + 1]:
playfair_encrypt(plaintext[i], 'X', key_matrix)
else:
playfair_encrypt(plaintext[i], plaintext[i + 1], key_matrix)
i += 1
if __name__ == "__main__":
main()
Output:
Enter key: 4
Enter the plain text: world
Entered text: WORLD
Cipher Text:YMMTQMOACY
Program-03
Object: Write a python program to implement Hill Cipher.
Algorithm-
STEP-1: Read the plain text and key from the user.
STEP-2: Split the plain text into groups of length three.
STEP-3: Arrange the keyword in a 3*3 matrix.
STEP-4: Multiply the two matrices to obtain the cipher text of length three.
STEP-5: Combine all these groups to get the complete cipher text.
Code:
def hill_cipher_encrypt(plain_text, encryption_matrix):
cipher_text = []
print("\nEncrypted Cipher Text:")
for i in range(0, len(plain_text), 3):
chunk = plain_text[i:i+3]
while len(chunk) < 3:
chunk += 'X' # Pad the last block with 'X' if needed
for j in range(3):
cipher_text.append(sum(encryption_matrix[j][k] * (ord(chunk[k]) - 65) for k in
range(3)) % 26)
print(chr(cipher_text[-1] + 65), end=' ')
return cipher_text
def hill_cipher_decrypt(cipher_text, decryption_matrix):
decrypted_text = []
print("\nDecrypted Cipher Text:")
for i in range(0, len(cipher_text), 3):
chunk = cipher_text[i:i+3]
for j in range(3):
decrypted_text.append(sum(decryption_matrix[j][k] * chunk[k] for k in
range(3)) % 26)
print(chr(decrypted_text[-1] + 65), end=' ')
def main():
encryption_matrix = [[6, 24, 1], [13, 16, 10], [20, 17, 15]]
decryption_matrix = [[8, 5, 10], [21, 8, 21], [21, 12, 8]]
print("Enter plain text:")
input_text = input().upper()
input_values = [ord(char) - 65 for char in input_text]
print("Input Values:")
for value in input_values:
print(value, end=' ')
cipher_text = hill_cipher_encrypt(input_text, encryption_matrix)
hill_cipher_decrypt(cipher_text, decryption_matrix)
if __name__ == "__main__":
main()
Output:
Enter plain text:
World
Input Values:
22 14 17 11 3
Encrypted Cipher Text:
R E X F F S
Decrypted Cipher Text:
W O R L D X
Program-04
Object: Write a python program to implement Vigenere Cipher.
Algorithm:
STEP-1: Arrange the alphabets in row and column of a 26*26 matrix.
STEP-2: Circulate the alphabets in each row to position left such that the first letter is
attached to last.
STEP-3: Repeat this process for all 26 rows and construct the final key matrix.
STEP-4: The keyword and the plain text is read from the user.
STEP-5: The characters in the keyword are repeated sequentially so as to match with
that of the plain text.
STEP-6: Pick the first letter of the plain text and that of the keyword as the row
indices and column indices respectively.
STEP-7: The junction character where these two meet forms the cipher character.
STEP-8: Repeat the above steps to generate the entire cipher text.
Code:
def vigenere_cipher(text, key, mode='encrypt'):
result = ''
key_length = len(key)
for i in range(len(text)):
char = text[i]
if char.isalpha():
shift = ord(key[i % key_length].upper()) - 65
if mode == 'decrypt':
shift = -shift
result += chr((ord(char.upper()) - 65 + shift) % 26 + 65)
else:
result += char
return result
def main():
print("Vigenere Cipher Demo")
plaintext = input("Enter the text: ")
key = input("Enter the key: ")
encrypted_text = vigenere_cipher(plaintext, key)
print(f"Encrypted Text: {encrypted_text}")
decrypted_text = vigenere_cipher(encrypted_text, key, mode='decrypt')
print(f"Decrypted Text: {decrypted_text}")
if __name__ == "__main__":
main()
Output:
Vigenere Cipher Demo
Enter the text: Word
Enter the key: 5
Encrypted Text: KCFR
Decrypted Text: WORD
Program-05
Object: Write a python program to implement Rail fence – row & Column Transformation.
Algorithm:
STEP-1: Read the plain text from the user.
STEP-2: Arrange the plain text in row columnar matrix format.
STEP-3: Now read the keyword depending on the number of columns of the plain text.
STEP-4: Arrange the characters of the keyword in sorted order and the corresponding
columns of the plain text.
STEP-5: Read the character’s row wise or column wise in the former order to get the
cipher text.
Code:
def rail_fence_cipher(input_string):
cipher_text = ""
# Encryption
for i in range(0, len(input_string), 2):
cipher_text += input_string[i]
for i in range(1, len(input_string), 2):
cipher_text += input_string[i]
return cipher_text
def rail_fence_decipher(cipher_text):
length = len(cipher_text)
# Calculate the number of rows in the rail fence
if length % 2 == 0:
num_rows = length // 2
else:
num_rows = (length // 2) + 1
# Decryption
decrypted_text = [''] * length
even_index = 0
odd_index = 1
for i in range(num_rows):
decrypted_text[even_index] = cipher_text[i]
even_index += 2
for i in range(num_rows, length):
decrypted_text[odd_index] = cipher_text[i]
odd_index += 2
return ''.join(decrypted_text)
def main():
input_string = input("\n\t\t RAIL FENCE TECHNIQUE\n\nEnter the input string: ")
# Encryption
cipher_text = rail_fence_cipher(input_string)
print("\nCipher text after applying rail fence:", cipher_text)
# Decryption
decrypted_text = rail_fence_decipher(cipher_text)
print("Text after decryption:", decrypted_text)
if __name__ == "__main__":
main()
Output:
RAIL FENCE TECHNIQUE
Enter the input string: World
Cipher text after applying rail fence: Wrdol
Text after decryption: World
Program-06
Object: Write a python program to implement RSA Algorithm.
Algorithm:
STEP-1: Select two co-prime numbers as p and q.
STEP-2: Compute n as the product of p and q.
STEP-3: Compute (p-1)*(q-1) and store it in z.
STEP-4: Select a random prime number e that is less than that of z.
STEP-5: Compute the private key, d as e * mod-1(z).
STEP-6: The cipher text is computed as message e * mod n.
STEP-7: Decryption is done as cipher d mod n.
Code:
import random
import math
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a
def mod_inverse(a, m):
m0, x0, x1 = m, 0, 1
while a > 1:
q = a // m
m, a = a % m, m
x0, x1 = x1 - q * x0, x0
return x1 + m0 if x1 < 0 else x1
def is_prime(num):
if num < 2:
return False
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def generate_keypair(p, q):
if not (is_prime(p) and is_prime(q)):
raise ValueError("Both numbers must be prime.")
elif p == q:
raise ValueError("p and q cannot be equal.")
n=p*q
phi = (p - 1) * (q - 1)
# Choose e such that 1 < e < phi and gcd(e, phi) = 1
e = random.randrange(2, phi)
while gcd(e, phi) != 1:
e = random.randrange(2, phi)
# Compute d, the modular inverse of e (mod phi)
d = mod_inverse(e, phi)
return ((e, n), (d, n))
def encrypt(public_key, plaintext):
e, n = public_key
cipher_text = [pow(ord(char), e, n) for char in plaintext]
return cipher_text
def decrypt(private_key, cipher_text):
d, n = private_key
decrypted_text = [chr(pow(char, d, n)) for char in cipher_text]
return ''.join(decrypted_text)
def main():
print("RSA Encryption and Decryption Demo")
# Choose two prime numbers
p = 61
q = 53
public_key, private_key = generate_keypair(p, q)
print(f"Public Key (e, n): {public_key}")
print(f"Private Key (d, n): {private_key}")
message = input("Enter a message to encrypt: ")
encrypted_message = encrypt(public_key, message)
print(f"Encrypted Message: {encrypted_message}")
decrypted_message = decrypt(private_key, encrypted_message)
print(f"Decrypted Message: {decrypted_message}")
if __name__ == "__main__":
main()
OUTPUT:
Enter a Prime number: 3
Enter another prime number: 7
Encryption keys are: 11, 21
Decryption keys are: 11, 21
Program-07
Object: Write a python program to implement MD5.
Algorithm:
STEP-1: Read the 128-bit plain text.
STEP-2: Divide into four blocks of 32-bits named as A, B, C and D.
STEP-3: Compute the functions f, g, h and i with operations such as, rotations,
permutations, etc.
STEP-4: The output of these functions are combined together as F and performed
circular shifting and then given to key round
STEP-5: Finally, right shift of ‘s’ times are performed and the results are combined
together to produce the final output.
Code:
import math
class MD5:
def __init__(self):
self.initial_hash_values = [0x67452301, 0xEFCDAB89, 0x98BADCFE,
0x10325476]
self.f_functions = [self.func0, self.func1, self.func2,
self.func3]
self.M = [1, 5, 3, 7]
self.O = [0, 1, 5, 0]
self.rotations_0 = [7, 12, 17, 22]
self.rotations_1 = [5, 9, 14, 20]
self.rotations_2 = [4, 11, 16, 23]
self.rotations_3 = [6, 10, 15, 21]
self.all_rotations = [self.rotations_0, self.rotations_1,
self.rotations_2, self.rotations_3]
self.k_space = [0] * 64
self.k = None
def is_prime(self, num):
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
return False
return True
def calculate_table(self, k_values):
power = pow(2, 32)
for i in range(64):
sin_value = abs(math.sin(1 + i))
k_values[i] = int(sin_value * power)
return k_values
def rotate_left(self, value, N):
mask1 = (1 << N) - 1
return ((value >> (32 - N)) & mask1) | ((value << N) & ~mask1)
def func0(self, abcd):
return (abcd[1] & abcd[2]) | (~abcd[1] & abcd[3])
def func1(self, abcd):
return (abcd[3] & abcd[1]) | (~abcd[3] & abcd[2])
def func2(self, abcd):
return abcd[1] ^ abcd[2] ^ abcd[3]
def func3(self, abcd):
return abcd[2] ^ (abcd[1] | ~abcd[3])
def md5(self, message):
h = self.initial_hash_values.copy()
message_length = len(message)
if self.k is None:
self.k = self.calculate_table(self.k_space)
groups = 1 + (message_length + 8) // 64
padded_message = bytearray(64 * groups)
padded_message[:message_length] = message.encode()
padded_message[message_length] = 0x80
q = message_length + 1
while q < 64 * groups:
padded_message[q] = 0
q += 1
w = 0
while w < 64 * groups:
block = bytearray(padded_message[w:w + 64])
abcd = h.copy()
for p in range(4):
function = self.f_functions[p]
rotations = self.all_rotations[p]
m = self.M[p]
o = self.O[p]
for q in range(16):
g = (m * q + o) % 16
f = abcd[1] + self.rotate_left(abcd[0] +
function(abcd) + self.k[q + 16 * p] + int.from_bytes(block[4 * g:4 * g +
4], 'little'), rotations[q % 4])
abcd[0], abcd[3], abcd[2], abcd[1] = abcd[3],
abcd[2], abcd[1], f
for p in range(4):
h[p] += abcd[p]
w += 64
return h
def md5_hexdigest(self, message):
digest = self.md5(message)
result = ''
for val in digest:
result += f'{val:02x}'
return result
def main():
md5_instance = MD5()
user_input = input()
hash_value = md5_instance.md5_hexdigest(user_input)
print(f"The MD5 code for input string is: 0x{hash_value.upper()}")
if __name__ == "__main__":
main()
OUTPUT:
Program-08
Object: Write a python program to implement SHA-1.
Algorithm:
STEP-1: Read the 256-bit key values.
STEP-2: Divide into five equal-sized blocks named A, B, C, D and E.
STEP-3: The blocks B, C and D are passed to the function F.
STEP-4: The resultant value is permuted with block E.
STEP-5: The block A is shifted right by ‘s’ times and permuted with the result of
step-4.
STEP-6: Then it is permuted with a weight value and then with some other key pair
and taken as the first block.
STEP-7: Block A is taken as the second block and the block B is shifted by ‘s’ times
and taken as the third block.
STEP-8: The blocks C and D are taken as the block D and E for the final output.
Code:
import hashlib
def sha1_hash(input_string):
sha1_hash_object = hashlib.sha1(input_string.encode())
return sha1_hash_object.hexdigest()
def main():
print("SHA-1 Hashing Demo")
input_text = input("Enter the text to hash using SHA-1: ")
sha1_result = sha1_hash(input_text)
print(f"SHA-1 Hash: {sha1_result}")
if __name__ == "__main__":
main()
Output:
SHA-1 Hashing Demo
Enter the text to hash using SHA-1: 7
SHA-1 Hash: 902ba3cda1883801594b6e1b452790cc53948fda
Program-09
Object: Write a python program to implement Diffie-Hellman.
Algorithm:
STEP-1: Both Alice and Bob shares the same public keys g and p.
STEP-2: Alice selects a random public key a.
STEP-3: Alice computes his secret key A as ga mod p.
STEP-4: Then Alice sends A to Bob.
STEP-5: Similarly Bob also selects a public key b and computes his secret key as B
and sends the same back to Alice.
STEP-6: Now both of them compute their common secret key as the other one’s secret
key power of a mod p.
Code:
def mod_exp(base, exp, mod):
result = 1
base = base % mod
while exp > 0:
if exp % 2 == 1:
result = (result * base) % mod
exp = exp // 2
base = (base * base) % mod
return result
def diffie_hellman(prime, primitive_root):
private_key_a = int(input("Enter private key for user A: "))
public_key_a = mod_exp(primitive_root, private_key_a, prime)
private_key_b = int(input("Enter private key for user B: "))
public_key_b = mod_exp(primitive_root, private_key_b, prime)
shared_key_a = mod_exp(public_key_b, private_key_a, prime)
shared_key_b = mod_exp(public_key_a, private_key_b, prime)
print(f"Public Key for User A: {public_key_a}")
print(f"Public Key for User B: {public_key_b}")
print(f"Shared Key for User A: {shared_key_a}")
print(f"Shared Key for User B: {shared_key_b}")
def main():
prime = int(input("Enter a prime number (shared prime): "))
primitive_root = int(input("Enter a primitive root modulo the prime: "))
diffie_hellman(prime, primitive_root)
if __name__ == "__main__":
main()
Output:
Enter a prime number (shared prime): 5
Enter a primitive root modulo the prime: 3
Enter private key for user A: 4
Enter private key for user B: 2
Public Key for User A: 1
Public Key for User B: 4
Shared Key for User A: 1
Shared Key for User B: 1
Program-10
Object: Write a python program to implement AES.
Algorithm:
STEP-1: Key Expansion: Generate round keys from the initial key using key schedule.
STEP-2: Initial Round: Add round key to input data.
STEP-3: Rounds: Perform substitution (SubBytes), permutation (ShiftRows), mixing
(MixColumns), and add round key for multiple rounds.
STEP-4: Final Round: Omit mixing step.
STEP-5: Output: Final encrypted data.
Code:
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import padding
def aes_encrypt(key, plaintext):
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
encryptor = cipher.encryptor()
# Perform PKCS7 padding
padder = padding.PKCS7(128).padder()
padded_data = padder.update(plaintext) + padder.finalize()
# Encrypt the padded data
ciphertext = encryptor.update(padded_data) + encryptor.finalize()
return ciphertext
def aes_decrypt(key, ciphertext):
backend = default_backend()
cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend)
decryptor = cipher.decryptor()
# Decrypt the ciphertext
padded_data = decryptor.update(ciphertext) + decryptor.finalize()
# Perform PKCS7 unpadding
unpadder = padding.PKCS7(128).unpadder()
plaintext = unpadder.update(padded_data) + unpadder.finalize()
return plaintext
def main():
key = b'Sixteen byte key' # 128-bit key
plaintext = b'This is a secret message'
# Encrypt
ciphertext = aes_encrypt(key, plaintext)
print(f'Encrypted Text: {ciphertext.hex()}')
# Decrypt
decrypted_text = aes_decrypt(key, ciphertext)
print(f'Decrypted Text: {decrypted_text.decode("utf-8")}')
if __name__ == "__main__":
main()
Output:
computer pc
Original value: computer pc
Encrypted value: beF17FXyKQdO0luQfezHQg==
Decrypted value: computer pc