0% found this document useful (0 votes)
44 views41 pages

Lab Manual - NSC Btics501sddsa

The document is a lab manual for the Network Security and Cryptography course at Shri Vaishnav Institute of Information Technology, detailing various cryptographic techniques and their implementations. It includes experiments on Caesar Cipher, Columnar Transposition, Rail Fence Technique, and Homophonic Substitution, providing explanations and programming examples for each. The manual is intended for the July-Dec 2025 session and is authored by Dr. Gaurav Shrivastava.

Uploaded by

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

Lab Manual - NSC Btics501sddsa

The document is a lab manual for the Network Security and Cryptography course at Shri Vaishnav Institute of Information Technology, detailing various cryptographic techniques and their implementations. It includes experiments on Caesar Cipher, Columnar Transposition, Rail Fence Technique, and Homophonic Substitution, providing explanations and programming examples for each. The manual is intended for the July-Dec 2025 session and is authored by Dr. Gaurav Shrivastava.

Uploaded by

dormouse06480
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Shri Vaishnav Vidyapeeth Vishwavidyalaya, Indore (MP)

Think Excellence. Live Excellence.

Shri Vaishnav Institute of Information Technology


Department of Information Security & Cloud Computing

Lab Manual
Network Security and Cryptography
(BTCS503)
Session July-Dec 2025

Subject Teacher
Dr. Gaurav Shrivastava
B.E. (CSE), M.E. (IT), Ph.D.
Associate Professor (IS & CC Dept.)
SVIIT-SVVV, Indore
INDEX

Ex. No. Name of the Experiment

Write a Program to implement Ceaser Cipher. Explain CeaserCipher &


1.
Modified Version of Ceaser Cipher.
Write a Program to implement Simple Columner
2. Transposition technique. Explain Simple Columnar
Transposition Technique with multiple rounds.
Write a Program to implement Rail fence technique. ExplainRail fence
3.
technique with Example.
Write a Program to implement Homophonic substitutiontechnique.
4.

5. Write a Program to implement Polygram substitution cipher.

6. Write a Program to implement Polyalphabetic substitution.

7. Write a Program to implement Hill Cipher.

Write a Program to implement DES Algorithm. Explain II-DES & III-


8.
DES Algorithms.
Write a Program to implement Simple RSA Algorithm withsmall
9.
numbers.

Write a Program to implement Simple Diffie- Hellman KeyExchange


10.
Algorithms with small numbers.
EXPERIMENT -1
Aim :- Write a program to implement Ceasar Cipher. How do you
convert plain text to Ceaser cipher.

Introduction :-
Ciphertext is encrypted text transformed from plaintext using an encryption algorithm. Ciphertext
can't be read until it has been converted into plaintext (decrypted) with a key. The decryption
cipher is an algorithm that transforms the ciphertext back into plaintext.
The term cipher is sometimes used as a synonym for ciphertext. However, it refers to the method
of encryption rather than the result.

Caesar Cipher Technique

The Caesar Cipher technique is one of the earliest and simplest methods of encryption technique.
It’s simply a type of substitution cipher, i.e., each letter of a given text is replaced by a letter
with a fixed number of positions down the alphabet.

For example with a shift of 1, A would be replaced by B, B would become C, and so on. The
method is apparently named after Julius Caesar, who apparently used it to communicate with his
officials.
Thus to cipher a given text we need an integer value, known as a shift which indicates the number
of positions each letter of the text has been moved down.
Conversion of Plain text into Cipher text
▪ In order to encrypt a plaintext letter, the sender positions the sliding ruler underneath the first
set of plaintext letters and slides it to LEFT by the number of positions of the secret shift.
▪ The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath.
The result of this process is depicted in the following illustration for an agreed shift of three
positions. In this case, the plaintext ‘studentproject’ is encrypted to the ciphertext
‘vwxghqwsurmhfw’. Here is the ciphertext alphabet for a Shift of 3 –

