0% found this document useful (0 votes)
18 views16 pages

In Spr Gms Revised Again

The document outlines various encryption algorithms including Caesar, Monoalphabetic, Diffie-Hellman, ECC, Vigenere, Feistel, Hill, Playfair, DES, and RSA. Each algorithm is presented with code snippets demonstrating encryption and decryption processes. The document serves as a comprehensive guide for understanding and implementing these cryptographic techniques.

Uploaded by

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

In Spr Gms Revised Again

The document outlines various encryption algorithms including Caesar, Monoalphabetic, Diffie-Hellman, ECC, Vigenere, Feistel, Hill, Playfair, DES, and RSA. Each algorithm is presented with code snippets demonstrating encryption and decryption processes. The document serves as a comprehensive guide for understanding and implementing these cryptographic techniques.

Uploaded by

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

1.

ceaser
def caesar_cipher(text, shift, encrypt=True):
result = ""
shift = shift if encrypt else -shift # Reverse shift for
decryption

for char in text:


if char.isalpha():
start = ord('A') if char.isupper() else ord('a')
# Adjust within the range of [0-25] for alphabets
result += chr((ord(char) - start + shift) % 26 + start)
else:
result += char # Keep non-alphabetic characters
unchanged

return result

# Example usage
text = "Hello, World!"
shift = 3

encrypted_text = caesar_cipher(text, shift, encrypt=True)


decrypted_text = caesar_cipher(encrypted_text, shift, encrypt=False)

print("Original Text:", text)


print("Encrypted Text:", encrypted_text)
print("Decrypted Text:", decrypted_text)

2.Monoalphabetic
def encrypt(a, dict1):
l = [] # Use a local list instead of a global variable
for x in a:
y = dict1.get(x, x) # If character not in dict, keep it
unchanged
l.append(y)
return "".join(l)

def decrypt(cipher_text, dict1):


# Reverse the dictionary for decryption
reverse_dict = {v: k for k, v in dict1.items()}
decrypted_text = []
for char in cipher_text:
decrypted_text.append(reverse_dict.get(char, char))
return "".join(decrypted_text)

# Monoalphabetic cipher mapping


dict2 = {
'A': 'Z', 'B': 'Y', 'C': 'X', 'D': 'W', 'E': 'V', 'F': 'U', 'G':
'T', 'H': 'S',
'I': 'R', 'J': 'Q', 'K': 'P', 'L': 'O', 'M': 'N', 'N': 'M', 'O':
'L', 'P': 'K',
'Q': 'J', 'R': 'I', 'S': 'H', 'T': 'G', 'U': 'F', 'V': 'E', 'W':
'D', 'X': 'C',
'Y': 'B', 'Z': 'A', 'a': 'z', 'b': 'y', 'c': 'x', 'd': 'w', 'e':
'v', 'f': 'u',
'g': 't', 'h': 's', 'i': 'r', 'j': 'q', 'k': 'p', 'l': 'o', 'm':
'n', 'n': 'm',
'o': 'l', 'p': 'k', 'q': 'j', 'r': 'i', 's': 'h', 't': 'g', 'u':
'f', 'v': 'e',
'w': 'd', 'x': 'c', 'y': 'b', 'z': 'a'
}

text = input("Enter a text: ")


cipher_text = encrypt(text, dict2)
print("\nEncrypting...")
print("Cipher text:", cipher_text)

print("\nDecrypting...")
decrypted_text = decrypt(cipher_text, dict2)
print("Decrypted text:", decrypted_text)

3.diffie helman

# Diffie-Hellman Key Exchange


q = int(input("Enter a prime number (q): "))
a = int(input("Enter a primitive root of q (a): "))

Xa = int(input("Enter the private key of A (Xa): "))


Xb = int(input("Enter the private key of B (Xb): "))

# Public keys
Ya = pow(a, Xa, q) # (a^Xa) % q
Yb = pow(a, Xb, q) # (a^Xb) % q

print("Public key of A (Ya):", Ya)


print("Public key of B (Yb):", Yb)

# Shared keys computed by both parties


Ka = pow(Yb, Xa, q) # (Yb^Xa) % q
Kb = pow(Ya, Xb, q) # (Ya^Xb) % q
print("Shared key for A (Ka):", Ka)
print("Shared key for B (Kb):", Kb)

# Verify if both shared keys match


