You are on page 1of 52

SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 1
1.Write a C/Python program to implement
a) Multiplicative Inverse
b) Logical Operations
c) Modular Arithmetic

Aim: Calculate modular multiplicative inverse of a given number.

Description: In modular the multiplicative inverse of an integer a modulo m is an integer x


such that
ax=1 mod m
That is, it is the multiplicative inverse in the ring of integers modulo m, denoted Zm.
Suppose we wish to find modular multiplicative inverse x of 3 modulo 11.
x=3-1 (mod 11)
This is the same as finding x such that
3x= 1 (mod 11)
Working in Z11 we find one value of x that satisfies this congruence is 4 because
3.4=12= 1 (mod11)
and there are no other values of x in Z11 that satisfy this congruence. Therefore, the modular
multiplicative inverse of 3 modulo 11 is 4.

PROGRAM:

a)MULTIPLICATIVE INVERSE:

def modulo_multiplicative_inverse(A, M):


for i in range(0, M):
if (A*i) % M == 1:
return i
return -1
a=int(input("Enter a value:"))
b=int(input("Enter m value:"))
mod=modulo_multiplicative_inverse(a,b)
print("The modular multiplicative inverse is:",mod)

b)Logical Operations:
x = True
y = False
print('x and y is',x and y)
print('x or y is',x or y)
print('not x is',notx,'not y is',not y)

c)Modular Arithmetic:
a=int(input("Enter a value:"))
b=int(input("Enter b value:"))
amodb=a%b
print ("modular arithmetic of a and b is",amodb)

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 2

2. Write a C/Python program to implement Substitution techniques


a ) Playfair Cipher
b) Hill Cipher

a)PlayfairCipher:

Aim: Convert given plaintext to ciphertext using Playfair Cipher.

Description:

The matrix is constructed by filling in the letters of the keyword (minus duplicates) from left to
right and from top to bottom, and then filling in the remainder of the matrix with the remaining
letters in alphabetic order. The letters I and J count as one letter. Plaintext is encrypted two
letters at a time, according to the following rules:
1. Repeating plaintext letters that are in the same pair are separated with a filler letter, such as x,
so that balloon would be treated as ba lx lo on.
2. Two plaintext letters that fall in the same row of the matrix are each replaced by the letter to
the right, with the first element of the row circularly following the last. For example, ar is
encrypted as RM.
3. Two plaintext letters that fall in the same column are each replaced by the letter beneath, with
the top element of the column circularly following the last. For example, mu is encrypted as
CM.
4. Otherwise, each plaintext letter in a pair is replaced by the letter that lies in its own row and
the column occupied by the other plaintext letter. Thus, hs becomes BP and ea becomes IM (or
JM, as the encipherer wishes).

PROGRAM:

def matrix(key):
matrix=[]
for e in key.upper():
if e not in matrix:
matrix.append(e)
alphabet="ABCDEFGHIKLMNOPQRSTUVWXYZ"
for e in alphabet:
if e not in matrix:
matrix.append(e)
matrix_group=[]
for e in range(5):
matrix_group.append('')
matrix_group[0]=matrix[0:5]
matrix_group[1]=matrix[5:10]
matrix_group[2]=matrix[10:15]
matrix_group[3]=matrix[15:20]
matrix_group[4]=matrix[20:25]

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

return matrix_group

def message_to_digraphs(message_original):
message=[]
for e in message_original:
message.append(e)

#Delet space
for unused in range(len(message)):
if " " in message:
message.remove(" ")
i=0
for e in range(len(message)/2):
if message[i]==message[i+1]:
message.insert(i+1,'X')
i=i+2
if len(message)%2==1:
message.append("X")
i=0
new=[]
for x in xrange(1,len(message)/2+1):
new.append(message[i:i+2])
i=i+2
return new
def find_position(key_matrix,letter):
x=y=0
for i in range(5):
for j in range(5):
if key_matrix[i][j]==letter:
x=i
y=j
return x,y
def encrypt(message):
message=message_to_digraphs(message)
key_matrix=matrix(key)
cipher=[]
for e in message:
p1,q1=find_position(key_matrix,e[0])
p2,q2=find_position(key_matrix,e[1])
if p1==p2:
if q1==4:
q1=-1
if q2==4:
q2=-1
cipher.append(key_matrix[p1][q1+1])
cipher.append(key_matrix[p1][q2+1])

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

elif q1==q2:

if p1==4:
p1=-1;

