You are on page 1of 15

DAYALBAGH EDUCATIONAL INSTITUTE

Deemed University , Agra

Cryptography & Network


security lab
                 
SESSION : 2019-2022

Course Code       :      ITV603


CLASS      :     B.Voc - IOT

   By – Kanchan Pal
1904700
Assignment – 1
Submit your own complete source code in a language of your choice
for implementing:

1. Classical Substitution Cipher.


plain_text = input("Please enter your plaintext: ")
secret = input("Please enter your key: ")
alphabet = "abcdefghijklmnopqrstuvwxyz"
ciphertext = ""
while (isinstance(int(secret), int) == False):
secret = input("Please enter your key (integers only!): ")

secret = int(secret)

new_ind = 0
for i in plaintext:
if i.lower() in alphabet:
new_ind = alphabet.index(i) + secret
ciphertext += alphabet[new_ind % 26]
else:
ciphertext += i
print("The ciphertext is: " + ciphertext)

2. Classical Transposition Cipher.

import pyperclip
def main():
myMessage ='DAYALBAGH EDUCATION INSTITUTE'
myKey = 2
ciphertext = encryptMessage(myKey, myMessage)
print("Cipher Text is")
print(ciphertext + '|')
pyperclip.copy(ciphertext)

def encryptMessage(key, message):


ciphertext = [''] * key
for col in range(key):
position = col
while position < len(message):
ciphertext[col] += message[position]
position += key
return ''.join(ciphertext) #Cipher text
if __name__ == '__main__':
main()

Assignment – 2

Submit your own complete source code in a language of your choice


for implementing:

1. Caesar Cipher.

def encypt_func(txt, s):


result = ""
for i in range(len(txt)):
char = txt[i]
if (char.isupper()):
result += chr((ord(char) + s - 64) % 26 + 65)
else:
result += chr((ord(char) + s - 96) % 26 + 97)
return result
txt = "CEASER CIPHER EXAMPLE"
s=4
print("Plain txt : " + txt)
print("Shift pattern : " + str(s))
print("Cipher: " + encypt_func(txt, s)
2. Modified Caesar Cipher.

plaintext = input("Please enter your plaintext: ")


shift = input("Please enter your key: ")
alphabet = "abcdefghijklmnopqrstuvwxyz
ciphertext = ""
while isinstance(int(shift), int) == False:
shift = input("Please enter your key (integers only!): ")

shift = int(shift)

new_ind = 0
for i in plaintext:
if i.lower() in alphabet:
new_ind = alphabet.index(i) + shift
ciphertext += alphabet[new_ind % 26]
else:
ciphertext += i
print("The ciphertext is: " + ciphertext)
Assignment-3
Submit your own complete source code in a language of your choice
for implementing:

1. Rail Fence Cipher.

# Rail Fence Cipher Encryption


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 = []
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] != '*'):
result.append(rail[row][col])
col += 1
if dir_down:
row += 1
else:
row -= 1
return("".join(result))
if __name__ == "__main__":
print(encryptRailFence("Neelu", 2))
print(encryptRailFence("Dayalbagh Educational Institute ", 3))
2. Simple Columnar Cipher.

#ex4 simple columnar


import math
key = "HACK"
def encryptMessage(msg):
cipher = ""
k_indx = 0
msg_len = float(len(msg))
msg_lst = list(msg)
key_lst = sorted(list(key))
col = len(key)
row = int(math.ceil(msg_len / col))
fill_null = int((row * col) - msg_len)
msg_lst.extend('_' * fill_null)

matrix = [msg_lst[i: i + col]


for i in range(0, len(msg_lst), col)]
for _ in range(col):
curr_idx = key.index(key_lst[k_indx])
cipher += ''.join([row[curr_idx]
for row in matrix])
k_indx += 1
return cipher
def decryptMessage(cipher):
msg = ""
k_indx = 0
msg_indx = 0
msg_len = float(len(cipher))
msg_lst = list(cipher)
col = len(key)
row = int(math.ceil(msg_len / col))
key_lst = sorted(list(key))
dec_cipher = []
for _ in range(row):
dec_cipher += [[None] * col]
for _ in range(col):
curr_idx = key.index(key_lst[k_indx])
for j in range(row):
dec_cipher[j][curr_idx] = msg_lst[msg_indx]
msg_indx += 1
k_indx += 1
try:
msg = ''.join(sum(dec_cipher, []))
except TypeError:
raise TypeError("This program cannot",
"handle repeating words.")
null_count = msg.count('_')

if null_count > 0:
return msg[: -null_count]
return msg
msg = "I AM VERY HAPPY"

cipher = encryptMessage(msg)
print("Encrypted Message: {}".
format(cipher))

