Lab Manual - NSC Btics501sddsa
Lab Manual - NSC Btics501sddsa
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
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.
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
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.
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
iouixhestxtnkieswcfxiteyx
# 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-
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.
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:
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.
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", "ð"]],
@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 :-
Program :-
#include<stdio.h>
#include<string.h
>int main()
{
char msg[] = "THECRAZYPROGRAMMER";
char key[] = "HELLO";
int msgLen = strlen(msg), keyLen = strlen(key), i, j;
newKey[i] = key[j];
}
newKey[i] = '\0';
//encryption
for(i = 0; i < msgLen; ++i)
encryptedMsg[i] = ((msg[i] + newKey[i])
//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 :-
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;
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.
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.
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:
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
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]
left = pt[0:32]
right = pt[32:64]
for i in range(0, 16):
right_expanded = permute(right, exp_d, 48)
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)
if(i != 15):
left, right = right, left
print("Round ", i + 1, " ",
bin2hex(left),
" ", bin2hex(right), " ",
pt = "123456ABCD132536"
key =
"AABB09182736CCDD"
key = hex2bin(key)
shift_table = [1, 1, 2, 2,
2, 2, 2, 2,
1, 2, 2, 2,
2, 2, 2, 1]
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 :-
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.
import math
p=3
q=7
n = p*q
e=2
phi = (p-1)*(q-1)
(k*phi))/emsg =
12.0
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.
P = 23
G=9
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))
Output :-
===========================