DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING (CYBER SECURITY)
CRYPTANALYSIS LAB
Code- PC-CS-CYS-316LA
SUBMITTED TO: SUBMITTED BY:
Ms. Pooja Dahiya Sagar
Assistant Professor 2022025417
Department of CSE (Cyber Security) BTech CSE (CS)
Affiliated to KURUKSHETRA UNIVERSITY, KURUKSHETRA, INDIA
Page | 1
INDEX
[Link]. Experiment Page Date Signature
No.
1 Write a program to perform encryption and decryption 3-6
using the following algorithms: a) Ceaser Cipher
b) Substitution Cipher c) Hill Cipher
2 Implementation of various Stream Ciphers, such as, 7-9
additive cipher, multiplicative cipher, and affine cipher
with cryptanalysis.
3 Write a program to implement the DES and AES 10-12
algorithm logic.
4 Implementation of Euclidian’s algorithm, Chinese 13-16
reminder theorem, Primality test, Fermat’s algorithms,
Euler algorithm.
5 Write a program to implement the Blowfish algorithm. 17
6 Using Cryptography, encrypt the text “Hello world” 18
using Blowfish.
7 Create your own key using Java key tool. 19
8 Write a program to implement RSA Algorithm. 20-21
9 Implement the Diffie Hellman Key Exchange 22
mechanism using HTML and JavaScript.
10 Configure SSH (Secure Shell) and send/receive a file on 23-24
this connection to verify the correctness of this system
using the configured parameters.
Page | 2
EXPERIMENT-01
Aim: Write a program to perform encryption and decryption using the following algorithms:
a) Ceaser Cipher b) Substitution Cipher c) Hill Cipher
Code:
(a) Ceaser cipher
def encrypt_caesar(text,
shift): result = ""
for char in text:
if [Link]():
base = ord('A') if [Link]() else ord('a')
result += chr((ord(char) - base + shift) % 26 + base)
else:
result +=
char return result
def decrypt_caesar(text, shift):
return encrypt_caesar(text, -
shift)
# Step 1: Encryption
plain_text = input("Enter text to encrypt: ")
key = int(input("Enter shift key (0-25): "))
encrypted_text = encrypt_caesar(plain_text,
key) print("\nEncrypted Text:", encrypted_text)
# Step 2: Decryption
cipher_input = input("\nEnter text to decrypt: ")
decrypted_text = decrypt_caesar(cipher_input,
key) print("Decrypted Text:", decrypted_text)
Output:
Page | 3
(b) Substitution Cipher
import string
def encrypt_substitution(text, key_map):
result = ""
for char in text:
if [Link]():
is_upper = [Link]()
idx = ord([Link]()) -
ord('A') substitute =
key_map[idx]
result += [Link]() if is_upper else [Link]()
else:
result +=
char return result
def decrypt_substitution(text, key_map):
reverse_map = {v: chr(i + ord('A')) for i, v in enumerate(key_map)}
result = ""
for char in text:
if [Link]():
is_upper = [Link]()
original = reverse_map[[Link]()]
result += [Link]() if is_upper else [Link]()
else:
result +=
char return result
# Key: shufled alphabet (must be 26 characters long and unique)
substitution_key = "QWERTYUIOPASDFGHJKLZXCVBNM" # Example substitution
# Step 1: Encrypt
plain_text = input("Enter text to encrypt: ")
encrypted_text = encrypt_substitution(plain_text,
substitution_key) print("\nEncrypted Text:", encrypted_text)
# Step 2: Decrypt
Page | 4
cipher_input = input("\nEnter text to decrypt: ")
decrypted_text = decrypt_substitution(cipher_input,
substitution_key) print("Decrypted Text:", decrypted_text)
Output:
(c) Hill Cipher
import numpy as np
def mod_inverse(a,
m):
for i in range(1, m):
if (a * i) % m == 1:
return
i return -1
def encrypt_hill(text, key):
text = [Link]().replace(" ",
"") if len(text) % 2 != 0:
text += 'X'
nums = [ord(c) - 65 for c in text]
res = ''
for i in range(0, len(nums), 2):
vec = [Link](key, [nums[i], nums[i+1]]) % 26
res += ''.join(chr(n + 65) for n in vec)
return res
def decrypt_hill(text, key):
det = int([Link]([Link](key))) %
26 inv_det = mod_inverse(det, 26)
if inv_det == -1:
Page | 5
return "Key matrix not invertible"
key_inv = (inv_det * [Link]([Link](key) * det).astype(int)) % 26
return encrypt_hill(text, key_inv)
# Key matrix (must be invertible mod 26)
key_matrix = [Link]([[3, 3], [2, 5]])
# Step 1: Encrypt
plain = input("Enter text to encrypt: ")
cipher = encrypt_hill(plain,
key_matrix) print("\nEncrypted Text:",
cipher)
# Step 2: Decrypt
to_decrypt = input("\nEnter text to decrypt: ")
plain_back = decrypt_hill(to_decrypt,
key_matrix) print("Decrypted Text:", plain_back)
Output:
Page | 6
EXPERIMENT-02
Aim: Implementation of various Stream Ciphers, such as, additive cipher, multiplicative cipher, and
affine cipher with cryptanalysis.
Code:
(a) Additive Cipher (Shift Cipher)
plain = input("Enter your plaintext: ")
key = int(input("Enter your cipher key: "))
encrypted = ""
for char in plain:
if
[Link]():
shifted = (ord([Link]()) - 97 + key) % 26 + 97
encrypted += chr(shifted)
else:
encrypted += char
print("Encrypted text:", encrypted)
Output:
(b) Multiplicative Cipher
def mod_inverse(a,
m): for i in range(1,
m):
if (a * i) % m == 1:
return
i return -1
plain = input("Enter your plaintext: ")
key = int(input("Enter your cipher key:
")) if mod_inverse(key, 26) == -1:
Page | 7
print("Invalid key! No modular inverse exists for this key under mod 26.")
Page | 8
else:
encrypted = ""
for char in
plain:
if [Link]():
shifted = ((ord([Link]()) - 97) * key) % 26 + 97
encrypted += chr(shifted)
else:
encrypted += char
print("Encrypted text:", encrypted)
Output:
(c) Affine Cipher
def mod_inverse(a,
m): for i in range(1,
m):
if (a * i) % m == 1:
return
i return -1
plain = input("Enter your plaintext: ")
a = int(input("Enter the 'a' value (must be coprime with 26): "))
b = int(input("Enter the 'b' value: "))
if mod_inverse(a, 26) == -1:
print("Invalid 'a' value! It must be coprime with 26.")
else:
encrypted = ""
Page | 9
for char in
plain:
if [Link]():
Page | 10
shifted = (a * (ord([Link]()) - 97) + b) % 26 +
97 encrypted += chr(shifted)
else:
encrypted += char
print("Encrypted text:", encrypted)
Output:
Page | 11
EXPERIMENT-03
Aim: Write a program to implement the DES and AES algorithm logic.
Code:
(a) DES
from [Link] import DES
from [Link] import pad, unpad
from [Link] import
get_random_bytes import base64
# DES Encryption
def encrypt_des(plain_text, key):
cipher = [Link](key, DES.MODE_CBC)
padded_text = pad(plain_text.encode(),
DES.block_size) cipher_text =
[Link](padded_text)
return [Link] + cipher_text # return IV +
ciphertext # DES Decryption
def decrypt_des(encrypted,
key): iv = encrypted[:8]
cipher = [Link](key, DES.MODE_CBC, iv)
plain_text = unpad([Link](encrypted[8:]), DES.block_size)
return plain_text.decode()
# Input and Key Generation
plain_text = input("Enter text to encrypt using DES: ")
key = get_random_bytes(8)
# Encrypt
encrypted = encrypt_des(plain_text,
key) # Output in various formats
print("\n--- DES Output ---")
print("Raw Bytes :",
encrypted)
print("Hexadecimal :", [Link]())
Page | 12
print("Base64 :",
base64.b64encode(encrypted).decode()) # Decrypt
Page | 13
decrypted = decrypt_des(encrypted,
key) print("Decrypted Text :",
decrypted) Output:
(b) AES
from [Link] import AES
from [Link] import pad, unpad
from [Link] import
get_random_bytes import base64
# AES Encryption
def encrypt_aes(plain_text, key):
cipher = [Link](key, AES.MODE_CBC)
padded_text = pad(plain_text.encode(),
AES.block_size) cipher_text =
[Link](padded_text)
return [Link] + cipher_text # IV +
ciphertext # AES Decryption
def decrypt_aes(encrypted,
key): iv = encrypted[:16]
cipher = [Link](key, AES.MODE_CBC, iv)
plain_text = unpad([Link](encrypted[16:]),
AES.block_size) return plain_text.decode()
# Input and Key Generation
plain_text = input("Enter text to encrypt using AES: ")
key = get_random_bytes(16) # 16 bytes = 128-bit
key # Encrypt
encrypted = encrypt_aes(plain_text, key)
Page | 14
# Output in various formats
print("\n--- AES Output ---")
print("Raw Bytes :",
encrypted)
print("Hexadecimal :", [Link]())
print("Base64 :",
base64.b64encode(encrypted).decode()) # Decrypt
decrypted = decrypt_aes(encrypted,
key) print("Decrypted Text :",
decrypted) Output:
Page | 15
EXPERIMENT-04
Aim: Implementation of Euclidean’s algorithm, Chinese reminder theorem, Primality test, Fermat’s
algorithms, Euler algorithm.
Code:
(a) Euclidean’s Algorithm
def gcd(a, b):
while b:
a, b = b, a % b
return a
# Example usage
a = int(input("Enter first number (a): "))
b = int(input("Enter second number (b):
")) print("GCD of", a, "and", b, "is:", gcd(a,
b)) Output:
(b) Chinese Remainder Theorem
def chinese_remainder(n,
a): sum = 0
prod = 1
for ni in
n:
prod *= ni
for ni, ai in zip(n, a):
p = prod // ni
inv = pow(p, -1,
ni) sum += ai * inv
*p
return sum %
prod # Example
Page | 16
usage
Page | 17
n = [3, 5, 7]
a = [2, 3, 2]
print("Solution of CRT is:", chinese_remainder(n, a))
Output:
(c) Primality Test (Trial Division)
def
is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5)+1):
if n % i == 0:
return
False return
True
num = int(input("Enter number to test for primality: "))
print("Prime" if is_prime(num) else "Not Prime")
Output:
(d) Fermat’s Algorithm
def gcd(a, b):
while b:
a, b = b, a % b
return a
def fermat_mod_inverse(a,
p): if gcd(a, p) != 1:
return None # Inverse doesn't exist
# Fermat's Little Theorem: a^(p-2) ≡ a⁻¹ mod p
Page | 18
return pow(a, p - 2, p)
# Input
a = int(input("Enter value of a: "))
p = int(input("Enter a prime number p (modulus):
")) # Compute inverse
inverse = fermat_mod_inverse(a,
p) # Output
if inverse:
print(f"Modular inverse of {a} modulo {p} is: {inverse}")
else:
print(f"No modular inverse exists for {a} mod {p}"
output:
(e) Euler Algorithm
def gcd(a, b):
while b:
a, b = b, a % b
return a
def
euler_totient(n):
result = 0
for i in range(1, n):
if gcd(i, n) == 1:
result +=
1 return result
def euler_mod_inverse(a,
n): if gcd(a, n) != 1:
return None # Inverse does not exist
phi = euler_totient(n)
Page | 19
return pow(a, phi - 1, n)
# Input
a = int(input("Enter value of a: "))
n = int(input("Enter modulus n (not necessarily prime):
")) # Compute inverse
inverse = euler_mod_inverse(a,
n) # Output
if inverse:
print(f"Modular inverse of {a} modulo {n} using Euler's theorem is: {inverse}")
else:
print(f"No modular inverse exists for {a} mod {n}")
Output:
Page | 20
EXPERIMENT-05
Aim: Write a program to implement the Blowfish algorithm.
Code:
from [Link] import Blowfish
from [Link] import
get_random_bytes from [Link]
import pad, unpad
# Get input from user
plaintext = input("Enter the plaintext: ")
key = input("Enter the secret key (4–56 bytes):
").encode() # Blowfish requires key size between 4 and
56 bytes
if not (4 <= len(key) <= 56):
raise ValueError("Key must be between 4 and 56
bytes.") # Padding and encryption
cipher = [Link](key,
Blowfish.MODE_CBC) iv = [Link]
padded_text = pad([Link](),
Blowfish.block_size) ciphertext =
[Link](padded_text) print("\nEncrypted
ciphertext (hex):", [Link]())
# Decryption
decipher = [Link](key, Blowfish.MODE_CBC, iv)
decrypted_data = unpad([Link](ciphertext), Blowfish.block_size)
print("Decrypted plaintext:", decrypted_data.decode())
Output:
Page | 21
EXPERIMENT-06
Aim: Using Cryptography, encrypt the text “Hello world” using Blow Fish.
Code:
from [Link] import Blowfish
from [Link] import
pad # Fixed plaintext and key
plaintext = "Hello world"
key = b'mykey123' # Key must be 4 to 56
bytes # Blowfish encryption
cipher = [Link](key,
Blowfish.MODE_CBC) iv = [Link]
padded_text = pad([Link](),
Blowfish.block_size) ciphertext =
[Link](padded_text) print("Plaintext:", plaintext)
print("Encrypted (hex):", [Link]())
Output:
Page | 22
EXPERIMENT-07
Aim: Implementation of MD5.
Code:
import hashlib
# Input text to be hashed
input_text = input("Enter text to hash using MD5:
") # Creating MD5 hash object
md5_hash = hashlib.md5()
# Update the object with the input text encoded in UTF-
8 md5_hash.update(input_text.encode('utf-8'))
# Get the hexadecimal digest of the hash
hashed_text = md5_hash.hexdigest()
# Output the result
print("MD5 Hash of the input text is:", hashed_text)
Output:
Page | 23
EXPERIMENT-08
Aim: Write a program to implement RSA Algorithm.
Code:
import math
# Given primes p and q
p=3
q=7
# Compute n = p *
qn=p*q
print("n =", n)
# Compute the Euler's Totient (phi) function
phi = (p - 1) * (q - 1)
# Find e such that 1 < e < phi and gcd(e, phi) =
1e=2
while e < phi:
if [Link](e, phi) == 1:
break
else:
e += 1
print("e =", e)
# Choose a value for k and compute d (the modular multiplicative inverse of e modulo
phi) k = 2
d = ((k * phi) + 1) // e # Integer division to make sure it's an integer
print("d =", d)
# Print public and private keys
print(f'Public key: ({e}, {n})')
print(f'Private key: ({d}, {n})')
# Original message to be encrypted
msg = 11
print(f'Original message: {msg}')
# Encrypt the message using the public key (C = msg^e % n)
Page | 24
C = pow(msg, e, n)
print(f'Encrypted message: {C}')
# Decrypt the message using the private key (M = C^d % n)
M = pow(C, d, n)
print(f'Decrypted message: {M}')
Output:
Page | 25
EXPERIMENT-09
Aim: Implementation of SHA – 1.
Code:
import hashlib
# Input text to be hashed
input_text = input("Enter text to hash using SHA-1:
") # Creating SHA-1 hash object
sha1_hash = hashlib.sha1()
# Update the object with the input text encoded in UTF-
8 sha1_hash.update(input_text.encode('utf-8'))
# Get the hexadecimal digest of the hash
hashed_text = sha1_hash.hexdigest()
# Output the result
print("SHA-1 Hash of the input text is:", hashed_text)
Output:
Page | 26
EXPERIMENT-10
Aim: Create your own key with Diffie Hellman Key exchange mechanism.
Code:
# Function to compute power with modulo (g^a %
p) def power_mod(base, exp, mod):
return pow(base, exp, mod)
# Step 1: Public Parameters (Agreed upon prime number p and base
g) p = 23 # Example prime number
g = 5 # Example generator (base)
print(f"Public Parameters:\np = {p}\ng = {g}\
n") # Step 2: Private keys for Alice and Bob
# Private keys should be kept secret
a = 6 # Alice's private key
b = 15 # Bob's private key
# Step 3: Public keys computation
A = power_mod(g, a, p) # Alice's public key
B = power_mod(g, b, p) # Bob's public key
print(f"Alice's Public Key: A = {A}")
print(f"Bob's Public Key: B = {B}")
# Step 4: Shared secret computation
# Alice computes shared secret using Bob's public key
alice_shared_secret = power_mod(B, a, p)
# Bob computes shared secret using Alice's public key
bob_shared_secret = power_mod(A, b, p)
# Step 5: Output the shared secret
print(f"Alice's Shared Secret:
{alice_shared_secret}") print(f"Bob's Shared Secret:
{bob_shared_secret}") # Check if both computed
the same shared secret
if alice_shared_secret == bob_shared_secret:
print("\nThe key exchange is successful! Shared secret:",
Page | 27
alice_shared_secret) else:
Page | 28
print("\nThe key exchange
failed.") output:
Page | 29