if Ka == Kb:
print("The shared keys match! Secure communication established.
")
else:

print("Error: Shared keys do not match. ")

4. ECC
from tinyec import registry
import secrets

# Function to calculate compressed point of elliptic curves


def compress(publicKey):
return hex(publicKey.x) + hex(publicKey.y % 2)[2:]

# The elliptic curve used for ECDH calculations


curve = registry.get_curve('brainpoolP256r1')

# Generation of secret key and public key for User A


Ka = secrets.randbelow(curve.field.n)
X = Ka * curve.g
print("Public Key of User A (X):", compress(X))

# Generation of secret key and public key for User B


Kb = secrets.randbelow(curve.field.n)
Y = Kb * curve.g
print("Public Key of User B (Y):", compress(Y))

print("Currently exchanging the public keys (e.g., through the


Internet)")

# Computing shared keys


A_SharedKey = Ka * Y
print("Shared Key calculated by User A:", compress(A_SharedKey))

B_SharedKey = Kb * X
print("Shared Key calculated by User B:", compress(B_SharedKey))

# Checking if both shared keys match


print("Are the shared keys equal?", A_SharedKey == B_SharedKey)

5.Vignere

def vigenere_cipher(text, key, encryption=True):


result = ""
text = text.upper() # Ensure uppercase for simplicity
key = key.upper() # Ensure key is uppercase
key_length = len(key)

for i in range(len(text)):
if text[i].isalpha(): # Process only alphabetic characters
shift = ord(key[i % key_length]) - ord('A') # Shift
based on key
if encryption:
new_char = chr((ord(text[i]) - ord('A') + shift) % 26
+ ord('A'))
else:
new_char = chr((ord(text[i]) - ord('A') - shift) % 26
+ ord('A'))
result += new_char
else:
result += text[i] # Keep non-alphabetic characters
unchanged

return result

# Example Usage
plaintext = "HELLOVIGENERE"
key = "KEY"

# Encryption
ciphertext = vigenere_cipher(plaintext, key, encryption=True)
print("Ciphertext:", ciphertext)

# Decryption
decrypted_text = vigenere_cipher(ciphertext, key, encryption=False)
print("Decrypted Text:", decrypted_text)

part b

1.fiestel cipher
import random

def round_function(right, key):


return right ^ key

def feistel_encrypt(plain_text, keys):


left, right = plain_text
for key in keys:
temp = right
right = left ^ round_function(right, key)
left = temp
return left, right

def feistel_decrypt(cipher_text, keys):


left, right = cipher_text
for key in reversed(keys):
temp = left
left = right ^ round_function(left, key)
right = temp
return left, right

def generate_keys(num_rounds):
return [random.randint(0, 255) for _ in range(num_rounds)]

def text_to_pairs(text):
text_bytes = [ord(c) for c in text]
if len(text_bytes) % 2 != 0: # If odd length, pad with 0
text_bytes.append(0)
return [(text_bytes[i], text_bytes[i + 1]) for i in range(0,
len(text_bytes), 2)]

def pairs_to_text(pairs):
chars = [chr(num) for pair in pairs for num in pair if num != 0]
# Ignore padded zeros
return "".join(chars)

if __name__ == "__main__":
num_rounds = 4
keys = generate_keys(num_rounds)

text = "HELLO"
text_pairs = text_to_pairs(text)

encrypted_pairs = [feistel_encrypt(pair, keys) for pair in


text_pairs]
decrypted_pairs = [feistel_decrypt(pair, keys) for pair in
encrypted_pairs]

encrypted_text = pairs_to_text(encrypted_pairs)
decrypted_text = pairs_to_text(decrypted_pairs)

print("Original text: ", text)


print("Encrypted text:", encrypted_text)
print("Decrypted text:", decrypted_text)

2.hill cipher

def hill_cipher(text, key, decrypt=False):


from sympy import Matrix

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


n = len(key)

if decrypt:
key = Matrix(key).inv_mod(26)
key = [[int(key[row, col]) for col in range(n)] for row in
range(n)]
while len(text) % n != 0:
text += 'X' # Padding with 'X' if the text length is not a
multiple of key size

result = ""
for i in range(0, len(text), n):
block = [ord(c) - ord('A') for c in text[i:i + n]]
processed_block = [
sum(key[row][col] * block[col] for col in range(n)) % 26
for row in range(n)
]
result += ''.join(chr(num + ord('A')) for num in
processed_block)

return result

size = int(input("Enter the size of the key matrix (2 or 3): "))


key = [list(map(int, input(f"Enter row {i + 1}: ").split())) for i in
range(size)]
plaintext = input("Enter the plaintext: ")

ciphertext = hill_cipher(plaintext, key)


decrypted_text = hill_cipher(ciphertext, key, decrypt=True)

print("Plain text: ", plaintext)


print("Cipher text: ", ciphertext)
print("Decrypted text: ", decrypted_text)

3.Playfair
key = input("Enter a key: ")
key = key.upper()
keysAlready = []
mapper = {}
matrix = [[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0]]

i = 0
j = 0

# Key matrix creation


for ch in key:
if ch not in keysAlready:
matrix[i][j] = ch
mapper[ch] = (i, j)
keysAlready.append(ch)
j = (j + 1) % 5
if j == 0:
i += 1

for ascii_val in range(65, 91): # ASCII range for A-Z


ch = chr(ascii_val)
if ch not in keysAlready and ch != 'J': # Exclude 'J'
matrix[i][j] = ch
mapper[ch] = (i, j)
keysAlready.append(ch)
j = (j + 1) % 5
if j == 0:
i += 1

print("Key Matrix:")
for row in matrix:
print(row)

# Plaintext modification
plainText = input("Enter a plaintext: ")
plainText = plainText.upper().replace("J", "I") # Replace 'J' with
'I' if present

# Adjust plaintext to handle duplicate pairs


i = 0
while i < len(plainText) - 1:
if plainText[i] == plainText[i + 1]:
plainText = plainText[:i + 1] + "X" + plainText[i + 1:]
i += 2

if len(plainText) % 2 != 0:
plainText += "X"

print("Modified Plaintext:", plainText)

# Encryption
cipherText = ""
for i in range(0, len(plainText), 2):
char1, char2 = plainText[i], plainText[i + 1]
row1, col1 = mapper[char1]
row2, col2 = mapper[char2]
if row1 == row2: # Same row
cipherText += matrix[row1][(col1 + 1) % 5]
cipherText += matrix[row2][(col2 + 1) % 5]
elif col1 == col2: # Same column
cipherText += matrix[(row1 + 1) % 5][col1]
cipherText += matrix[(row2 + 1) % 5][col2]
else: # Rectangle swap
cipherText += matrix[row1][col2]
cipherText += matrix[row2][col1]

print("Ciphertext:", cipherText)

# Decryption
decryptedText = ""
for i in range(0, len(cipherText), 2):
char1, char2 = cipherText[i], cipherText[i + 1]
row1, col1 = mapper[char1]
row2, col2 = mapper[char2]

if row1 == row2: # Same row


decryptedText += matrix[row1][(col1 - 1) % 5]
decryptedText += matrix[row2][(col2 - 1) % 5]
elif col1 == col2: # Same column
decryptedText += matrix[(row1 - 1) % 5][col1]
decryptedText += matrix[(row2 - 1) % 5][col2]
else: # Rectangle swap
decryptedText += matrix[row1][col2]
decryptedText += matrix[row2][col1]

print("Decrypted Plaintext:", decryptedText)


4.DES

initial_key =
"00010110011010101101001001101010101111001111001111110011011101101"

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
]