if p2==4:
p2=-1;
cipher.append(key_matrix[p1+1][q1])
cipher.append(key_matrix[p2+1][q2])
else:
cipher.append(key_matrix[p1][q2])
cipher.append(key_matrix[p2][q1])
return cipher
def cipher_to_digraphs(cipher):
i=0
new=[]
for x in range(len(cipher)/2):
new.append(cipher[i:i+2])
i=i+2
return new
def decrypt(cipher):
cipher=cipher_to_digraphs(cipher)
key_matrix=matrix(key)
plaintext=[]
for e in cipher:
p1,q1=find_position(key_matrix,e[0])
p2,q2=find_position(key_matrix,e[1])
if p1==p2:
if q1==4:
q1=-1
if q2==4:
q2=-1
plaintext.append(key_matrix[p1][q1-1])
plaintext.append(key_matrix[p1][q2-1])
elif q1==q2:
if p1==4:
p1=-1;
if p2==4:
p2=-1;
plaintext.append(key_matrix[p1-1][q1])
plaintext.append(key_matrix[p2-1][q2])
else:
plaintext.append(key_matrix[p1][q2])
plaintext.append(key_matrix[p2][q1])

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

for unused in range(len(plaintext)):


if "X" in plaintext:
plaintext.remove("X")

output=""
for e in plaintext:
output+=e
return output.lower()

print ("Playfair Cipher")


order=input("Choose :\n1,Encrypting \n2,Decrypting\n")
if order==1:
key=raw_input("Please input the key : ")
message=raw_input("Please input the message : ")
print ("Encrypting: \n"+"Message: "+message)
print ("Break the message into digraphs: ")
print (message_to_digraphs(message))
print ("Matrix: ")
print (matrix(key) )
print ("Cipher: " )
print (encrypt(message))
elif order==2:
key=raw_input("Please input the key : ")
cipher=raw_input("Please input the cipher text: ")
print ("\nDecrypting: \n"+"Cipher: "+cipher)
print ("Plaintext:")
print (decrypt(cipher))
else:
print ("Error")

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

b)Hill Cipher:

Aim: Convert given plaintext to ciphertext using Hill Cipher.

Description:
The Hill cipher is an example of a block cipher. A block cipher is a cipher in which groups of
letters are enciphered together in equal length blocks.
Encryption: In order to encrypt a message using the Hill cipher, the sender and receiver must
first agree upon a key matrix A of size n x n. Amust be invertible mod 26. The plaintext will
then be enciphered in blocks of size n. In the following example A is a 2 x 2 matrix and the
message will be enciphered in blocks of 2 characters.
Decryption: To decipher a message, first calculate the inverse of the key A.(mod 26)
Then multiply the inverse of the key by each pair of ciphertext letters (mod 26) to recover the
original text.

PROGRAM:
def hill(code):
decryptionKey = [[2,0,3],
[23,5,11],
[7,6,25]]
code = code.lower()
output = [[0],[0],[0]]
counter = 0
for character in code:
number = ord(character) - 97
output[counter][0] = number
counter += 1
result = [[0],
[0],
[0]]
for i in range(len(decryptionKey)):
for j in range(len(output[0])):
for k in range(len(output)):
result[i][0] += decryptionKey[i][k] * output[k][j]
unCiphered = ""
for r in result:
numeric_letter = r[0] % 26
val = chr(numeric_letter + 97)
unCiphered = unCiphered + val
return unCiphered
code = raw_input("Enter plaintext: ")
ciphertext = ""
while(code):
plaintext = code[:3]
code = code[3:]
ciphertext = ciphertext + hill(plaintext)
print ciphertext

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 3

3. Write a C/Python program to implement Transposition techniques


a) Railfence
b) Columnar

a)Railfence :

AIM:Convert given plaintext to ciphertext using Railfence Transposition.

Description:

The simplest such cipher is the rail fence technique, in which the plaintext iswritten down as a
sequence of diagonals and then read off as a sequence of rows.

PROGRAM:

def main():
layers = 2
plain_text = input("Enter the plain text: ")
cipher_text = encrypt(layers, plain_text)
print("Encrypted text: " + cipher_text)

def encrypt(layers, plain_text):


plain_text = plain_text.replace(" ", "")
plain_text = plain_text.upper()
rail = [""] * layers
layer = 0
for p in plain_text:
rail[layer] += p
if layer >= layers - 1:
layer = 0
else:
layer += 1

cipher = "".join(rail)
return cipher
if __name__ == '__main__':
main()

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

b)Columnar :

Aim: Convert given plaintext to Ciphertext using Columnar Transposition.

Description:
A more complex scheme is to write the message in a rectangle, row by row, and read the
message off, column by column, but permute the order of the columns. The order of the
columns then
A more complex scheme is to write the message in a rectangle, row by row, and read the
message off, column by column, but permute the order of the columns. The order of the
columns then becomes key to the algoritm.

PROGRAM:

def split(seq, length):


return [seq[i:i + length] for i in range(0, len(seq), length)]
def encode(key, plaintext):
order = {
int(val): num for num, val in enumerate(key)
}
ciphertext = ''
for i in sorted(order.keys()):
for part in split(plaintext, len(key)):
try:
ciphertext += part[order[i]]
except IndexError:
continue
return ciphertext
key=input("enter the key:")
plaintext=input("Enter the plaintext to encrypt: ")
print(encode(key,plaintext))

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 4

4.Write a C/Python program to implement DES


a) Key Generation
b) Encryption & Decryption

AIM: Program to implement DES algorithm..

