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

A5/1 CIPHER

import random

def generate_random_key(bits):
random_key = "".join(str(random.randint(0, 1)) for _ in range(bits))
return random_key

class A51Cipher:
def __init__(self, key, frame):
self.state = [0] * 64
self.frame = frame
self.load_key(key)

def load_key(self, key):


for i, bit in enumerate(key):
self.state[i] = int(bit)

def majority(self, x, y, z):


return (x & y) ^ (x & z) ^ (y & z)

def clock(self, register, mask):


majority_bit = self.majority(register[8], register[10], register[10])
new_bit = register[mask[0]] ^ majority_bit
for i in range(len(register) - 1, 0, -1):
register[i] = register[i - 1]
register[0] = new_bit

def step(self):
clocking_bit = self.state[8] ^ self.state[10] ^ self.state[10]
if self.state[0] == clocking_bit:
self.clock(self.state, [13, 16, 17, 18])
if self.state[1] == clocking_bit:
self.clock(self.state, [20, 21])
if self.state[2] == clocking_bit:
self.clock(self.state, [7, 20, 21])

def generate_keystream(self, length):


keystream = []
for _ in range(length):
self.step()
output_bit = self.state[18] ^ self.state[21] ^ self.state[22]
keystream.append(output_bit)
return keystream

def encrypt(self, plaintext):


keystream = self.generate_keystream(len(plaintext))
ciphertext = [str(int(plaintext[i]) ^ keystream[i]) for i in
range(len(plaintext))]
return ''.join(ciphertext)

session_key = generate_random_key(64)
frame = "1001001010110100010"
plaintext = "0101010101010101"
cipher = A51Cipher(session_key, frame)
ciphertext = cipher.encrypt(plaintext)
print("Session Key:", session_key)
print("Plaintext:", plaintext)
print("Ciphertext:", ciphertext)
VIGENERE CIPHER

def encrypt(p,key):
val = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for i,char in enumerate(p):
char = p[i]
if char.isalpha():
shift = val.index(key[i%len(key)])
index = val.index(char)
encrypted_index = (index+shift)%26
encrypted_char = val[encrypted_index]
encrypted += encrypted_char
else:
encrypted += char
return encrypted

def decrypt(p,key):
val = 'abcdefghijklmnopqrstuvwxyz'
decrypted = ''
for i,char in enumerate(p):
if char.isalpha():
shift = val.index(key[i%len(key)])
index = val.index(char)
decrypted_index = (index-shift)%26
decrypted_char = val[decrypted_index]
decrypted += decrypted_char
else:
decrypted += char
return decrypted

if __name__ == '__main__':
plaintext = 'attack'
key = 'butter'
x = encrypt(plaintext,key)
print(x)
print(decrypt(x,key))
ADDITIVE CIPHER
p: plaintext ; k: key

Encryption (c) = (p+k)mod26


Decryption (d) = (c-k)mod26

SERVER.py
import socket

def encrypt(p,key):
val = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for char in p:
if char.isalpha():
index = (val.index(char) + key) % 26
encrypted += val[index]
else:
index += char

return encrypted

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket Created")

port = 12345
s.bind(('',port))
print(f"Socket binded to {port}")
s.listen(1)
print("Socket is listening")

c, addr = s.accept()
print(str(addr))

txt = input("Enter plaintext: ")


key = int(input("Enter Key: "))
encryption = encrypt(txt,key)
c.sendall(encryption.encode())
c.close()
CLIENT.py
import socket
def decrypt(p,key):
val = 'abcdefghijklmnopqrstuvwxyz'
decrypted = ''
for char in p:
if char.isalpha():
index = (val.index(char) - key) % 26
decrypted += val[index]
else:
decrypted += char
return decrypted

host = 'localhost'
port = 12345

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',port))

msg = s.recv(1024)

while msg:
key = int(input('Enter Key: '))
print('Received: ' + decrypt(msg.decode(),key))
msg = s.recv(1024)
s.close()
MULTIPLICATIVE CIPHER
p: plaintext ; k: key

Encryption (c) = (p*k)mod26


-1
Decryption (d) = (c*k )mod26

SERVER.py
import socket

