Professional Documents
Culture Documents
PROGRAM 1
1.Write a C/Python program to implement
a) Multiplicative Inverse
b) Logical Operations
c) Modular Arithmetic
PROGRAM:
a)MULTIPLICATIVE INVERSE:
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)
PROGRAM 2
a)PlayfairCipher:
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]
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])
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])
output=""
for e in plaintext:
output+=e
return output.lower()
b)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
PROGRAM 3
a)Railfence :
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)
cipher = "".join(rail)
return cipher
if __name__ == '__main__':
main()
b)Columnar :
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:
PROGRAM 4
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.
a)Key Generation:
PROGRAM:
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 = [
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
ENCRYPT=1
DECRYPT=0
class des():
def __init__(self):
self.password = None
self.text = None
self.keys = list()
eliflen(key) > 8:
key = key[:8]
self.password = key
self.text = text
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
bin = binvalue(val, 4)
result += [int(x) for x in bin]
return result
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 addPadding(self):
pad_len = 8 - (len(self.text) % 8)
print (self.text)
self.text += pad_len * chr(pad_len)
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)
b) Encryption/Decryption:
PROGRAM:
key = "0111111101"
cipher = "10100010"
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]
]
return permutated_key
PROGRAM 5
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']]
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
PROGRAM 6
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.
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"
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
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)
PROGRAM 7
7. Write a C/Python program to generate random numbers using LCG & BSS Pseudo
random number generators.
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)
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 fattori_primi(n):
fatt = []
d=2
while d*d <= n:
while n % d == 0:
fatt.append(d)
n /= d
d += 1
if n > 1:
fatt.append(n)
return fatt
if __name__ == "__main__":
main()
PROGRAM 8
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
PROGRAM 9
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):
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
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))
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): "))
PROGRAM 10
Description:
PROGRAM:
def primRoots(modulo):
roots = []
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)
PROGRAM 12
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