Description: DES (and most of the other major symmetric ciphers) is based on a cipher text is
known as the Feistel block cipher. This was a block cipher developed by the IBM research,
cryptography researcher Horst Feistel in the early 70’s. It consists of a number of rounds where
each round contains bit-shuffling, non-linear substitutions (S-boxes) and exclusive OR
operations. Most symmetric encryption schemes today are based on this structure
(known as a feistel network).the plaintext to be encrypted secret.

key.

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

a)Key Generation:

PROGRAM:

PI = [58, 50, 42, 34, 26, 18, 10, 2,


60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7]

CP_1 = [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]

CP_2 = [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]

E = [32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1]

S_BOX = [

[[14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7],


[0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8],
[4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0],
[15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13],
],

[[15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10],

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

[3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5],


[0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15],
[13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9],
],

[[10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8],


[13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1],
[13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7],
[1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12],
],

[[7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15],


[13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9],
[10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4],
[3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14],
],

[[2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9],


[14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6],
[4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14],
[11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3],
],

[[12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11],


[10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8],
[9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6],
[4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13],
],

[[4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1],


[13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6],
[1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2],
[6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12],
],

[[13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7],


[1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2],
[7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8],
[2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11],
]
]

P = [16, 7, 20, 21, 29, 12, 28, 17,


1, 15, 23, 26, 5, 18, 31, 10,
2, 8, 24, 14, 32, 27, 3, 9,
19, 13, 30, 6, 22, 11, 4, 25]

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PI_1 = [40, 8, 48, 16, 56, 24, 64, 32,

39, 7, 47, 15, 55, 23, 63, 31,


38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25]

SHIFT = [1,1,2,2,2,2,2,2,1,2,2,2,2,2,2,1]

def string_to_bit_array(text):
array = list()
for char in text:
binval = binvalue(char, 8)
array.extend([int(x) for x in list(binval)])
return array

def bit_array_to_string(array):
res = ''.join([chr(int(y,2)) for y in [''.join([str(x) for x in bytes]) for bytes in
nsplit(array,8)]])
return res

def binvalue(val, bitsize):


binval = bin(val)[2:] if isinstance(val, int) else bin(ord(val))[2:]
if len(binval) >bitsize:
raise "binary value larger than the expected size"
while len(binval) <bitsize:
binval = "0"+binval
return binval

def nsplit(s, n):


return [s[k:k+n] for k in range(0, len(s), n)]

ENCRYPT=1
DECRYPT=0

class des():
def __init__(self):
self.password = None
self.text = None
self.keys = list()

def run(self, key, text, action=ENCRYPT, padding=False):


if len(key) < 8:
raise "Key Should be 8 bytes long"

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

eliflen(key) > 8:

key = key[:8]

self.password = key
self.text = text

if padding and action==ENCRYPT:


self.addPadding()
eliflen(self.text) % 8 != 0:
raise "Data size should be multiple of 8"

self.generatekeys()
text_blocks = nsplit(self.text, 8)
result = list()
for block in text_blocks:
block = string_to_bit_array(block)
block = self.permut(block,PI)
g, d = nsplit(block, 32)
tmp = None
for i in range(16):
d_e = self.expand(d, E)
if action == ENCRYPT:
tmp = self.xor(self.keys[i], d_e)
else:
tmp = self.xor(self.keys[15-i], d_e)
tmp = self.substitute(tmp)
tmp = self.permut(tmp, P)
tmp = self.xor(g, tmp)
g=d
d = tmp
result += self.permut(d+g, PI_1
final_res = bit_array_to_string(result)
if padding and action==DECRYPT:
return self.removePadding(final_res)
else:
return final_res

def substitute(self, d_e):


subblocks = nsplit(d_e, 6)
result = list()
for i in range(len(subblocks)):
block = subblocks[i]
row = int(str(block[0])+str(block[5]),2)
column = int(''.join([str(x) for x in block[1:][:-1]]),2)
val = S_BOX[i][row][column]

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

bin = binvalue(val, 4)
result += [int(x) for x in bin]

return result

def permut(self, block, table):


return [block[x-1] for x in table]

def expand(self, block, table):


return [block[x-1] for x in table]

def xor(self, t1, t2):


return [x^y for x,y in zip(t1,t2)]

def generatekeys(self):
self.keys = []
key = string_to_bit_array(self.password)
key = self.permut(key, CP_1)
g, d = nsplit(key, 28)
for i in range(16):
g, d = self.shift(g, d, SHIFT[i])
tmp = g + d
self.keys.append(self.permut(tmp, CP_2))

def shift(self, g, d, n): #Shift a list of the given value


print (g[n:] + g[:n], d[n:] + d[:n])
return g[n:] + g[:n], d[n:] + d[:n]

def addPadding(self):
pad_len = 8 - (len(self.text) % 8)
print (self.text)
self.text += pad_len * chr(pad_len)

def removePadding(self, data):


pad_len = ord(data[-1])
return data[:-pad_len]

def encrypt(self, key, text, padding=False):


return self.run(key, text, ENCRYPT, padding)

def decrypt(self, key, text, padding=False):


return self.run(key, text, DECRYPT, padding)

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

if __name__ == '__main__':
key = "0001001100110100010101110111100110011011101111001101111111110001"
text= "11110000110011001010101011110101010101100110011110001111"
d = des()
r = d.encrypt(key,text)
r2 = d.decrypt(key,r)
print ("Ciphered: %r" % r)
print ("Deciphered: ", r2)

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

b) Encryption/Decryption:

PROGRAM:

key = "0111111101"
cipher = "10100010"

P10 = (3, 5, 2, 7, 4, 10, 1, 9, 8, 6)


P8 = (6, 3, 7, 4, 8, 5, 10, 9)
P4 = (2, 4, 3, 1)

IP = (2, 6, 3, 1, 4, 8, 5, 7)
IPi = (4, 1, 3, 5, 7, 2, 8, 6)

E = (4, 1, 2, 3, 2, 3, 4, 1)

S0 = [
[1, 0, 3, 2],
[3, 2, 1, 0],
[0, 2, 1, 3],
[3, 1, 3, 2]
]

S1 = [
[0, 1, 2, 3],
[2, 0, 1, 3],
[3, 0, 1, 0],
[2, 1, 0, 3]
]

def permutation(perm, key):


permutated_key = ""
for i in perm:
permutated_key += key[i-1]

return permutated_key

def generate_first_key(left_key, right_key):


left_key_rot = left_key[1:] + left_key[:1]
right_key_rot = right_key[1:] + right_key[:1]
key_rot = left_key_rot + right_key_rot
return permutation(P8, key_rot)

def generate_second_key(left_key, right_key):


left_key_rot = left_key[3:] + left_key[:3]
right_key_rot = right_key[3:] + right_key[:3]
key_rot = left_key_rot + right_key_rot

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

return permutation(P8, key_rot)

def F(right, subkey):


expanded_cipher = permutation(E, right)
xor_cipher = bin( int(expanded_cipher, 2) ^ int(subkey, 2) )[2:].zfill(8)
left_xor_cipher = xor_cipher[:4]
right_xor_cipher = xor_cipher[4:]
left_sbox_cipher = Sbox(left_xor_cipher, S0)
right_sbox_cipher = Sbox(right_xor_cipher, S1)
return permutation(P4, left_sbox_cipher + right_sbox_cipher)

def Sbox(input, sbox):


row = int(input[0] + input[3], 2)
column = int(input[1] + input[2], 2)
return bin(sbox[row][column])[2:].zfill(4)

def f(first_half, second_half, key):


left = int(first_half, 2) ^ int(F(second_half, key), 2)
print "Fk: " + bin(left)[2:].zfill(4) + second_half
return bin(left)[2:].zfill(4), second_half

p10key = permutation(P10, key)


left = p10key[:int(len(p10key)/2)]
right = p10key[int(len(p10key)/2):]

first_key = generate_first_key(left, right)


second_key = generate_second_key(left, right)
print "[*] First key: " + first_key
print "[*] Second key: " + second_key

permutated_cipher = permutation(IP, cipher)


print "IP: " + permutated_cipher
first_half_cipher = permutated_cipher[:int(len(permutated_cipher)/2)]
second_half_cipher = permutated_cipher[int(len(permutated_cipher)/2):]

left, right = f(first_half_cipher, second_half_cipher, second_key)


print "SW: " + right + left
left, right = f(right, left, first_key) # switch left and right!

print "IP^-1: " + permutation(IPi, left + right)

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 5

5.Write a C/Python program to implement AES Key Generation.

Aim: Program to implement AES Key Generation.

Description: Takes 128-bit (16-byte) key and expands into array of 44/52/60 32-bit words start by
copying key into first 4 words then loop creating words that depend on values in previous & 4 places
back in 3 of 4 cases just XOR these together 1st word in 4 has rotate + S-box + XOR round constant on
previous, before XOR 4th back.

PROGRAM:

import numpy as np
keyfinal = []
sBox = [['0x63', '0x7c', '0x77', '0x7b', '0xf2', '0x6b', '0x6f', '0xc5','0x30', '0x01', '0x67', '0x2b',
'0xfe', '0xd7', '0xab', '0x76']
,['0xca', '0x82', '0xc9', '0x7d', '0xfa', '0x59', '0x47', '0xf0','0xad', '0xd4', '0xa2', '0xaf', '0x9c',
'0xa4', '0x72','0xc0']
,['0xb7', '0xfd', '0x93', '0x26', '0x36', '0x3f', '0xf7', '0xcc','0x34', '0xa5', '0xe5', '0xf1', '0x71',
'0xd8', '0x31', '0x15']
,['0x04', '0xc7', '0x23', '0xc3', '0x18', '0x96', '0x05', '0x9a','0x07', '0x12', '0x80', '0xe2', '0xeb',
'0x27', '0xb2', '0x75']
,['0x09', '0x83', '0x2c', '0x1a','0x1b', '0x6e', '0x5a', '0xa0','0x52', '0x3b', '0xd6', '0xb3', '0x29',
'0xe3', '0x2f', '0x84']
,['0x53', '0xd1', '0x00', '0xed','0x20', '0xfc', '0xb1', '0x5b','0x6a', '0xcb', '0xbe', '0x39', '0x4a',
'0x4c', '0x58', '0xcf']
,['0xd0', '0xef', '0xaa', '0xfb', '0x43','0x4d', '0x33', '0x85', '0x45', '0xf9', '0x02', '0x7f', '0x50',
'0x3c', '0x9f', '0xa8']
,['0x51', '0xa3', '0x40', '0x8f', '0x92', '0x9d', '0x38','0xf5','0xbc', '0xb6', '0xda', '0x21', '0x10',
'0xff', '0xf3', '0xd2']
,['0xcd', '0x0c', '0x13', '0xec', '0x5f', '0x97', '0x44', '0x17','0xc4', '0xa7', '0x7e', '0x3d','0x64',
'0x5d', '0x19', '0x73']
,['0x60', '0x81', '0x4f', '0xdc', '0x22', '0x2a', '0x90', '0x88','0x46', '0xee', '0xb8', '0x14', '0xde',
'0x5e', '0x0b', '0xdb']
,['0xe0', '0x32', '0x3a', '0x0a', '0x49', '0x06', '0x24', '0x5c','0xc2', '0xd3', '0xac', '0x62', '0x91',
'0x95', '0xe4', '0x79']
,['0xe7', '0xc8', '0x37', '0x6d','0x8d', '0xd5', '0x4e', '0xa9','0x6c', '0x56', '0xf4', '0xea', '0x65',
'0x7a', '0xae', '0x08']
,['0xba', '0x78', '0x25', '0x2e', '0x1c', '0xa6', '0xb4', '0xc6','0xe8', '0xdd', '0x74', '0x1f', '0x4b',
'0xbd', '0x8b', '0x8a']
,['0x70','0x3e', '0xb5', '0x66', '0x48', '0x03', '0xf6', '0x0e', '0x61', '0x35','0x57', '0xb9', '0x86',
'0xc1', '0x1d', '0x9e']
,['0xe1', '0xf8', '0x98', '0x11', '0x69', '0xd9', '0x8e', '0x94', '0x9b', '0x1e', '0x87', '0xe9', '0xce',
'0x55', '0x28', '0xdf']
,['0x8c', '0xa1', '0x89', '0x0d', '0xbf', '0xe6', '0x42', '0x68', '0x41', '0x99', '0x2d', '0x0f', '0xb0',
'0x54', '0xbb', '0x16']]

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

num= {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'a':10,'b':11,'c':12,'d':13,'e':14,'f':15}
anum={0:'0',1:'1',2:'2',3:'3',4:'4',5:'5',6:'6',7:'7',8:'8',9:'9',10:'a',11:'b',12:'c',13:'d',14:'e',15:'f'}
xnum={'0':'0000','1':'0001','2':'0010','3':'0011','4':'0100','5':'0101','6':'0110','7':'0111','8':'1000','9':'
1001','a':'1010','b':'1011','c':'1100','d':'1101','e':'1110','f':'1111'}
rcon = [[[0,0,0,0],[0,0,0,1],[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,0,0,0]
,[0,0,1,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]]
,[[0,0,0,0],[0,1,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,0]]
,[[0,0,0,0],[1,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,0,0]]
,[[0,0,0,1],[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,0,0,0]]
,[[0,0,1,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],[0,0,0,0]]
,[[0,1,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,0],[0,0,0,0]]
,[[1,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,0,0],[0,0,0,0]]
,[[0,0,0,1],[1,0,1,1],[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,0,1,1],[0,1,1,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]]]
def rotate(l, n):
return l[n:] + l[:n]
k = raw_input("Enter Your Key: ")

v = [None]*len(k)
for i in range(len(k)):
v[i] = str(hex(ord(k[i]))[2:])
v1 = []
v1.append(v[0:4])
v1.append(v[4:8])
v1.append(v[8:12])
v1.append(v[12:16])
for l in range(10):
v4r = rotate(v1[3],1)
v4a = [None]*4
final = []
for i in range(4):
temp = v4r[i]
temp1 = sBox[num[temp[0]]][num[temp[1]]]
v4a[i] = str(temp1[2:])
temp = v4a[0]
s = ''
s1= ''
results = list(map(int, list(xnum[temp[0]])))
plainep = np.array(results)
key1 = np.array(rcon[l][0])
plaink1 = plainep ^ key1
plaink1 = plaink1.tolist()
str1 = ''.join(str(e) for e in plaink1)
val = int(str1,2)
s = anum[val]
temp12 = s + temp[1]
temp = temp12

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

results = list(map(int, list(xnum[temp[1]])))


plainep = np.array(results)
key1 = np.array(rcon[l][1])
plaink1 = plainep ^ key1
plaink1 = plaink1.tolist()
str1 = ''.join(str(e) for e in plaink1)
val = int(str1,2)
s1 = anum[val]
temp11 = temp[0]+s1
v4a[0] = ''
v4a[0]+=temp11
for k in range(4):
vt = [None]*4
for i in range(4):
imp = ''
temp = v4a[i]
temp1 = v1[k][i]
for j in range(2):
results = list(map(int, list(xnum[temp[j]])))
results1 = list(map(int, list(xnum[temp1[j]])))
plainep = np.array(results)
key1 = np.array(results1)
plaink1 = plainep ^ key1
plaink1 = plaink1.tolist()
str1 = ''.join(str(e) for e in plaink1)
val = int(str1, 2)
imp+= list(num.keys())[list(num.values()).index(val)]
vt[i] = imp
v4a = vt
final.append(vt)
v1 = final
keyfinal.append(v1)
for i in range(10):
print("KEY ",i+1," ",keyfinal[i])

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 6

6. Write a C/Python program to implement following AES Operations.


a)Add Round Key
b)Substitute bytes
c) Shift Rows
d) Mix Columns