def encrypt(p,key):
val = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for char in p:
if char.isalpha():
index = (val.index(char) * key) % 26
encrypted += val[index]
else:
encrypted += char

return encrypted

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print("Socket Created")

port = 12345
s.bind(('',port))
print(f"Socket binded to {port}")
s.listen(1)
print("Socket is listening")

c, addr = s.accept()
print(str(addr))

txt = input("Enter plaintext: ")


key = int(input("Enter Key: "))
encryption = encrypt(txt,key)
c.sendall(encryption.encode())
c.close()

CLIENT.py
import socket

def mod_inv(k,key):
k = k % key
for x in range(1,key):
if (k*x) % key == 1:
return x
return -1

def decrypt(p, key):


val = 'abcdefghijklmnopqrstuvwxyz'
decrypted = ''

n = mod_inv(key,26)
for char in p:
if char.isalpha():
index = (val.index(char) * n) % 26
decrypted += val[index]
else:
decrypted += char

return decrypted

host = 'localhost'
port = 12345

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('127.0.0.1',port))

msg = s.recv(1024)

while msg:
key = int(input('Enter Key: '))
print('Received: ' + decrypt(msg.decode(),key))
msg = s.recv(1024)
s.close()
RSA
p,q : large prime numbers (13,17) ; n = p*q ; phi = (p-1)(q-1) ; (e, n) : public key ;
ed = 1 mod phi ; (d, n) : private key

Encryption (c) = M^e mod n


Decryption (M) = c^d mod n

SERVER.py
import math
import socket

with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as server_socket:


server_socket.bind(('127.0.0.1', 12345))
server_socket.listen()
print('Server listening')
client,adr = server_socket.accept()
print("Connected to ", adr)
received_keys = client.recv(1024).decode().split()
e,n = map(int, received_keys)
print("Public Keys (e,n): ", e,n)
message = 124
c = pow(message,e,n)
c_str = str(c)
client.send(c_str.encode())
print("Sent Encrypted Text: ", c_str)
CLIENT.py
import math
import socket

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

def mod(a,m):
for i in range(1,m):
if (a*i) % m == 1:
return i
return None

p = 13
q = 17
n = p*q
e = 2
phi = (p-1)*(q-1)

while (1<e and e<phi):


if gcd(e,phi) == 1:
break
e+=1

with socket.socket(socket.AF_INET,socket.SOCK_STREAM) as client_socket:


client_socket.connect(('127.0.0.1', 12345))
keys = f'{e} {n}'
client_socket.send(keys.encode())

encrypted_bytes = client_socket.recv(1024)
encrypted = int(encrypted_bytes.decode())
print("Encrypted Text: ", encrypted)

d = mod(e,phi)
m = pow(encrypted,d,n)
print("Decrypted Text: ", m)
DIFFIE-HELLMAN
A. Client/Sender
1. Choose a large prime number p
2. Calculate generator g of p
3. Share p and g with the Server/Receiver
4. Select any natural number (client secrete) a
5. Calculate RA = g
a mod p and send it to the Server/Receiver
a
6. Upon receiving RB from the Server/Receiver, calculate shared key KAB = (RB ) mod p
B. Server/Receiver:
1. Select any natural number (server secrete) b
2. Upon receiving p and g, calculate RB = b
a mod p and send it to the Client/Sender
b
3. Upon receiving RA from the Client/Sender, calculate shared key KAB = (RA ) mod p

SERVER.py
import socket
import random
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server_socket:
server_socket.bind(('127.0.0.1', 12344))
server_socket.listen()
print("Server Listening")
client_socket, client_address = server_socket.accept()
print("Connected to: ", client_address)

p_g = client_socket.recv(1024).decode().split()
p, g = map(int, p_g)

b = random.randint(1, p - 1)
RB = pow(g, b, p)
RA = client_socket.recv(1024).decode()

str_RB = str(RB)
client_socket.send(str_RB.encode())

KAB = pow(int(RA), b, p)
print("KAB:", KAB)
except Exception as e:
print(f"Server error: {e}")
CLIENT.py
import socket
import random
import time
try:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect(('127.0.0.1', 12344))
p = 23
g = random.randint(2, p - 1)
p_g = f'{p} {g}'
client_socket.send(p_g.encode())
a = random.randint(1, p - 1)

RA = pow(g, a, p)
str_RA = str(RA)
time.sleep(3)

client_socket.send(str_RA.encode())
RB = client_socket.recv(1024).decode()

KAB = pow(int(RB), a, p)
print("KAB:", KAB)

except Exception as e:
print(f"Client error: {e}")
MAC (Message Authentication Code)
- Take input of Message, Block_Size, Key, IV
- Check Message, Key and IV are digits
- Add Padding to message ( Block_Size - (len(message) % block_size)
- Calculate Num_blocks and iterate it to find all blocks
- Nested iteration for finding mac. Temp += str(int(mac[j]) ^ int(block[j])

def cbc_mac():
msg = input("Enter a message: ")
block_size = int(input("Enter a block size: "))
key = input("Enter a key: ")
IV = input("Enter an IV: ")
if not msg.isdigit() or not key.isdigit() or not IV.isdigit():
print("Error: Message, key, and IV should contain only numeric characters.")
return
if len(msg) % block_size != 0:
pad = block_size - (len(msg) % block_size)
msg += '0' * pad
print("Padded Message:", msg)
num_blocks = len(msg) // block_size
mac = IV
for i in range(num_blocks):
start_index = i * block_size
end_index = (i + 1) * block_size
block = msg[start_index:end_index]
temp = ""
for j in range(block_size):
temp += str(int(mac[j]) ^ int(block[j]))
mac = temp
print("CBC-MAC:", mac)
Challenge Response Protocol
BOB (server) ; Alice (client)

- Alice sends password (PSWD) to bob


- Bob generates random 3 digit number (RAND) and sends it to alice
- Alice calculates remainder : PSWD Mod RAND ; pow(PSWD,1,RAND)
- Alice sends remainder to Bob. Bob cross-checks the remainder and Authenticates if
matched.
BOB.py (SERVER)
import random
import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as bob_socket:


bob_socket.bind(('127.0.0.1', 12345))
bob_socket.listen()
print('Server listening')
alice,adr = bob_socket.accept()
PSWD = int(alice.recv(1024).decode())
RAND = random.randint(100,999)
alice.send(str(RAND).encode())
RB = pow(PSWD,1,RAND)

RA = int(alice.recv(1024).decode())
if str(RA) == str(RB):
print("Authentication Successful")

Alice.py (Client)
import socket

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as alice_socket:


alice_socket.connect(('127.0.0.1', 12345))
PSWD = 100
alice_socket.send(str(PSWD).encode())

RAND = alice_socket.recv(1024).decode()
remainder = pow(int(PSWD),1,int(RAND))
alice_socket.send(str(remainder).encode())

AFFINE CIPHER
def mod_inv(k,key):
k = k % key
for x in range(1,key):
if (k*x) % key == 1:
return x
return -1

def add_encrypt(p, key):


val = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for char in p:
if char.isalpha():
index = (val.index(char) + key) % 26
encrypted += val[index]
else:
encrypted += char
return encrypted

def add_decrypt(p,key):
val = 'abcdefghijklmnopqrstuvwxyz'
decrypted = ''
for char in p:
if char.isalpha():
index = (val.index(char) - key) % 26
decrypted += val[index]
else:
decrypted += char
return decrypted

def mult_encrypt(p,key):
val = 'abcdefghijklmnopqrstuvwxyz'
encrypted = ''
for char in p:
if char.isalpha():
index = (val.index(char) * key) % 26
encrypted += val[index]
else:
encrypted += char
return encrypted

def mult_decrypt(p,key):
val = 'abcdefghijklmnopqrstuvwxyz'
decrypted = ''
n = mod_inv(key,26)
for char in p:
if char.isalpha():
index = (val.index(char) * n) % 26
decrypted += val[index]
else:
decrypted += char
return decrypted

def affine_encrypt(p,key):
x = add_encrypt(p,key)
ciphertext = mult_encrypt(x,key)

return ciphertext

def affine_decrypt(p,key):
x = mult_decrypt(p,key)
plaintext = add_decrypt(x,key)

return plaintext

if __name__ == '__main__':
plaintext = 'rahul'
key = 3
x = affine_encrypt(plaintext,key)
print(x)
y = affine_decrypt(x,key)
print(y)

You might also like