key_rotation_schedule = [
1, 1, 2, 2, 2, 2, 2, 2,
1, 2, 2, 2, 2, 2, 2, 1
]

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
]

initial_key = [int(bit) for bit in initial_key]


key_halves = [initial_key[pc1_table[i] - 1] for i in range(56)]
c0, d0 = key_halves[:28], key_halves[28:]

subkeys = []
for i in range(16):
c0 = c0[key_rotation_schedule[i]:] +
c0[:key_rotation_schedule[i]]
d0 = d0[key_rotation_schedule[i]:] +
d0[:key_rotation_schedule[i]]
cd = c0 + d0
subkey = [cd[pc2_table[j] - 1] for j in range(48)]
subkeys.append(subkey)

for i, subkey in enumerate(subkeys):


print(f"Subkey {i + 1}: {''.join(map(str, subkey))}")

5.RSA
def gcd(a, b):
while b:
a, b = b, a % b
return a

def find_e(phi):
for i in range(2, phi):
if gcd(i, phi) == 1:
return i # Return the first valid e

def find_d(e, phi):


j = 1
while True:
if (j * e) % phi == 1:
return j # Return the corresponding d
j += 1

def RSA(p, q, msg):


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

# Find encryption key 'e'


e = find_e(phi)

# Find decryption key 'd'


d = find_d(e, phi)

print(f"\nEncryption Key (e): {e}")


print(f"Decryption Key (d): {d}")

# Encrypt the message using modular exponentiation


encrypted_msg = [pow(ord(char), e, n) for char in msg]
print(f"Encrypted message: {encrypted_msg}")

# Decrypt the message using modular exponentiation


decrypted_msg = ''.join([chr(pow(char, d, n)) for char in
encrypted_msg])
print(f"Decrypted message: {decrypted_msg}")

# Input from the user


p = int(input("Enter the value of p (prime): "))
q = int(input("Enter the value of q (prime): "))
msg = input("Enter a message (text): ")

RSA(p, q, msg)

You might also like