Aim: Program to implement AES Operations.

Description:
Byte Substitution:
A simple substitution of each byte uses one table of 16x16 bytes containing a permutation of all
256 8-bit values each byte of state is replaced by byte indexed by row (left 4-bits) & column
(right 4-bits)
S-box constructed using defined transformation of values in GF(28) designed to be resistant to
all known attacks.

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

Shift Rows: A circular byte shift in each each


 1st row is unchanged
 2nd row does 1 byte circular shift to left
 3rd row does 2 byte circular shift to left
 4th row does 3 byte circular shift to left

Mix Columns: Each column is processed separately each byte is replaced by a value dependent
on all 4 bytes in the column effectively a matrix multiplication in GF(28) using prime poly m(x)
=x8+x4+x3+x+1.

Add Round Key: XOR state with 128-bits of the round key again processed by column (though
effectively a series of byte operations) inverse for decryption identical since XOR own inverse,
with reversed keys designed to be as simple as possible a form of Vernam cipher on expanded
key, requires other stages for complexity / security.

POGRAM:

key="0100101011110101"
rc1="10000000"
rc2="00110000"
plaintext="1101011100101000"
def rotate(key,right_key):
left_key_rot=left_key[1:] + left_key[:1]
right_key_rot=right_key[1:] + right_key[:1]
key_rot=left_key_rot+right_key_rot
return permutation(P8,key_rot)
def Sbox(input):
if input=="0000":
z="1001"
elif input=="0001":
z="0100"
elif input=="0010":
z="1010"
elif input=="0011":
z="1011"
elif input=="0100":
z="1101"
elif input=="0101":
z="0001"
elif input=="0110":
z="1000"
elif input=="0110":
z="0101"
elif input=="1000":
z="0110"
elif input=="1001":
z="0010"

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

elif input=="1010":
z="0000"
elif input=="1011":
z="0011"
elif input=="1100":
z="1100"
elif input=="1101":
z="1110"
elif input=="1110":
z="1111"
else:
z="0111"
return z
def F(right,subkey):
expanded_cipher=permutation(E,right)
xor_cipher=bin(int(expanded_cipher,2)^int(subkey,2) )[2:].zfill(8)
left_xor_cipher=xor_cipher[:4]
right_xor_cipher=xor_cipher[4:]
left_sbox_cipher=Sbox(left_xor_cipher,S0)
right_sbox_cipher=Sbox(right_xor_cipher,S1)
return permutation(P4,left_sbox_cipher+right_sbox_cipher)
def xor(x,y):
z=int(x)^int(y)
return z
w0= key[:int(len(key)/2)]
w1 = key[int(len(key)/2):]
print ("w0= ",w0)
print ("w1= ",w1)
word_1_left= w1[:int(len(w1)/2)]
word_1_right= w1[int(len(w1)/2):]
rotated=word_1_right+word_1_left
print ("w1 after rotation= ",rotated)
left_for_substitution=rotated[:int(len(rotated)/2)]
right_for_substitution=rotated[int(len(rotated)/2):]
left_substituted=Sbox(left_for_substitution)
right_substituted=Sbox(right_for_substitution)
substituted=left_substituted+right_substituted
print ("w1 after substitution= ",substituted)
xored_result=bin(int(substituted,2)^int(rc1,2) )[2:].zfill(8)
print ("w1 after xor with round constant= ",xored_result)
w2=bin(int(xored_result,2)^int(w0,2) )[2:].zfill(8)
print ("w2= ",w2)
w3=bin(int(w2,2)^int(w1,2) )[2:].zfill(8)
print ("w3= ",w3)
word_3_left= w3[:int(len(w3)/2)]
word_3_right= w3[int(len(w3)/2):]
rotated3=word_3_right+word_3_left

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

print ("rotated3= ",rotated3)