Plaintext a b c d e f g h i j k l m n o p q r s t u v w x y z
Alphabe
t
Ciphertext D E F G H I J K L M N O P Q R S T U V W X Y Z A B C
Alphabet

▪ On receiving the ciphertext, the receiver who also knows the secret shift, positions his sliding
ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift number, 3
in this case.

▪ He then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath.
Hence the ciphertext ‘vwxghqwsurmhfw’ is decrypted to ‘studentproject’. To decrypt a
message encoded with a Shift of 3, generate the plaintext alphabet using a shift of ‘-3’ as shown
below –

Plaintext A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Alphabe
t
Ciphertext x y z a b c d e f g h i j k l m n o p q r s t u v w
Alphabet

Program to implement Caesar Cipher


#include<iostream>
#include<string.h>
using namespace std;
int main()
{
cout<<"Enter the message:\n";
char msg[100];
[Link](msg,100);
int i, j, length,choice,key;
cout << "Enter key:
";cin >> key;
length = strlen(msg);

cout<<"Enter your choice \n1. Encryption \n2. Decryption \n";


cin>>choice;
if (choice==1)
{
char ch;
for(int i = 0; msg[i] != '\0'; ++i)
{
ch = msg[i];

if (ch >= 'a' && ch <= 'z')


{
ch = ch +
key;if (ch >
'z')
{
ch = ch - 'z' + 'a' - 1;
}
msg[i] = ch;
}

else if (ch >= 'A' && ch <= 'Z')


{
ch = ch +
key;if (ch >
'Z'){
ch = ch - 'Z' + 'A' - 1;
}
msg[i] = ch;
}
}
printf("Encrypted message: %s", msg);
}
else if (choice == 2)
{
char ch;
for(int i = 0; msg[i] != '\0'; ++i)
{
ch = msg[i];

if(ch >= 'a' && ch <= 'z')


{ch = ch - key;
if(ch < 'a')
{
ch = ch + 'z' - 'a' + 1;
}
msg[i] = ch;
}

else if(ch >= 'A' && ch <= 'Z')


{
ch = ch -
key;if(ch <
'A')
{
ch = ch + 'Z' - 'A' + 1;
}
msg[i] = ch;
}
}
cout << "Decrypted message: " << msg;
}
}
Output :-
EXPERIMENT - 2
Aim :- Write a Program to implement Simple Columner
Transposition technique. Explain Simple Columnar Transposition
Technique with multiple rounds.

Introduction :-
The columnar transposition cipher is a fairly simple, easy to implement cipher. It is a
transposition cipher that follows a simple rule for mixing up the characters in the plaintext to
form the ciphertext.
Columnar Transposition involves writing the plaintext out in rows, and then reading the
ciphertext off in columns. In its simplest form, it is the Route Cipher where the route is to
read down each column in order.

Example –
The key for the columnar transposition cipher is a keyword e.g. GERMAN. The row length
that is used is the same as the length of the keyword. To encrypt a piece of text, e.g.

this is network security file

we write it out in a special way in a number of rows (the keyword here is GERMAN):

G E R M A N

t h i s i s

n e t w o r

k s e c u r

i t y f i l

e x x x x x

In the above example, the plaintext has been padded so that it neatly fits in a rectangle. Thecolumns
are now reordered such that the letters in the key word are ordered alphabetically.
A E G M N R

i h t s s i
o e n w r t
u s k c r e
i t i f l y
x x e x x x

The ciphertext is read off along the columns:

iouixhestxtnkieswcfxiteyx

Program to implement Simple Columnar Transposition Technique.