print("Decryped Message: {}".


format(decryptMessage(cipher)))
Assignment-4
Submit your own complete source code in a language of your choice
for implementing:

1. Monoalphabetic Cipher.

monoalpha={'a':'m','b':'n','c':'b','d':'j','e':'x','f':'k','g':'l','h':'a','i':'s','j':'n','k':'o','l':'p','m':'h','n':'b','o'
:'r','p':'q','q':'z','r':'w','s':'i','t':'v','u':'t','v':'d','w':'y','x':'f','y':'u','z':'g',' ':' ',}

inverse_monoalpha={}
for i in monoalpha:
    inverse_monoalpha[monoalpha[i]]=i

msg=input("enter your msg:  ")


encrypt_msg=[]
for letter in msg:
    encrypt_msg.append(monoalpha.get(letter,letter))
print(''.join(encrypt_msg))

decrypt_msg=[]
for letter in encrypt_msg:
    decrypt_msg.append(inverse_monoalpha.get(letter,letter))
print(''.join(decrypt_msg))

2. Polyalphabetic Cipher.
def encrypt(plaintext, key):
    key_length = len(key)
    key_as_int = [ord(i) for i in key]
    plaintext_int = [ord(i) for i in plaintext]
    ciphertext = ""
    for i in range(len(plaintext_int)):
        value = (plaintext_int[i] + key_as_int[i % key_length]) % 26
        ciphertext += chr(value + 65)
    return ciphertext

def decrypt(ciphertext, key):


    key_length = len(key)
    key_as_int = [ord(i) for i in key]
    ciphertext_int = [ord(i) for i in ciphertext]
    plaintext = ""
    for i in range(len(ciphertext_int)):
        value = (ciphertext_int[i] - key_as_int[i % key_length]) % 26
        plaintext += chr(value + 65)
    return plaintext

print(encrypt("hello","khushi"))

Assignment-5
Submit your own complete source code in a language of your choice
for implementing:

1.Diffie Hellman key exchange Algorithm.


Code(in java)-
// This program calculates the Key for two persons
// using the Diffie-Hellman Key exchange algorithm
class GFG{

// Power function to return value of a ^ b mod P


private static long power(long a, long b, long p)
{
if (b == 1)
return a;
else
return (((long)Math.pow(a, b)) % p);
}

// Driver code
public static void main(String[] args)
{
long P, G, x, a, y, b, ka, kb;

// Both the persons will be agreed upon the


// public keys G and P

// A prime number P is taken


P = 23;
System.out.println("The value of P:" + P);

// A primitive root for P, G is taken


G = 9;
System.out.println("The value of G:" + G);

// Alice will choose the private key a


// a is the chosen private key
a = 4;
System.out.println("The private key a for Alice:" + a);

// Gets the generated key


x = power(G, a, P);

// Bob will choose the private key b


// b is the chosen private key
b = 3;
System.out.println("The private key b for Bob:" + b);

// Gets the generated key


y = power(G, b, P);

// Generating the secret key after the exchange


// of keys
ka = power(y, a, P); // Secret key for Alice
kb = power(x, b, P); // Secret key for Bob

System.out.println("Secret key for the Alice is:" + ka);


System.out.println("Secret key for the Bob is:" + kb);
}
}

2. RSA Algorithm.
Code(in java)-
/ Java Program to Implement the RSA Algorithm
import java.math.*;
import java.util.*;

class RSA {
public static void main(String args[])
{
int p, q, n, z, d = 0, e, i;

// The number to be encrypted and decrypted


int msg = 12;
double c;
BigIntegermsgback;

// 1st prime number p


p = 3;

// 2nd prime number q


q = 11;
n = p * q;
z = (p - 1) * (q - 1);
System.out.println("the value of z = " + z);

for (e = 2; e < z; e++) {

// e is for public key exponent


if (gcd(e, z) == 1) {
break;
}
}
System.out.println("the value of e = " + e);
for (i = 0; i<= 9; i++) {
int x = 1 + (i * z);

// d is for private key exponent


if (x % e == 0) {
d = x / e;
break;
}
}
System.out.println("the value of d = " + d);
c = (Math.pow(msg, e)) % n;
System.out.println("Encrypted message is : " + c);

// converting int value of n to BigInteger


BigInteger N = BigInteger.valueOf(n);

// converting float value of c to BigInteger


BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
System.out.println("Decrypted message is : "
+ msgback);
}

static int gcd(int e, int z)


{
if (e == 0)
return z;
else
return gcd(z % e, e);
}
}

Assignment-6
Submit your own complete source code in a language of your choice
for implementing:
1. Communication between two controllers using I2C in Simplex
Mode.

2. Communication between two controllers using I2C in Half Duplex


Mode.

3.

Communication between two controllers using I2C in Full Duplex


Mode

You might also like