0% found this document useful (0 votes)
56 views37 pages

19BECE30543 Cns

The document describes the implementation of various cryptographic techniques like Caesar cipher, brute force attack on Caesar cipher, simple substitution cipher (using a transition matrix), and simple permutation cipher. It includes functions for encryption, decryption and other supporting functions like binary to hexadecimal conversion, permutation of bits, shifting bits, and XOR operation on binary strings. Tables for initial permutation, expansion, straight permutation, and S-boxes used in permutation cipher are also included.

Uploaded by

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

19BECE30543 Cns

The document describes the implementation of various cryptographic techniques like Caesar cipher, brute force attack on Caesar cipher, simple substitution cipher (using a transition matrix), and simple permutation cipher. It includes functions for encryption, decryption and other supporting functions like binary to hexadecimal conversion, permutation of bits, shifting bits, and XOR operation on binary strings. Tables for initial permutation, expansion, straight permutation, and S-boxes used in permutation cipher are also included.

Uploaded by

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

Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


Practical – 1 : Implement the Caesar cipher with variable key.
def encryption(pt,k):
result = ""

for i in range(len(pt)):
char = pt[i]

if (char.isupper()):
result = result+ chr((ord(char) + k - 65)%26 + 65)
elif(ord(char)==32):
result = result+char
else:
result = result + chr((ord(char) +k - 97)%26 + 97)
return result

def decription(R,k):
result_d = ""
for i in range(len(R)):
char = R[i]
if (char.isupper()):
result_d = result_d + chr((ord(char) - k - 65)%26
+ 65)
elif(ord(char)==32):
result_d = result_d+char
else:
result_d = result_d + chr((ord(char) - k - 97)%26
+ 97)
return result_d

pt=str(input("Enter the plain text "))


k = int(input("Enter the key value in the form of number "))
print("Plain text=",pt)
print("key value=",k)
R=encryption(pt,k)
print("Cipher Text=",str.upper(R))
print("Plain Text=",decription(R,k))

[1]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


Output :-

[2]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


Practical – 2 : Implement the brute-force (exhaustive key search)
attack on Caesar Cipher.
def encryption(pt, k):
result = ""

for i in range(len(pt)):
char = pt[i]

if (char.isupper()):
result = result + chr((ord(char) + k - 65) % 26 + 65)
elif (ord(char) == 32):
result = result + char
else:
result = result + chr((ord(char) + k - 97) % 26 + 97)
return result

def decription(R, k):


result_d = ""
for i in range(len(R)):
char = R[i]
if (char.isupper()):
result_d = result_d + chr((ord(char) - k - 65) % 26 + 65)
elif (ord(char) == 32):
result_d = result_d + char
else:
result_d = result_d + chr((ord(char) - k - 97) % 26 + 97)
return result_d

def bruteforce(R, j):


result_d = ""
for i in range(len(R)):
char = R[i]
if (char.isupper()):
result_d = result_d + chr((ord(char) - j - 65) % 26 + 65)
elif (ord(char) == 32):
result_d = result_d + char
else:
result_d = result_d + chr((ord(char) - j - 97) % 26 + 97)
return result_d

pt = str(input("Enter the plain text "))


k = int(input("Enter the key value in the form of number "))
print("Plain text=", pt)
print("key value=", k)
R = encryption(pt, k)
print("Cipher Text=", str.upper(R))
print("Plain Text=", decription(R, k))
for i in range(0, 25):
text = bruteforce(R, i)
if text == pt:
print(i)
break
else:
continue

[3]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

Output :-

[4]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

Practical – 3 : Implement simple transition technique.