import math
key = "GERMAN"
# Encryption
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([Link](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 =
[Link](key_lst[k_indx])cipher +=
''.join([row[curr_idx]
for row in matrix])
k_indx +=
1return cipher

# Decryption
def decryptMessage(cipher):
msg = ""
k_indx = 0
msg_indx = 0
msg_len = float(len(cipher))
msg_lst = list(cipher)
col = len(key)
row = int([Link](msg_len / col))
key_lst = sorted(list(key))
dec_cipher = []
for _ in range(row):
dec_cipher += [[None] *
col]for _ in range(col):
curr_idx =
[Link](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 = [Link]('_')
if null_count > 0:
return msg[: -null_count]
return msg
msg = "this is columnar transposition program"
cipher = encryptMessage(msg)
print("Encrypted Message: {}".
format(cipher))
print("Decryped Message: {}".
format(decryptMessage(cipher)))

Output-

Simple Columnar Transposition with Multiple Rounds

To improve basic Simple columnar transposition technique, we can introduce more


complexity. The idea is to use the same basic procedure as used by the Simple columnar
transposition technique, but to do it more than once. That adds considerably more complexity
for the code breaker.

Write the plain text message row-by-row in grids of rectangle of a pre-defined size.

Read the message column by column. However, it need to be in the order of column 1, 2,
3,4,5,6 etc. It can be any random order such as 2, 6, 4, 3, 5, and 1.
The message obtain is the cipher text message of round 1 repeat step 1 and 2 as many
times as desire.

As we can see only addition to Simple columnar transposition technique is step 3, which
results in execution of algorithm more than once. This adds more complexity to the cipher
text.

More the number of rounds in this technique more complex are cipher text.
EXPERIMENT – 3
Aim :- Write a Program to implement Rail Fence Technique. Explain
Rail Fence Technique with example.
Introduction :-

The rail fence cipher (sometimes called zigzag cipher) is a transposition cipher that jumbles
up the order of the letters of a message using a basic algorithm.

The rail fence cipher works by writing your message on alternate lines across the page, and
then reading off each line in turn.

For example, let’s consider the plaintext “This is a secret message”.

To encode this message we will first write over two lines (the “rails of the fence”) as follows:

Note that all white spaces have been removed from the plain text.

The ciphertext is then read off by writing the top row first, followed by the bottom row:

For example, let us encrypt a name of one of the countries in Europe:


The United Kingdom.
Let's assume that the secret key is 3, so three levels of rails will be produced.

First, we will remove the empty spaces, and encrypt only the capitalized letters:

THEUNITEDKINGDOM
Next, the plaintext letters will form the shape of the fence:

T . . . N . . . D . . . G . . .
. H . U . I . E . K . N . D . M
. . E . . . T . . . I . . . O .
Then, the letters should be read row by row, starting from the top one. Finally, they ought to be
concatenated to form one ciphertext message. In our example, the calculated ciphertext sequence
would be:

TNDGHUIEKNDMETIO

To decrypt the message, the receiver should know the secret key, that is the number of levels of
the rail. Based on the number of rows and the ciphertext length, it is possible to reconstruct the
grid and fill it with letters in the right order (that is, in the same way as used by the sender during
encryption).

Program :-

#include<bits/stdc++.h>
using namespace std;

int main(){
int t,n,m,i,j,k,sum=0;
string s;
cout<<"Enter the message"<<'\n';
cin>>s;
cout<<"Enter key"<<'\n';
cin>>n;
vector<vector<char> > a(n,vector<char>([Link](),'
'));j=0;
int flag=0;
for(i=0;i<[Link]();i++
){
a[j][i] =
s[i];
if(j==n-1){
flag=1;
}
else
if(j==0)
flag=0;

if(flag==0)
{j++;
}
else j--;
}
for(i=0;i<n;i++){
for(j=0;j<[Link]();j++
){
if(a[i][j]!=' ')
cout<<a[i][j]
;
}
}
cout<<'\n';

return 0;
}

Output –
EXPERIMENT – 4
Aim :- Write a program to implement Homophonic substitution
technique.

Introduction :-

The one to one mapping of simple substitution cipher makes it susceptible to statistical
frequency based attacks. If the frequency distribution of simple substitution cipher is
manipulated in such a way that the ciphertext produces a random frequency distribution ,
then the frequency based attack will not work on such ciphers. The homophonic substitution
cipher is one such variant of the substitution cipher where the frequency distribution is
flattened in the resultant ciphertext.

Homophonic Substitution Cipher Technique :-

Homophonic substitution cipher is a much more complicated variant of substitution cipher


where, instead of using one to one mapping of simple substitution, one to many mapping is
used . In one to many mapping, each plaintext letter can be substituted with multiple
ciphertext symbols.

However, each ciphertext symbol can represent one and only one plaintext letter. Such
mapping tends to flatten the frequency statistics in the resulting ciphertext and consequently
makes the attacks based on statistical frequency based analysis more and more difficult.

An example of a homophonic substitution cipher is given in below , where we have used some
non-alphabetic symbols, since we require more than 26 ciphertext symbols. For the key in
given example , any of the symbols R, 3, or 9 can be substitutedfor a plaintext E, and either Y
or can be substituted for plaintext L. So, using this key, plaintext HELLO can be encrypted
as U96YB. In this case, a cryptanalyst has no indication that ciphertext 6 and Y both
represent the same plaintext letter.
➢ Program :-
class homophonic:
@staticmethod
def charTable():
return [
["A", ["†", "„", "§", "É"]],
[" ", ["Ú", "Ý", "Ü", "Þ"]],
["B", ["€", "¦", "È", "Ò"]],
["C", ["Š", "‡", "Ë", "Ï"]],
["D", ["ƒ", "‘", "¢", "Ê"]],
["E", ["Ž", ".", "£", "Ì"]],
["F", ["™", ":", "Ä", "Ö"]],
["G", [",", "^", "\"", "á"]],
["H", ["#", "!", "¤", "Å"]],
["I", ["@", "¥", "ã"]],
["J", ["A", "2", "À", "Ù"]],
["K", ["b", "1", "Á", "Õ"]],
["L", ["6", "8", "Â", "é"]],
["M", ["4", "0", "¿", "ù"]],
["N", ["5", "c", "»", "ç"]],
["O", ["z", "I", "º", "æ"]],
["P", ["š", "/", "¹", "à"]],
["Q", ["\\", "=", "¸", "û"]],
["R", ["+", "%", "µ", "Ø"]],
["S", ["*", ")", "³", "ê"]],
["T", ["]", "(", "²", "ì"]],
["U", ["}", "{", "ž", "Ð"]],
["V", ["_", "r", "¬", "Ñ"]],
["W", ["-", "&", "©", "×"]],
["X", ["~", "`", "«"]],
["Y", [">", "|", "®"]],
["Z", ["?", "<", "°"]],
["0", ["Æ", "Ç", "Ô"]],
["1", ["ä", "ø", "ï"]],
["2", ["ß", "õ", "ÿ"]],
["3", ["è", "ö", "ô"]],
["4", ["Ó", "þ", "ò"]],
["5", ["ë", "ü", "ó"]],
["6", ["í", "a", "ð"]],

["7", ["ñ", "ý", "î"]],


["8", ["÷", "n", "â"]],
["9", ["ú", "p", "å"]],
]

@staticmethod
def
encode(p
laintext):
import
random
result =
""
for each in [Link]():
for encodes in
[Link]():if
encodes[0] == each:
result +=
str([Link](encodes[1]
))break
return result

@staticmethod
def
decode(encryp
tedText):result
= ""
for eachNumber in encryptedText:
for encodes in
[Link]():if
eachNumber in
encodes[1]:
result +=
encodes[
0]break
return result

if name == '
main ':import
textwrap
plainText = "This is a homophonic substitution cipher text ,a experiment of
networksecurity and cryptography , written by khushi verma"

encoded = [Link](plainText)
print('\033[91m'+"Encoded text:\n",
[Link](encoded, 200))
print('\033[92m'+"Decoded text:\n", [Link]([Link](encoded), 200))

Output :-
EXPERIMENT – 5
Aim :- Write a program to implement Polygram substitution cipher.
Introduction :-

A polygram substitution cipher is a cryptosystem in which blocks of characters are substituted


in groups. For instance (for a particular key) AA could map to NO, AB to IR, JU toAQ, etc.
These cryptosystems make cryptanalysis harder by destroying the single character
frequencies, preserved under simple substitution ciphers. In Polygram Substitution Cipher
technique, a block of alphabets is replaced with another block. For instance, BECAUSE
could be replaced by XAYWQOA, but CAUSE could be replaced by totally different cipher
IGAYK. This is true despite the last five characters of the two blocks of text (CAUSE) being
the same. This shows that in Polygram Substitution Cipher, thereplacement of plain text
happens block by block rather than character by character. Polygram Substitution Cipher
Technique replaces one block of plain text with a block of cipher text.

Program :-

#include<stdio.h>
#include<string.h
>int main()
{
char msg[] = "THECRAZYPROGRAMMER";
char key[] = "HELLO";
int msgLen = strlen(msg), keyLen = strlen(key), i, j;

char newKey[msgLen], encryptedMsg[msgLen], decryptedMsg[msgLen];

//generating new key


for(i = 0, j = 0; i < msgLen; ++i, ++j){if(j ==
keyLen)j = 0;

newKey[i] = key[j];
}

newKey[i] = '\0';

//encryption
for(i = 0; i < msgLen; ++i)
encryptedMsg[i] = ((msg[i] + newKey[i])

% 26) + 'A';encryptedMsg[i] = '\0';

//decryption
for(i = 0; i < msgLen; ++i)
decryptedMsg[i] = (((encryptedMsg[i] - newKey[i]) + 26) % 26) + 'A';

decryptedMsg[i] = '\0';

printf("Original Message:
%s", msg);printf("\nKey:
%s", key);
printf("\nNew Generated Key: %s",
newKey); printf("\nEncrypted Message:
%s", encryptedMsg);printf("\nDecrypted
Message: %s", decryptedMsg);

return 0;
}

Output -
EXPERIMENT – 6
Aim :- Write a program to implement Polyalphabetic Substitution.

Introduction :-

A poly-alphabetic cipher is any cipher based on substitution, using several substitution


alphabets. In polyalphabetic substitution ciphers, the plaintext letters are enciphered
differently based upon their installation in the text. Rather than being a one-to-one
correspondence, there is a one-to-many relationship between each letter and its substitutes.

Vigenere cipher is one of the simplest and popular algorithms in polyalphabetic cipher. In this
approach, the alphabetic text is encrypted using a sequence of multiple Caesar ciphers based
on the letters of a keyword.

The Caesar cipher restoring each letter in the plaintext with the letters standing constant
position to the right in the alphabet. This shift is implemented modulo 26. For instance, in a
Caesar cipher of shift 3, A can become D, B can become E and so on.

Program :-

#include<stdio.h>
#include<conio.h>
#include<string.h
>int main()
{
char pt[20]={'\0'},ct[20]={'\0'},key[20]={'\0'},rt[20]={'\0'};
int i,j;

printf("\n enter the plain text:");scanf("%s",pt);


printf("\n enter the key:");scanf("%s",key);

//length of plaintext equal to length of keyj=0;


for(i=strlen(key);i<strlen(pt);i++)
{
if(j==strlen(key))
{
j=0
;
}
key[i]=key[j]
;j++;
}
printf("\n new key is:%s",key);

//converting plain text to cipher text (encryption)for(i=0;i<strlen(pt);i++)


{
ct[i]=(((pt[i]-97)+(key[i]-97))%26)+97;
}
printf("\n \n cipher text is:%s",ct);

//converting cipher text to plain text (decryption)for(i=0;i<strlen(ct);i++)


{
if(ct[i]<key[i])
{
rt[i]=26+((ct[i]-97)-(key[i]-97))+97;
}
else
rt[i]=(((ct[i]-97)-(key[i]-97))%26)+97;
}
printf("\n \n plain text is:%s",rt);

Output :-
EXPERIMENT – 7
Aim :- Write a program to implement Hill Cipher.
Introduction :-

In classical cryptography, the hill cipher is a polygraphic substitution cipher based on Linear
Algebra. It was invented by Lester S. Hill in the year 1929. In simple words, it is a
cryptographyalgorithm used to encrypt and decrypt data for the purpose of data security.

The algorithm uses matrix calculations used in Linear Algebra. In hill cipher algorithm every
letter (A-Z) is represented by a number moduli 26. Usually, the simple substitution scheme is
used where A = 0, B = 1, C = 2…Z = 25 in order to use 2x2 key matrix.

Generally, the below-mentioned structure of numbers and letters are used in the Hill Cipher
Encryption, but this can be modified as per requirement.

For encrypting a message, one starts with each block having n letters and then multiplied
with an n x n matrix, in parallel with modulus 26. Subsequently, each block needs to be
multiplied by the inverse matrix for decryption.

Steps for Encryption :-

Step 1: Let's say our key text (3x3) is GYBNQKURP. Convert this key using a
substitutionscheme into a 3x3 key matrix as shown below:
Step 2: Now, we will convert our plain text into vector form. Since the key matrix is 3x3, the
vector must be 3x1 for matrix multiplication.

Step 3: Multiply the key matrix with each 3x1 plain text vector, and take the modulo of result
(3x1 vectors) by 26. Then concatenate the results, and we get the encrypted or ciphertext as
POH.

Steps for Decryption :-

Step 1: To decrypt the message, we turn the ciphertext back into a vector, then simply
multiply by the inverse matrix of the key [Link] inverse of the matrix used in the
previous example is:

Step 2: For the previous Ciphertext ‘POH’:

which gives us back ‘ACT’.


Program to implement 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]) %
65k += 1
def encrypt(messageVector):
for i in range(3):
for j in range(1):
cipherMatrix[i][j] =
0for 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]) %
65encrypt(messageVector)
CipherText = []
for i in range(3):
[Link](chr(cipherMatrix[i][0] +
65))print("Ciphertext: ", "".join(CipherText))
def main():
message =
"ACT"
key = "GYBNQKURP"
HillCipher(message,
key)if name == "
main ":
main()

Output –
EXPERIMENT – 8
Aim :- Write a program to implement DES Algorithm. Explain II-
DES and III-DES Algorithms.
Introduction :-

DES is a block cipher and encrypts data in blocks of size of 64 bits each, which means 64
bits of plain text go as the input to DES, which produces 64 bits of ciphertext. The same
algorithm and key are used for encryption and decryption, with minor differences. The key
length is 56 bits. The basic idea is shown in the figure:

We have mentioned that DES uses a 56-bit key. Actually, the initial key consists of 64 bits.
However, before the DES process even starts, every 8th bit of the key is discarded to produce
a 56-bit key. That is bit positions 8, 16, 24, 32, 40, 48, 56, and 64 are discarded.
Program to implement DES algorithm :-

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

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] ch = ch + s[i
+ 2] ch = ch +
s[i + 3]
hex = hex +

mp[ch]return hex

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

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

def permute(k, arr, n):


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

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

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

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]

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]

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]

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

[[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],
[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_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)

pt = permute(pt, initial_perm, 64)


print("After initial permutation", bin2hex(pt))

left = pt[0:32]
right = pt[32:64]
for i in range(0, 16):
right_expanded = permute(right, exp_d, 48)

xor_x = xor(right_expanded, rkb[i])

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 + 2] + xor_x[j * 6 + 3] + xor_x[j * 6
+ 4]))
val = sbox[j][row][col]
sbox_str = sbox_str +

dec2bin(val)sbox_str = permute(sbox_str,

per, 32)

result = xor(left, sbox_str)


left = result

if(i != 15):
left, right = right, left
print("Round ", i + 1, " ",
bin2hex(left),
" ", bin2hex(right), " ",

rk[i])combine = left + right

cipher_text = permute(combine, final_perm, 64)


return cipher_text

pt = "123456ABCD132536"
key =
"AABB09182736CCDD"

key = hex2bin(key)

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]

key = permute(key, keyp, 56)

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

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]

left = key[0:28]
right =
key[28:56]rkb =
[]
rk = []
for i in range(0, 16):
left = shift_left(left, shift_table[i])
right = shift_left(right, shift_table[i])
combine_str = left + right
round_key = permute(combine_str, key_comp, 48)
[Link](round_key)
[Link](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)

Output :-
II – DES Algorithm :-
Double DES is a encryption technique which uses two instance of DES on same plain text.
In both instances it uses different keys to encrypt the plain text. Both keys are required at the
time of decryption. The 64 bit plain text goes into first DES instance which then converted
into a 64 bit middle text using the first key and then it goes to second DES instance which
gives 64 bit cipher text by using second key.
However double DES uses 112 bit key but gives security level of 2^56 not 2^112 and this is
because of meet-in-the middle attack which can be used to break through double DES.
III – DES Algorithm :-

Triple DES is a encryption technique which uses three instance of DES on same plain text. It
uses there different types of key choosing technique in first all used keys are different and
in second two keys are same and one is different and in third all keys are same.

Triple DES is also vulnerable to meet-in-the middle attack because of which it give total
security level of 2^112 instead of using 168 bit of key. The block collision attack can also be
done because of short block size and using same key to encrypt large size of text. It is also
vulnerable to sweet32 attack.
EXPERIMENT – 9
Aim :- Write a program to implement RSA Algorithm with small
numbers.
Introduction :-

RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually means that it


works on two different keys i.e. Public Key and Private Key. As the name describes that the
Public Key is given to everyone and the Private key is kept private.

The idea of RSA is based on the fact that it is difficult to factorize a large integer. The public
key consists of two numbers where one number is a multiplication of two large prime
numbers. And private key is also derived from the same two prime numbers. So if somebody
can factorize the large number, the private key is compromised. Therefore encryption
strength totally lies on the key size and if we double or triple the key size, the strength of
encryption increases exponentially. RSA keys can be typically 1024 or 2048 bits long, but
experts believe that 1024-bit keys could be broken in the near future. But till now it seems to
be an infeasible task.

Program to implement RSA Algorithm :-

import math

def gcd(a, h):


temp = 0
while(1):
temp = a % h
if (temp ==
0):
return h
a=h
h = temp

p=3
q=7
n = p*q
e=2
phi = (p-1)*(q-1)

while (e < phi):


if(gcd(e, phi) ==
1):break
else:
e = e+1
k=2
d = (1 +

(k*phi))/emsg =

12.0

print("Message data = ", msg)

c = pow(msg, e)
c = [Link](c, n)
print("Encrypted data = ", c)

m = pow(c, d)
m = [Link](m, n)
print("Original Message Sent = ",
m)

Output :-
EXPERIMENT – 10
Aim :- Write a program to implement Simple Diffie – Hellman Key
Exchange Algorithms with small numbers.
Introduction :-

The Diffie-Hellman algorithm is being used to establish a shared secret that can be used for
secret communications while exchanging data over a public network using the elliptic curve
to generate points and get the secret key using the parameters.
For the sake of simplicity and practical implementation of the algorithm, we will
consider only 4 variables, one prime P and G (a primitive root of P) and two private
values a and b.
P and G are both publicly available numbers. Users (say Alice and Bob) pick private
values a and b and they generate a key and exchange it publicly. The opposite person
receives the key and that generates a secret key, after which they have the same secret
key to encrypt.

Program to implement Simple Diffie – Hellman Key Exchange Algorithm :-

from random import randint

if name == ' main ':

P = 23

G=9

print('The Value of P is :%d'%(P))


print('The Value of G is :%d'%(G))

a=4
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 :-

===========================

You might also like