left3_for_substitution=rotated3[:int(len(rotated3)/2)]
right3_for_substitution=rotated3[int(len(rotated3)/2):]
left3_substituted=Sbox(left3_for_substitution)
right3_substituted=Sbox(right3_for_substitution)
substituted3=left3_substituted+right3_substituted
print ("substituted3= ",substituted3)
xored3_result=bin(int(substituted3,2)^int(rc2,2) )[2:].zfill(8)
print ("w3 after xor with round constant 2= ",xored3_result)
w4=bin(int(xored3_result,2)^int(w2,2) )[2:].zfill(8)
print ("w4= ",w4)
w5=bin(int(w3,2)^int(w4,2) )[2:].zfill(8)
print ("w5= ",w5)
key0=w0+w1
key1=w2+w3
key2=w4+w5
print ("Key 0= ",key0)
print ("Key 1= ",key1)
print ("Key 2= ",key2)
print ("ENCRYPTION")
print ("ROUND 0")
round0=bin(int(key0,2)^int(plaintext,2) )[2:].zfill(16)
print ("Result after adding round 0 Key: ", round0)
print ("ROUND 1")
print ("NIBBLE SUBSTITUTION")
lft1=round0[0:4]
print (lft1)
lft2=round0[4:8]
print (lft2)
lft3=round0[8:12]
print (lft3)
lft4=round0[12:16]
print (lft4)
rht1=Sbox(lft1)
rht2=Sbox(lft2)
rht3=Sbox(lft3)
rht4=Sbox(lft4)
r1_substitution=rht1+rht2+rht3+rht4
print ("Round1 result after substitution is= ",r1_substitution)
r1_shift=rht1+rht4+rht3+rht2
print ("Round1 result after shifting rows= ",r1_shift)

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 7

7. Write a C/Python program to generate random numbers using LCG & BSS Pseudo
random number generators.

Aim: Generate Random numbers using Linear Congruential Generator.

Description: A linear congruential sequence is a series of numbers based on the recurrence relation
formula:
Xn = (aXn-1 + c) mod m

In this formula, m is called the modulus, a is called the multiplier, and c is called the increment. It is
not difficult to imagine the resulting sequence of this formula when given different values.

PROGRAM:
import random as rnd
import numpy as np
from itertools import cycle
def main():
m = int(input("Inserire il valore di m: "))
a = int(input("Inserire il valore di a: "))
c = int(input("Inserire il valore di c: "))
seed = rnd.randint(0, m - 1)
sequenza = genera_sequenza(m, a, c, seed, count=m, full=False, check=False)
print("Seme: " + str(seed))
print(sequenza)
old_min = min(sequenza)
old_max = max(sequenza)
new_min = 0
new_max = 255
values = [((x - old_min) * (new_max - new_min) / (old_max - old_min)) +
new_min for x in sequenza]
row = cycle(values)
arr_img = np.array([[row.next() for i in range(0, 301)]] * 300)

def genera_sequenza(m, a, c, seed, count, full=True, check=True):


seq = []

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

xn = seed
if check:
if m < 0 or a >= m or a <= 0 or c >= m or c < 0:
return None
if full:
if mcd(c, m) != 1 or not divisibile_fattori_primi(a-1, m) or not ((a - 1) % 4 == 0
and m % 4 == 0):
return None
generatore = lcg(m, a, c, seed)
for i in range(count):
seq.append(generatore.next())
return seq

def lcg(m, a, c, seed):


_xn = seed
while True:
yield _xn
_xn = (a * _xn + c) % m

def mcd(a, b):


while b != 0:
resto = a % b
a=b
b = resto
return a

def fattori_primi(n):
fatt = []
d=2
while d*d <= n:
while n % d == 0:
fatt.append(d)
n /= d
d += 1

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

if n > 1:
fatt.append(n)
return fatt

def divisibile_fattori_primi(a, b):


fatt_primi = fattori_primi(b)
for i in fatt_primi:
if a % i != 0:
return False
return True

if __name__ == "__main__":
main()

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 8

8.Write a C/Python program to implement RC-4 .

Aim: Convert given plaintext to ciphertext using RC4 algorithm.

Description:

PROGRAM:

def KSA(key):
keylength = len(key)
S = list(range(256))
j=0
for i in range(256):
j = (j + S[i] + key[i % keylength]) % 256
S[i], S[j] = S[j], S[i]
return S
def PRGA(S):
i=0
j=0
while True:
i = (i + 1) % 256
j = (j + S[i]) % 256
S[i], S[j] = S[j], S[i]
K = S[(S[i] + S[j]) % 256]
yield K
def RC4(key):
S = KSA(key)
return PRGA(S)
if __name__ == '__main__':
key = input("Enter the key")
plaintext = input("Enter the plaintext")
def convert_key(s):
return [ord(c) for c in s]
key = convert_key(key)
keystream = RC4(key)
import sys
for c in plaintext:
sys.stdout.write("%02X" % (ord(c) ^ next(keystream)))
print

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 9

9. Write a C/Python program to implement RSA algorithm.

Aim: Convert given plaintext to ciphertext using RSA algorithm.

Description:

PROGRAM:

import random
def gcd(a, b):
if a>b:
minval=b
else:
minval=a
for i in range(1,minval+1):
if(a%i==0 and b%i==0):
hcf=i
return hcf
def multiplicative_inverse(e,phi):
for i in range(0, phi):

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

if (e*i) % phi == 1:

return i
return -1
def is_prime(num):
if num>1:
for i in range(2,num):
if num%i==0:
return False
else:
return True
else:
return False

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)
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(pk, plaintext):


key, n = pk
cipher = [(ord(char) ** key) % n for char in plaintext]
return cipher

def decrypt(pk, ciphertext):


key, n = pk
plain = [chr((char ** key) % n) for char in ciphertext]
return ''.join(plain)

if __name__ == '__main__':
'''
Detect if the script is being run directly by the user
'''
print ("RSA Encrypter/ Decrypter")
p = int(input("Enter a prime number (17, 19, 23, etc): "))

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….
q = int(input("Enter another prime number (Not one you entered above): "))

print ("Generating your public/private keypairs now . . .")

public, private = generate_keypair(p, q)


print ("Your public key is ", public ," and your private key is ", private)
message = input("Enter a message to encrypt with your private key: ")
encrypted_msg = encrypt(private, message)
print ("Your encrypted message is: ")
print (''.join(map(lambda x: str(x), encrypted_msg)))
print ("Decrypting message with public key ", public ," . . .")
print ("Your message is:")
print (decrypt(public, encrypted_msg))

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 10

10. Write a C/Python program to implement Diffie-Hellman Key Exchange algorithm.

Aim: Convert given plaintext to ciphertext using Diffie-Hellman algorithm.

Description:

PROGRAM:

def power(a, b):


result = 1
while b > 0:
result = result * a
b -= 1
return result
def gcd(a,b):
while b != 0:
a, b = b, a % b
return a

def primRoots(modulo):
roots = []

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

required_set = set(num for num in range (1, modulo) if gcd(num, modulo) == 1)

for g in range(1, modulo):


actual_set = set(pow(g, powers) % modulo for powers in range (1, modulo))
if required_set == actual_set:
roots.append(g)
return roots

q=int(input("enter a prime number:"))


primitive_roots = primRoots(q)

a=int(input("enter alpha value from given set:"))


xa=int(input("enter XA value:"))
xb=int(input("enter XB value:"))
ya=((power(a,xa))%q)
yb=((power(a,xb))%q)
print ("Ya value is:")
print(ya)
print ("Yb value is:")
print(yb)
print ("Key Generation at User A:")
K=((power(yb,xa))%q)
print (K)
print ("Key Generation at User B:")
K=((power(ya,xb))%q)
print(K)

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 11

11. Write a C/Python program to generate hash code using simple hash function.

Aim: Program to generate hash code using hash functions MD5 and SHA1.

Description: An iterative fashion to produce an -bit hash function. One of the simplest hash
functions is the bit-by-bit exclusive-OR (XOR) of every block.
A simple way to improve matters is to perform a one-bit circular shift, or rotation, on the hash
value after each block is processed. The procedure can be summarized as follows.
1. Initially set the -bit hash value to zero.
2. Process each successive -bit block of data as follows:
a. Rotate the current hash value to the left by one bit.
b. XOR the block into the hash value.

MD5 PROGRAM:

import hashlib
hash_object = hashlib.md5(b'Hello World')
hex_dig= hash_object.hexdigest()
print(hex_dig)

SHA1 PROGRAM:

import hashlib
hash_object = hashlib.sha1(b'Hello World')
hex_dig= hash_object.hexdigest()
print(hex_dig)

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

PROGRAM 12

12. Write a python code to implement Elgamal digital Signature.

Aim: Program to implement Digital Signature using Elgamal Digital Signature.

Description:

PROGRAM:

import random
from random import randint
def modinv(a,m):
for i in range(0,m):
if (a*i)%m==1:
return i
return -1

q=int(input("enter a prime number:"))


proot=10
M=int(input("enter message as integer that should be less than given prime number:"))
print ("Primitive root we taken:",proot)
X=randint(1,q-1)
Y=(pow(proot,X)) % q
print ("public key:",[q,proot,Y])

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

print ("private key:",X)


k=5
print("selected random integer is ",k)
K=(modinv(k,(q-1)))
print("Calculated K is:",K)
s1=pow(proot,k)%q
s2=(K*(M-X*s1))%(q-1)
print ("digital signature is:",(s1,s2))
v1=pow(proot,M)%q
print("calculated v1 is :",v1)
v2=((pow(Y,s1))*(pow(s1,s2)))%q
print("calculated v2 is :",v2)
print("verified digital signature is",(v1,v2))

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459


SHEET No ……………………….

IAS-15CS3112 Regd No. 160030459

You might also like