import math
key=input("Enter keyword text (Contains unique letters only):
").lower().replace(" ", "")
plain_text = input("Enter plain text (Letters only):
").lower().replace(" ", "")

len_key = len(key)
len_plain = len(plain_text)
row = int(math.ceil(len_plain / len_key))
matrix = [ ['X']*len_key for i in range(row) ]

#Encryption

t = 0
for r in range(row):
for c, ch in enumerate(plain_text[t: t + len_key]):
matrix[r][c] = ch
t += len_key

# print(matrix)
sort_order = sorted([(ch, i) for i, ch in enumerate(key)]) #
to make alphabetically order of chars
# print(sort_order)

cipher_text = ''
for ch, c in sort_order:
for r in range(row):
cipher_text += matrix[r][c]

print("Encryption")
print("Plain text is :", plain_text)
print("Cipher text is:", cipher_text)

#Decryption

matrix_new = [ ['X']*len_key for i in range(row) ]


key_order = [ key.index(ch) for ch in sorted(list(key))] #to
make original key order when we know keyword
# print(key_order)

t = 0
for c in key_order:
for r,ch in enumerate(cipher_text[t : t+ row]):
matrix_new[r][c] = ch
t += row

[5]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


p_text = ''
for r in range(row):
for c in range(len_key):
p_text += matrix_new[r][c] if matrix_new[r][c] != 'X' else
''

print("Decryption")
print("Cipher text is:",cipher_text)
print("Plain text is :",p_text)

Output :

[6]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

Practical – 4 : Implement simple permutation technique.


def hex2bin(s):
mp = {'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"}
bin = ""
for i in range(len(s)):
bin = bin + mp[s[i]]
return bin

# Binary to hexadecimal conversion


def bin2hex(s):
mp = {"0000": '0',
"0001": '1',
"0010": '2',
"0011": '3',
"0100": '4',
"0101": '5',
"0110": '6',
"0111": '7',
"1000": '8',
"1001": '9',
"1010": 'A',
"1011": 'B',
"1100": 'C',
"1101": 'D',
"1110": 'E',
"1111": 'F'}
hex = ""
for i in range(0, len(s), 4):
ch = ""
ch = ch + s[i]
ch = ch + s[i + 1]

[7]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


ch = ch + s[i + 2]
ch = ch + s[i + 3]
hex = hex + mp[ch]

return hex

# Binary to decimal conversion


def bin2dec(binary):
binary1 = binary
decimal, i, n = 0, 0, 0
while (binary != 0):
dec = binary % 10
decimal = decimal + dec * pow(2, i)
binary = binary // 10
i += 1
return decimal

# Decimal to binary conversion


def dec2bin(num):
res = bin(num).replace("0b", "")
if (len(res) % 4 != 0):
div = len(res) / 4
div = int(div)
counter = (4 * (div + 1)) - len(res)
for i in range(0, counter):
res = '0' + res
return res

# Permute function to rearrange the bits


def permute(k, arr, n):
permutation = ""
for i in range(0, n):
permutation = permutation + k[arr[i] - 1]
return permutation

# shifting the bits towards left by nth shifts


def shift_left(k, nth_shifts):
s = ""
for i in range(nth_shifts):
for j in range(1, len(k)):
s = s + k[j]
s = s + k[0]
k = s
s = ""
return k

[8]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

# calculating xow of two strings of binary number a and b


def xor(a, b):
ans = ""
for i in range(len(a)):
if a[i] == b[i]:
ans = ans + "0"
else:
ans = ans + "1"
return ans

# Table of Position of 64 bits at initial level: Initial Per-


mutation Table
initial_perm = [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]

# Expansion D-box Table


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

# Straight Permutation Table


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

# S-box Table
sbox = [[[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]],

[9]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

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


10],
[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],

[10]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


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

# Final Permutation Table


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

def encrypt(pt, rkb, rk):


pt = hex2bin(pt)

# Initial Permutation
pt = permute(pt, initial_perm, 64)
print("After initial permutation", bin2hex(pt))

# Splitting
left = pt[0:32]
right = pt[32:64]
for i in range(0, 16):
# Expansion D-box: Expanding the 32 bits data into 48
bits
right_expanded = permute(right, exp_d, 48)

# XOR RoundKey[i] and right_expanded


xor_x = xor(right_expanded, rkb[i])

# S-boxex: substituting the value from s-box table by


calculating row and column
sbox_str = ""
for j in range(0, 8):
row = bin2dec(int(xor_x[j * 6] + xor_x[j * 6 +
5]))
col = bin2dec(int(xor_x[j * 6 + 1] + xor_x[j * 6 +

[11]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


2] + xor_x[j * 6 + 3] + xor_x[j * 6 + 4]))
val = sbox[j][row][col]
sbox_str = sbox_str + dec2bin(val)

# Straight D-box: After substituting rearranging the


bits
sbox_str = permute(sbox_str, per, 32)

# XOR left and sbox_str


result = xor(left, sbox_str)
left = result

# Swapper
if (i != 15):
left, right = right, left
print("Round ", i + 1, " ", bin2hex(left), " ",
bin2hex(right), " ", rk[i])

# Combination
combine = left + right

# Final permutation: final rearranging of bits to get


cipher text
cipher_text = permute(combine, final_perm, 64)
return cipher_text

pt = "123456ABCD132536"
key = "AABB09182736CCDD"

# Key generation
# --hex to binary
key = hex2bin(key)

# --parity bit drop table


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

# getting 56 bit key from 64 bit using the parity bits


key = permute(key, keyp, 56)

# Number of bit shifts


shift_table = [1, 1, 2, 2,
2, 2, 2, 2,

[12]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


1, 2, 2, 2,
2, 2, 2, 1]

# Key- Compression Table : Compression of key from 56 bits to


48 bits
key_comp = [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]

# Splitting
left = key[0:28] # rkb for RoundKeys in binary
right = key[28:56] # rk for RoundKeys in hexadecimal

rkb = []
rk = []
for i in range(0, 16):
# Shifting the bits by nth shifts by checking from shift
table
left = shift_left(left, shift_table[i])
right = shift_left(right, shift_table[i])

# Combination of left and right string


combine_str = left + right

# Compression of key from 56 to 48 bits


round_key = permute(combine_str, key_comp, 48)

rkb.append(round_key)
rk.append(bin2hex(round_key))

print("Encryption")
cipher_text = bin2hex(encrypt(pt, rkb, rk))
print("Cipher Text : ", cipher_text)

print("Decryption")
rkb_rev = rkb[::-1]
rk_rev = rk[::-1]
text = bin2hex(encrypt(cipher_text, rkb_rev, rk_rev))
print("Plain Text : ", text)

[13]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

Output :-

[14]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

Practical – 5 : Implement the rail fence cipher with variable fence.


def encryptRailFence(text, key):

rail = [['\n' for i in range(len(text))]


for j in range(key)]

dir_down = False
row, col = 0, 0

for i in range(len(text)):
if (row == 0) or (row == key - 1):
dir_down = not dir_down

rail[row][col] = text[i]
col += 1

if dir_down:
row += 1
else:
row -= 1

result = []

[15]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


for i in range(key):
for j in range(len(text)):
if rail[i][j] != '\n':
result.append(rail[i][j])
return ("".join(result))

def decryptRailFence(cipher, key):


rail = [['\n' for i in range(len(cipher))]
for j in range(key)]

dir_down = None
row, col = 0, 0

for i in range(len(cipher)):
if row == 0:
dir_down = True
if row == key - 1:
dir_down = False

rail[row][col] = '*'
col += 1

if dir_down:
row += 1
else:
row -= 1

index = 0
for i in range(key):
for j in range(len(cipher)):
if ((rail[i][j] == '*') and
(index < len(cipher))):
rail[i][j] = cipher[index]
index += 1

result = []
row, col = 0, 0
for i in range(len(cipher)):

if row == 0:
dir_down = True
if row == key - 1:
dir_down = False

if (rail[row][col] != '*'):

[16]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


result.append(rail[row][col])
col += 1

if dir_down:
row += 1
else:
row -= 1
return ("".join(result))

if __name__ == "__main__":
print(encryptRailFence("attack at once", 2))
print(encryptRailFence("Ldrp ITR ", 3))
print(encryptRailFence("defend the east wall", 3))

print(decryptRailFence("L dpIRrT", 3))


print(decryptRailFence("atc toctaka ne", 2))
print(decryptRailFence("dnhaweedtees alf tl", 3))

Output :-

[17]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

Practical - 6 : Implement 6 x 6 Playfair cipher.


key = input("Enter key")
key = key.replace(" ", "")
key = key.upper()

def matrix(x, y, initial):


return [[initial for i in range(x)] for j in range(y)]

result = list()
for c in key: # storing key
if c not in result:
if c == 'J':
result.append('I')
else:
result.append(c)
flag = 0
for i in range(65, 91): # storing other character
if chr(i) not in result:
if i == 73 and chr(74) not in result:
result.append("I")
flag = 1

[18]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


elif flag == 0 and i == 73 or i == 74:
pass
else:
result.append(chr(i))
k = 0
my_matrix = matrix(5, 5, 0) # initialize matrix
for i in range(0, 5): # making matrix
for j in range(0, 5):
my_matrix[i][j] = result[k]
k += 1

def locindex(c): # get location of each character


loc = list()
if c == 'J':
c = 'I'
for i, j in enumerate(my_matrix):
for k, l in enumerate(j):
if c == l:
loc.append(i)
loc.append(k)
return loc

def encrypt(): # Encryption


msg = str(input("ENTER MSG:"))
msg = msg.upper()
msg = msg.replace(" ", "")
i = 0
for s in range(0, len(msg) + 1, 2):
if s < len(msg) - 1:
if msg[s] == msg[s + 1]:
msg = msg[:s + 1] + 'X' + msg[s + 1:]
if len(msg) % 2 != 0:
msg = msg[:] + 'X'
print("CIPHER TEXT:", end=' ')
while i < len(msg):
loc = list()
loc = locindex(msg[i])
loc1 = list()
loc1 = locindex(msg[i + 1])
if loc[1] == loc1[1]:
print("{}{}".format(my_matrix[(loc[0] + 1) % 5][loc[1]],
my_matrix[(loc1[0] + 1) % 5][loc1[1]]), end=' ')
elif loc[0] == loc1[0]:
print("{}{}".format(my_matrix[loc[0]][(loc[1] + 1) % 5],
my_matrix[loc1[0]][(loc1[1] + 1) % 5]), end=' ')
else:
print("{}{}".format(my_matrix[loc[0]][loc1[1]],
my_matrix[loc1[0]][loc[1]]), end=' ')
i = i + 2

def decrypt(): # decryption


msg = str(input("ENTER CIPHER TEXT:"))
msg = msg.upper()
msg = msg.replace(" ", "")
print("PLAIN TEXT:", end=' ')
i = 0
while i < len(msg):

[19]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


loc = list()
loc = locindex(msg[i])
loc1 = list()
loc1 = locindex(msg[i + 1])
if loc[1] == loc1[1]:
print("{}{}".format(my_matrix[(loc[0] - 1) % 5][loc[1]],
my_matrix[(loc1[0] - 1) % 5][loc1[1]]), end=' ')
elif loc[0] == loc1[0]:
print("{}{}".format(my_matrix[loc[0]][(loc[1] - 1) % 5],
my_matrix[loc1[0]][(loc1[1] - 1) % 5]), end=' ')
else:
print("{}{}".format(my_matrix[loc[0]][loc1[1]],
my_matrix[loc1[0]][loc[1]]), end=' ')
i = i + 2

while (1):
choice = int(input("\n 1.Encryption \n 2.Decryption: \n 3.EXIT"))
if choice == 1:
encrypt()
elif choice == 2:
decrypt()
elif choice == 3:
exit()
else:
print("Choose correct choice")

Output :

[20]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

Practical – 7 : Implement n x n Hill cipher.


keyMatrix = [[0] * 3 for i in range(3)]

messageVector = [[0] for i in range(3)]

cipherMatrix = [[0] for i in range(3)]

def getKeyMatrix(key):
k = 0
for i in range(3):
for j in range(3):
keyMatrix[i][j] = ord(key[k]) % 65
k += 1

def encrypt(messageVector):
for i in range(3):
for j in range(1):
cipherMatrix[i][j] = 0

[21]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


for x in range(3):
cipherMatrix[i][j] += (keyMatrix[i][x] *
messageVector[x][j])
cipherMatrix[i][j] = cipherMatrix[i][j] % 26

def HillCipher(message, key):


getKeyMatrix(key)

for i in range(3):
messageVector[i][0] = ord(message[i]) % 65

encrypt(messageVector)

CipherText = []
for i in range(3):
CipherText.append(chr(cipherMatrix[i][0] + 65))

print("Ciphertext: ", "".join(CipherText))

def main():
message = "ACT"
key = "GYBNQKURP"
HillCipher(message, key)

if __name__ == "__main__":
main()

Output :

Practical – 8 : Implement Vigenere Cipher.


def generateKey(string, key):
key = list(key)
if len(string) == len(key):
return (key)
else:
for i in range(len(string) -
len(key)):
key.append(key[i % len(key)])
return ("".join(key))

def cipherText(string, key):


cipher_text = []
for i in range(len(string)):
x = (ord(string[i]) +
ord(key[i])) % 26
x += ord('A')

[22]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


cipher_text.append(chr(x))
return ("".join(cipher_text))

def originalText(cipher_text, key):


orig_text = []
for i in range(len(cipher_text)):
x = (ord(cipher_text[i]) -
ord(key[i]) + 26) % 26
x += ord('A')
orig_text.append(chr(x))
return ("".join(orig_text))

# Driver code
if __name__ == "__main__":
string = "Ldrp Itr"
keyword = "Xenesis"
key = generateKey(string, keyword)
cipher_text = cipherText(string, key)
print("Ciphertext :", cipher_text)
print("Original/Decrypted Text :",
originalText(cipher_text, key))

Output :

Practical – 9 : Implement the auto-key cipher.


dict1 = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4,
'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9,
'K': 10, 'L': 11, 'M': 12, 'N': 13, 'O': 14,
'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19,
'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25}

dict2 = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E',


5: 'F', 6: 'G', 7: 'H', 8: 'I', 9: 'J',
10: 'K', 11: 'L', 12: 'M', 13: 'N', 14: 'O',
15: 'P', 16: 'Q', 17: 'R', 18: 'S', 19: 'T',
20: 'U', 21: 'V', 22: 'W', 23: 'X', 24: 'Y', 25: 'Z'}

def generate_key(message, key):


i = 0
while True:

[23]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


if len(key) == len(message):
break
if message[i] == ' ':
i += 1
else:
key += message[i]
i += 1
return key

def cipherText(message, key_new):


cipher_text = ''
i = 0
for letter in message:
if letter == ' ':
cipher_text += ' '
else:
x = (dict1[letter]+dict1[key_new[i]]) % 26
i += 1
cipher_text += dict2[x]
return cipher_text

def originalText(cipher_text, key_new):


or_txt = ''
i = 0
for letter in cipher_text:
if letter == ' ':
or_txt += ' '
else:
x = (dict1[letter]-dict1[key_new[i]]+26) % 26
i += 1
or_txt += dict2[x]
return or_txt

def main():
message = 'THE GERMAN ATTACK'
key = 'SECRET'
key_new = generate_key(message, key)
cipher_text = cipherText(message, key_new)
original_text = originalText(cipher_text, key_new)
print("Encrypted Text =", cipher_text)
print("Original Text =", original_text)

# Executes the main function


if __name__ == '__main__':
main()

Output :

[24]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

Practical – 10 : Implement the Vernam cipher.


def makeVernamCypher(text, key):
answer = ""
p = 0
for char in text:
answer += chr(ord(char) ^ ord(key[p]))
p += 1
if p == len(key):
p = 0
return answer

MY_KEY = "ldrp"
while True:

[25]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


print("\n---Vernam Cypher---")
PlainText = input("Enter text to encrypt: ")
Cypher = makeVernamCypher(PlainText,MY_KEY)
print("Cypher text: "+Cypher)
decrypt = makeVernamCypher(Cypher,MY_KEY)
print("Decrypt: "+decrypt)

Output:-

Practical – 11 : Implement the One Time Pad(OTP) cipher.


from random import randint

character_list = 'aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOp-
PqQrRsStTuUvVwWxXyYzZ,./\;:"[]{}()_-!@#$%^&*|?<>`~'

def generate_otp(sheets, length):

for sheet in range(sheets):


with open("otp" + str(sheet) + ".txt", "w") as f:
for i in range (length):
f.write(str(randint(0, 81)) + "\n")

[26]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


def load_sheet(filename):
with open(filename, "r") as f:
contents = f.read().splitlines()
return contents

def get_plaintext():
plain_text = input('Enter your message: ')
return plain_text

def load_file(filename):

with open(filename, 'r') as f:


contents = f.read()

return contents

def save_file(filename, data):

with open(filename, 'w') as f:


f.write(data)

def encrypt(plaintext, sheet):


ciphertext = ''

for position, character in enumerate(plaintext):

if character not in character_list:


ciphertext += character
else:
encrypted = (character_list.index(character) +
int(sheet[position])) % 81
ciphertext += character_list[encrypted]

return ciphertext

def decrypt(ciphertext, sheet):


plaintext = ''

for position, character in enumerate (ciphertext):

if character not in character_list:


plaintext += character
else:
decrypted = (character_list.index(character) -
int(sheet[position])) % 81
plaintext += character_list[decrypted]

return plaintext

def menu():

[27]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


choices = ['1', '2', '3', '4']
choice = '0'
while True:
print('1. Generate one-time pads')
print('2. Encrypt a message')
print('3. Decrypt a message')
print('4. Quit program')

choice = input('Enter number: ')

if choice == '1':
sheets = int(input('How many OTP should be generated?
'))
length = int(input('What will be the maximum message
length? '))

generate_otp(sheets, length)

elif choice == '2':


filename = input('Enter filename of the OTP you want
to use: ')
sheet = load_sheet(filename)
plaintext = get_plaintext()
ciphertext = encrypt(plaintext, sheet)
filename = input('Enter name of encrypted file: ')

save_file(filename, ciphertext)

elif choice == '3':


filename = input('Enter filename of the OTP you want
to use: ')
sheet = load_sheet(filename)
filename = input('Type the name of the file to be de-
crypted: ')
ciphertext = load_file(filename)
plaintext = decrypt(ciphertext, sheet)

print('Decrypted Message: \n' + plaintext)

elif choice == '4':


exit()
choice = '0'

menu()

Output :-

[28]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

Practical – 12 : Implement the cryptanalysis using frequency ana-


lysis.
from operator import itemgetter
import json

def create_decryption_dictionary(plaintext_filepath, encryp-


ted_filepath, dictionary_filepath):

[29]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


sample_plaintext = _readfile(plaintext_filepath)
encrypted_text = _readfile(encrypted_filepath)

sample_plaintext_frequencies =
_count_letter_frequencies(sample_plaintext)
encrypted_text_frequencies = _count_letter_frequencies(en-
crypted_text)

decryption_dict = {}
for i in range(0, 26):
decryption_dict[encrypted_text_frequencies[i][0]] =
sample_plaintext_frequencies[i][0].lower()

f = open(dictionary_filepath, "w")
json.dump(decryption_dict, f)
f.close

def decrypt_file(encrypted_filepath, decrypted_filepath, dic-


tionary_filepath):

encrypted_text = _readfile(encrypted_filepath)

f = open(dictionary_filepath, "r")
decryption_dict = json.load(f)
f.close()

decrypted_list = []

for letter in encrypted_text:


asciicode = ord(letter.upper())
if asciicode >= 65 and asciicode <= 90:
decrypted_list.append(decryption_dict[letter])

decrypted_text = "".join(decrypted_list)

f = open(decrypted_filepath, "w")
f.write(decrypted_text)
f.close()

def _count_letter_frequencies(text):
frequencies = {}

for asciicode in range(65, 91):


frequencies[chr(asciicode)] = 0

for letter in text:


asciicode = ord(letter.upper())
if asciicode >= 65 and asciicode <= 90:

[30]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


frequencies[chr(asciicode)] += 1

sorted_by_frequency = sorted(frequencies.items(), key =


itemgetter(1), reverse=True)

return sorted_by_frequency

def _readfile(path):

f = open(path, "r")
text = f.read()
f.close()
return text

Output :-

Practical – 13 : Implement Euclidean & Advanced Euclidean Al-


gorithm.
def gcd(a, b):
if a == 0:
return b

return gcd(b % a, a)

[31]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


a = 31
b = 9
print("gcd(", a, ",", b, ") = ", gcd(a, b))

Output :-

Practical – 14 : Implement Deffie-Hellman algorithm for key ex-


change with small number.
if __name__ == '__main__':
P = 32
G = 89
print('The Value of P is :%d' % (P))

[32]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


print('The Value of G is :%d' % (G))
a = 14
print('The Private Key a for Alice is :%d' % (a))
x = int(pow(G, a, P))
b = 3
print('The Private Key b for Bob is :%d' % (b))
y = int(pow(G, b, P))
ka = int(pow(y, a, P))
kb = int(pow(x, b, P))
print('Secret key for the Alice is : %d' % (ka))
print('Secret Key for the Bob is : %d' % (kb))

Output :-

Practical – 15 : Implement RSA algorithm with small number.


import math
message = int(input("Enter the message to be encrypted: "))
p = 11
q = 7
e = 3
n = p * q

[33]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya


def encrypt(me):
en = math.pow(me, e)
c = en % n
print("Encrypted Message is: ", c)
return c
print("Original Message is: ", message)
c = encrypt(message)

Output :-

Practical – 16 : Study various encryption/decryption tools available


online (E.g. www.cryptool.org).

[34]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

[35]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

[36]
Cryptography and Network Security 19BECE30543

CE603-N Kishan Jogiya

[37]

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy