Name: Aman Tripathi
Roll no: 5508
Class : TYCS
Subject: Information & Network Security
Practical No. 1
Aim : Write programs to implement the following Substitution Cipher
Technique :
A) Ceasar Cipher Technique
#Ceaser Cipher Technique def
encrypt_func(txt, sh):
result = ""
#transverse the plain txt
for i in range(len(txt)):
char = txt[i]
#encypt_func uppercase characters in plain txt
if (char.isupper()):
result += chr(ord(char) + sh - 65) % 26 + 65)
#encypt_func lowercase characters in plain txt
else:
result += chr((ord(char) + sh - 97) % 26 + 97)
return result
#check the above function
txt = "CEASER CIPHER EXAMPLE" sh
=3
print("Plain txt : " + txt)) print("Shift
pattern : " + str(sh)) print("Cipher : " +
encrypt_func(txt, sh))
Output :
B) Monoalphabetic Cipher :
monoalpha_cipher = {
'a' :
'm','b':'n','c':'b','d':'v','e':'c','f':'x','g':'z','h':'a','i':'s','j':'d','k':'f','l':'g','m':'h','n':'j','o':'k','p':'l','
q':'p','r':'o','s':'i','t':'u','u':'y','v':'t','w':'r','x':'e','y':'w','z':'q','':'',
}
inverse_monoalpha_cipher ={} for key,
value in monoalpha_cipher.items():
inverse_monoalpha_cipher[value] = key
message = "This is an easy problem"
encrypted_message = [] for letter in
message :
#print(monoalpha_cipher.get(letter, letter))
encrypted_message.append(monoalpha_cipher.get(letter, letter))
print(''.join(encrypted_message))
encrypted_message = "Tasi si mj cmiw lokngch" decrypted_message = [] for
letter in encrypted_message :
decrypted_message.append(inverse_monoalpha_cipher.get(letter, letter))
print(''.join(decrypted_message)) encrypted_message = "Tasi si mj cmiw
lokngch" decrypted_message = [] for letter in encrypted_message :
decrypted_message.append(inverse_monoalpha_cipher.get(letter, letter))
print(''.join(decrypted_message))
Output :
Encryption
Decryption
Practical No. 2
Aim : Write Program to implement Substitution Cipher Techniques Vernam
Cipher (One Time Pad)
Source Code : def
stringEncryption(text, key):
cipherText = "" cipher = []
for i in range(len(key)):
cipher.append(ord(text[i]) - ord('A') + ord(key[i]) - ord('A'))
for i in range(len(key)): if cipher[i] > 25: cipher[i] =
cipher[i] - 26
for i in range(len(key)):
x = cipher[i] + ord('A')
cipherText+=chr(x)
return cipherText
def stringDecryption(s, key):
plainText = "" plain
= [] for i in
range(len(key)):
plain.append(ord(s[i]) - ord('A') - (ord(key[i]) - ord('A')))
for i in range(len(key)): if (plain[i] < 0):
plain[i] = plain[i] + 26
for i in range(len(key)):
x = plain[i] + ord('A')
plainText+=chr(x)
return plainText
plainText = "Hello"
key = "Money"
encryptedText = stringEncryption(plainText.upper(), key.upper())
print("Cipher Text - "+ encryptedText)
print("Message - "+ stringDecryption(encryptedText, key.upper()))
Output :
Practical No. 3
Aim : Write programs to implement the following Transposition Cipher
Technique : Rail Fence Cipher.
Source Code :
#Rail Fence Cipher Encryption and Decryption 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("attact at once", 2))
print(encryptRailFence("defend the east wall", 3))
print(decryptRailFence("atc toctaka ne", 2))
print(decryptRailFence("dnhaweedtees alf tl", 3))
Output :
Practical No. 4
Aim : Write programs to implement the following Transposition Cipher
Technique : Simple Columnar Technique.
Source Code : #
Columnar Transposition
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)]
print(matrix) 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 =
"attack at once" cipher =
encryptMessage(msg) print("Encrypted
Message : {}".format(cipher))
print("Decrypted Message : {}".format(decryptMessage(cipher)))
Output :
Practical No. 5
Aim : Write a program to encrypt and decrypt strings using the DES
algorithm.
Source Code :
package des;
import java.io.*;
import javax.crypto.*;
public class DES { Cipher
ecipher,dcipher; byte[] buf =
new byte[1024]; public
DES(SecretKey key) {
try {
ecipher =Cipher.getInstance("DES");
ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher
= Cipher.getInstance("DES");
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception e){
System.out.println("Exception Occur : " + e);
}
}
public void encrypt(InputStream in, OutputStream out) {
try {
int numRead = 0; out = new
CipherOutputStream(out,ecipher);
while((numRead = in.read(buf)) >= 0){
out.write(buf,0,numRead);
}
out.close();
}
catch (Exception e){
System.out.println("Exception Occur : " + e);
}
}
public void decrypt(InputStream in, OutputStream out) {
try {
int numRead = 0; in = new
CipherInputStream(in,dcipher);
while((numRead = in.read(buf)) >= 0){
out.write(buf,0,numRead);
}
out.close();
}
catch (Exception e) {
System.out.println("Exception Occur : " + e);
}
}
public static void main(String[] args) {
try {
System.out.println("Encryption and Decryption using DES");
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
DES encrypter = new DES(key); encrypter.encrypt(new
FileInputStream("D:\\tycs\\New Folder\\DES\\text.txt"),new
FileOutputStream("ciphertext.txt")); encrypter.decrypt(new
FileInputStream("ciphertext.txt"),new
FileOutputStream("text2.txt"));
System.out.println("Encryption and Decryption done successfully");
}
catch (Exception e){
System.out.println("Exception Occur : " + e);
}
}
}
Output :
Practical No. 6
Aim : Write a program to encrypt and decrypt strings using the AES
algorithm.
Source Code :
package aes;
import java.io.*;
import javax.crypto.*;
public class AES {
Cipher ecipher,dcipher;
byte[] buf = new byte[1024];
public AES(SecretKey key) {
try {
ecipher =Cipher.getInstance("AES");
ecipher.init(Cipher.ENCRYPT_MODE, key); dcipher
= Cipher.getInstance("AES");
dcipher.init(Cipher.DECRYPT_MODE, key);
}
catch (Exception e){
System.out.println("Exception Occur : " + e);
}
}
public void encrypt(InputStream in, OutputStream out) {
try {
int numRead = 0; out = new
CipherOutputStream(out,ecipher);
while((numRead = in.read(buf)) >= 0){
out.write(buf,0,numRead);
}
out.close();
}
catch (Exception e){
System.out.println("Exception Occur : " + e);
}
}
public void decrypt(InputStream in, OutputStream out) {
try {
int numRead = 0; in = new
CipherInputStream(in,dcipher);
while((numRead = in.read(buf)) >= 0){
out.write(buf,0,numRead);
}
out.close();
}
catch (Exception e) {
System.out.println("Exception Occur : " + e);
}
}
public static void main(String[] args) {
try {
System.out.println("Encryption and Decryption using AES");
SecretKey key = KeyGenerator.getInstance("AES").generateKey();
AES encrypter = new AES(key); encrypter.encrypt(new
FileInputStream("D:\\tycs\\New Folder\\DES\\test.txt"),new
FileOutputStream("ciphertext2.txt")); encrypter.decrypt(new
FileInputStream("ciphertext2.txt"),new
FileOutputStream("text3.txt"));
System.out.println("Encryption and Decryption done successfully");
}
catch (Exception e){
System.out.println("Exception Occur : " + e);
}
}
Output :
Practical No. 7
Aim : Write a program to implement an RSA algorithm to perform encryption
/ decryption of a given string.
Source Code :
package rsa;
import java.math.*;
import java.security.*;
public class RSA {
SecureRandom r;
BigInteger p,q,p1,q1,n,n1,e,d,msg,ct,pt;
public RSA() {
int bitLength = 512;
int certainty = 100;
r = new SecureRandom(); p = new
BigInteger(bitLength,certainty,r); q = new
BigInteger(bitLength,certainty,r);
n = p.multiply(q);
System.out.println("Prime no. P is : " + p.intValue());
System.out.println("Prime no. Q is : " + q.intValue());
System.out.println("N = P * Q is : " + n.intValue());
p1 = p.subtract(new BigInteger("1"));
q1 = q.subtract(new BigInteger("1"));
n1 = p1.multiply(q1); e = new
BigInteger("2");
while(n1.gcd(e).intValue() > 1 || e.compareTo(n1) != -1)
{
e = e.add(new BigInteger("1"));
}
System.out.println("Public Key is ("+n.intValue()+","+e.intValue()+")");
d = e.modInverse(n1);
System.out.println("Private Key is ("+n.intValue()+","+d.intValue()+")");
msg = new BigInteger("5");
ct = encrypt();
System.out.println("Encrypted text is : " + ct.intValue());
pt = decrypt(ct);
System.out.println("Decrypted text is : " + pt.intValue());
}
public BigInteger encrypt()
{
return msg.modPow(e,n);
}
public BigInteger decrypt(BigInteger ct)
{
return ct.modPow(d,n);
}
public static void main(String[] args) {
new RSA();
}
}
Output :
Practical No. 8
Aim : Write a program to implement the Diffie-Hellman Key Agreement
algorithm to generate symmetric keys.
Source Code :
package diffiehellman;
import java.io.*;
import java.math.BigInteger;
public class DiffieHellman {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter prime number 1 : ");
BigInteger p = new BigInteger(br.readLine());
System.out.println("Enter prime number 2 : ");
BigInteger q = new BigInteger(br.readLine());
System.out.println("Enter the value of private key a : ");
BigInteger a = new BigInteger(br.readLine());
BigInteger a1 = q.modPow(a, p);
System.out.println("Public key a1 is = " + a1);
System.out.println("Enter value of private key b : ");
BigInteger b = new BigInteger(br.readLine());
BigInteger b1 = q.modPow(b, p);
System.out.println("Public key b1 is = " + b1);
BigInteger x = b1.modPow(a, p);
System.out.println("Symmetric key calculated at alice side : " + x);
BigInteger y = a1.modPow(b, p);
System.out.println("Symmetric key calculated at bob side : " + y);
System.out.println("Diffie Hellman secret key encryption has taken");
if (x.equals(y))
{
System.out.println("Hellman both key are similar");
}
else
{
System.out.println("Hellman keys are not similar");
}
}
}
Output :
Practical No. 9
Aim : Write a program to implement the MD5 algorithm to generate
symmetric keys.
Source Code :
MD5Send : package
md5send;
import java.io.*;
import java.security.*;
public class MD5Send {
public static void main(String[] args) {
String input;
byte buffer[] = new byte[1024];
System.out.println("Enter the message to be send : ");
try
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
input = br.readLine();
FileOutputStream fos = new FileOutputStream("abc.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
MessageDigest md = MessageDigest.getInstance("MD5");
buffer = input.getBytes(); md.update(buffer);
oos.writeObject(input); //original data
oos.writeObject(md.digest()); //fingerprint data
System.out.println("Message send successfully !!!!");
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output :
MD5Recive : (In the same package)
package MD5Send;
import java.io.*;
import java.security.*;
public class MD5Recive { public
static void main(String args[]) {
byte dig[] = new byte[1024];
try
{
FileInputStream fis = new FileInputStream("abc.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
Object obj = ois.readObject();
String data = (String) obj;
System.out.println("Recive Data : " + data);
obj = ois.readObject();
dig = (byte[])obj;
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(data.getBytes());
if(MessageDigest.isEqual(md.digest(), dig))
{
System.out.println("Message retrived successfully !!");
ois.close();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Output :