INS Lab Manual
INS Lab Manual
PRACTICAL: 01
Theory: -
Caesar cipher is a substitution cipher where each letter in the
plaintext is shifted a certain number of places down or up the
alphabet.
It's a simple and historical method of encryption, but it's not
very secure due to its vulnerability to brute force attacks.
The key idea is shifting letters by a fixed amount to encode
and decode messages.
For Caesar cipher encryption, each letter in the plaintext is
shifted a fixed number of places down or up the alphabet.
Let's say we have a shift of 3. So, 'A' becomes 'D', 'B'
becomes 'E', and so on.
To decrypt, you simply shift back by the same number of
places.
It's a straightforward method but not very secure.
The key is crucial for both encryption and decryption.
Code: -
//encryption
#include <iostream>
#include <string>
int main() {
string plainText;
int key;
cout << "Cipher Text : " << encrypt(plainText, key) << endl;
return 0;
}
Output:
Code: -
//decryption
#include <iostream>
#include <string>
int main() {
string cipherText;
int key;
return 0;
}
Output:
PRACTICAL: 02
Theory: -
A monoalphabetic cipher is a substitution cipher where each
letter in the plaintext is replaced by a corresponding letter
from a fixed substitution alphabet.
This method ensures that each letter consistently maps to the
same substitute letter throughout the message.
Although simple to implement, monoalphabetic ciphers are
highly vulnerable to frequency analysis, as the patterns in
letter frequency remain unchanged from the plaintext to the
ciphertext.
Historical examples, like the Caesar cipher, demonstrate the
fundamental concept of monoalphabetic encryption and its
straightforward yet easily breakable nature.
Code: -
#include <iostream>
#include <string>
#include <cctype>
for (char ch : s) {
if (islower(ch)) {
result += encryChar[ch - 'a'];
} else {
result += ch;
}
}
return result;
}
for (char ch : s) {
if (isupper(ch)) {
for (int j = 0; j < 26; j++) {
if (ch == encryChar[j]) {
result += givenChar[j];
break;
}
}
} else {
result += ch;
}
}
return result;
}
int main() {
string plainText;
cout << "Enter Plain Text: ";
getline(cin, plainText);
return 0;
}
Output:
PRACTICAL: 03
Theory: -
Alphabet Pairing: The Playfair cipher encrypts pairs of
letters (digraphs), making it harder for frequency analysis to
crack the code.
5x5 Grid: It uses a 5x5 grid filled with a keyword (without
repeating letters) followed by the remaining letters of the
alphabet. 'I' and 'J' are often combined to fit into the 25 cells.
Rule-Based Encryption: Encryption rules depend on the
relative positions of the letter pairs in the grid: same row,
same column, or rectangle formation.
Handling Duplicates and Odd Letters: If a pair consists of
the same letter, an 'X' is inserted between them. If the
plaintext has an odd number of letters, an 'X' is added at the
end.
Decryption: The decryption process reverses the encryption
rules, restoring the original message by mapping the
encrypted pairs back through the grid.
Code: -
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
class PlayfairCipher {
private:
int length = 0;
vector<vector<string>> table;
public:
PlayfairCipher() {
Enrollment No.: 210303105168
CHAUDHARY UMANGKUMAR BALUBHAI
Page| 8
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester
string parseString() {
string input;
getline(cin, input);
transform(input.begin(), input.end(),
input.begin(), ::toupper);
input.erase(remove_if(input.begin(), input.end(), [](char c)
{ return !isalpha(c); }), input.end());
replace(input.begin(), input.end(), 'J', 'I');
return input;
}
if (r1 == r2) {
c1 = (c1 + 1) % 5;
c2 = (c2 + 1) % 5;
} else if (c1 == c2) {
r1 = (r1 + 1) % 5;
r2 = (r2 + 1) % 5;
} else {
swap(c1, c2);
}
encipher[i] = table[r1][c1] + table[r2][c2];
}
return encipher;
}
if (r1 == r2) {
c1 = (c1 + 4) % 5;
c2 = (c2 + 4) % 5;
} else if (c1 == c2) {
r1 = (r1 + 4) % 5;
r2 = (r2 + 4) % 5;
} else {
swap(c1, c2);
}
decoded += table[r1][c1] + table[r2][c2];
}
return decoded;
}
int main() {
PlayfairCipher pf;
return 0;
}
Output:
PRACTICAL: 04
Theory: -
The polyalphabetic cipher is a cryptographic technique that uses
multiple substitution alphabets to encrypt data. Unlike the
simple Caesar cipher, which shifts letters by a fixed amount,
polyalphabetic ciphers use a key to determine the shift for each
letter in the plaintext.
Encryption:
1) Choose a Key: Select a key word or phrase. Each letter in
the key represents a shift in the alphabet.
2) Repeat the Key: Repeat the key until it matches the length
of the plaintext.
3) Encrypt Each Letter: Shift each letter of the plaintext by
the amount indicated by the corresponding letter in the
key.
Decryption:
1) Repeat the Key: Repeat the key to match the length of the
ciphertext.
2) Decrypt Each Letter: Shift each letter of the ciphertext
back by the amount indicated by the corresponding letter
in the key.
A) Encryption
Code: -
//encryption
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string plaintext, key;
transform(plaintext.begin(), plaintext.end(),
plaintext.begin(), ::toupper);
transform(key.begin(), key.end(), key.begin(), ::toupper);
return 0;
}
Output:
B) Decryption
Code: -
//decryption
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main() {
string ciphertext, key;
transform(ciphertext.begin(), ciphertext.end(),
ciphertext.begin(), ::toupper);
transform(key.begin(), key.end(), key.begin(), ::toupper);
return 0;
}
Output:
PRACTICAL: 05
Theory: -
Hill cipher is a polygraphic substitution cipher that encrypts and
decrypts plaintext using matrix computations. To decrypt hill
ciphertext, compute the matrix inverse modulo 26 (where 26 is
the alphabet length), requiring the matrix to be invertible123.
Decryption involves matrix computations such as matrix
inversion, and arithmetic calculations such as modular inverse1.
Decryption can be done by a simple formula P= (K’) (C) mod26
where P is the plain text, K’ is the inverse key matrix, C is the
ciphertext vector or the column matrices2. To decrypt, use the
formula P = C K -1 mod 26, where C is the ciphertext and K -1
is the inverse of the matrix K3. To encrypt a message, each
block of n letters (considered as an n -component vector) is
multiplied by an invertible n × n matrix, against modulus 26. To
decrypt the message, each block is multiplied by the inverse of
the matrix used for encryption4.
C) Encryption
Code: -
//encryption
#include <iostream>
#include <vector>
using namespace std;
int messageVector[3][1];
for (int i = 0; i < 3; i++)
messageVector[i][0] = plaintext[i] - 'A';
int cipherMatrix[3][1];
encrypt(messageVector, keyMatrix, cipherMatrix);
string ciphertext;
for (int i = 0; i < 3; i++)
ciphertext += cipherMatrix[i][0] + 'A';
int main() {
string plaintext, key;
Output:
D) Decryption
Code: -
//decryption
#include <iostream>
#include <vector>
using namespace std;
int modInverse(int a) {
for (int x = 1; x < 26; x++)
if ((a * x) % 26 == 1)
return x;
return -1;
}
int adj[3][3];
adjoint(keyMatrix, adj);
int invKeyMatrix[3][3];
inverseKeyMatrix(keyMatrix, invKeyMatrix);
int cipherMatrix[3][1];
for (int i = 0; i < 3; i++)
cipherMatrix[i][0] = ciphertext[i] - 'A';
int messageVector[3][1];
decrypt(cipherMatrix, invKeyMatrix, messageVector);
string plaintext;
for (int i = 0; i < 3; i++)
plaintext += messageVector[i][0] + 'A';
int main() {
string ciphertext, key;
cout << "Enter the ciphertext: ";
cin >> ciphertext;
cout << "Enter the key: ";
cin >> key;
HillCipherDecrypt(ciphertext, key);
return 0;
}
Output:
PRACTICAL: 06
Theory: -
Rail – Fence cipher Introduction:
The Rail Fence Cipher is a form of transposition cipher
where the plaintext is written in a zigzag pattern (like a
fence) across multiple "rails" (rows) and then read off row
by row to create the ciphertext. This method is simple but
can be quite effective for basic encryption.
Basic Principle:
The basic principle of the Rail Fence Cipher is to use a
zigzag pattern to rearrange the characters of the plaintext
across multiple "rails" or rows, and then read off the
characters row by row to form the ciphertext. The key for
the cipher is the number of rails used.
Code: -
def rail_fence_cipher(text, num_rails):
for _ in range(len(text)):
rail_lengths[rail] += 1
if rail == 0:
dir = 1
elif rail == num_rails - 1:
dir = -1
rail += dir
rails = []
start = 0
for length in rail_lengths:
rails.append(text[start:start + length])
start += length
result = ''
dir = 1 # direction (1 = down, -1 = up)
# Example usage:
text = input("Enter the text to be encrypted: ")
num_rails = int(input("Enter the number of rails: "))
decrypted_text = rail_fence_decipher(encrypted_text,
num_rails)
print("Decrypted text:", decrypted_text)
Output:
Theory: -
Row – Column cipher Introduction:
The Row-Column Transposition Cipher is another form of
transposition cipher where the plaintext is written into a
grid (matrix) row by row and then read off column by
Enrollment No.: 210303105168
CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 27
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester
Principle:
The Row-Column Transposition Cipher, also known as the
Columnar Transposition Cipher, is a type of transposition
cipher that rearranges the characters of the plaintext into a
grid (matrix) and then reads the grid in a different order to
create the ciphertext. The key for the cipher is the number
of columns used in the grid.
Basic Principle:
1. Encryption:
Write the plaintext into a grid, row by row, with a
specified number of columns.
Read the characters from the grid column by column to
generate the ciphertext.
2. Decryption:
Determine the number of rows based on the length of
the ciphertext and the number of columns.
Write the ciphertext into the grid column by column.
Read the characters from the grid row by row to
reconstruct the plaintext.
Code: -
import math
def main():
message = input("Enter message: ")
key = int(input("Enter key [2-%s]: " % (len(message) - 1)))
mode = input("Encryption/Decryption [e/d]: ")
if mode.lower().startswith("e"):
text = encryptMessage(key, message)
elif mode.lower().startswith("d"):
text = decryptMessage(key, message)
print("Output:\n%s" % (text + "|"))
def encryptMessage(key, message):
numRows = key
numShadedBoxes = (numCols * numRows) - len(message)
plainText = [""] * numCols
col = 0
row = 0
for symbol in message:
plainText[col] += symbol
col += 1
if (
(col == numCols)
or (col == numCols - 1)
and (row >= numRows - numShadedBoxes)
):
col = 0
row += 1
return "".join(plainText)
if __name__ == "__main__":
import doctest
doctest.testmod()
main()
Output:
PRACTICAL: 07
Code: -
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
{"emp","rb","rd","emp","rd","rd"},
{"emp","rf","rf","emp","rf","rf"}
};
struct gotol
{
char r[3][4];
};
const struct gotol G[12]=
{
{"b","c","d"},
{"emp","emp","emp"},
{"emp","emp","emp"},
{"emp","emp","emp"},
{"i","c","d"},
{"emp","emp","emp"},
{"emp","j","d"},
{"emp","emp","k"},
{"emp","emp","emp"},
{"emp","emp","emp"},
};
char ter[6]={'i','+','*',')','(','$'};
char nter[3]={'E','T','F'};
char states[12]={'a','b','c','d','e','f','g','h','m','j','k','l'};
char stack[100];
int top=-1;
char temp[10];
struct grammar
{
char left;
char right[5];
};
const struct grammar rl[6]=
{
{'E',"e+T"},
{'E',"T"},
{'T',"T*F"},
{'T',"F"},
{'F',"(E)"},
{'F',"i"},
};
void main()
{
char inp[80],x,p,dl[80],y,bl='a';
int i=0,j,k,l,n,m,c,len;
printf(" Enter the input :");
scanf("%s",inp);
len=strlen(inp);
inp[len]='$';
inp[len+1]='\0';
push(stack,&top,bl);
printf("\n stack \t\t\t input");
printt(stack,&top,inp,i);
do
{
x=inp[i];
p=stacktop(stack);
isproduct(x,p);
if(strcmp(temp,"emp")==0)
error();
if(strcmp(temp,"acc")==0)
break;
else
{
if(temp[0]=='s')
{
push(stack,&top,inp[i]);
push(stack,&top,temp[1]);
i++;
}
else
{
if(temp[0]=='r')
Enrollment No.: 210303105168
CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 33
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester
{
j=isstate(temp[1]);
strcpy(temp,rl[j-2].right);
dl[0]=rl[j-2].left;
dl[1]='\0';
n=strlen(temp);
for(k=0;k<2*n;k++)
pop(stack,&top);
for(m=0;dl[m]!='\0';m++)
push(stack,&top,dl[m]);
l=top;
y=stack[l-1];
isreduce(y,dl[0]);
for(m=0;temp[m]!='\0';m++)
push(stack,&top,temp[m]);
}
}
}
printt(stack,&top,inp,i);
}
while(inp[i]!='\0');
if(strcmp(temp,"acc")==0)
printf(" \n accept the input ");
else
printf(" \n do not accept the input ");
}
void error()
{
printf(" error in the input ");
exit(0);
}
void isreduce(char x,char p)
{
int k,l;
k=isstate(x);
l=isnter(p);
strcpy(temp,G[k-1].r[l-1]);
}
char pop(char *s,int *sp)
{
char item;
if(*sp==-1)
printf(" stack is empty ");
else
{
item=s[*sp];
*sp=*sp-1;
}
return item;
}
void printt(char *t,int *p,char inp[],int i)
{
int r;
printf("\n");
for(r=0;r<=*p;r++)
rep(t,r);
printf("\t\t\t");
for(r=i;inp[r]!='\0';r++)
printf("%c",inp[r]);
}
void rep(char t[],int r)
{
char c;
c=t[r];
switch(c)
{
case 'a': printf("0");
break;
case 'b': printf("1");
break;
case 'c': printf("2");
break;
case 'd': printf("3");
break;
case 'e': printf("4");
break;
case 'f': printf("5");
break;
case 'g': printf("6");
break;
case 'h': printf("7");
break;
case 'm': printf("8");
break;
case 'j': printf("9");
break;
case 'k': printf("10");
break;
case 'l': printf("11");
break;
default :printf("%c",t[r]);
break;
}
}
Output:
PRACTICAL: 08
Explanation:
Lex - A Lexical Analyzer Generator:-
Lex is a program generator designed for lexical processing
of character input streams. It accepts a high-level, problem
oriented specification for character string matching, and
produces a program in a general purpose language which
recognizes regular expressions. The regular expressions
are specified by the user in the source specifications given
to Lex. The Lex written code recognizes these expressions
in an input stream and partitions the input stream into
strings matching the expressions.
What is Flex?
Enrollment No.: 210303105168
CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 39
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester
Installing Software’s:
1. Download Flex 2.5.4a
2. Download Bison 2.4.1
3. Download DevC++
4. Install Flex at "C:\GnuWin32"
5. Install Bison at "C:\GnuWin32"
6. Install DevC++ at "C:\Dev-Cpp"
7. Open Environment Variables.
8. Add "C:\GnuWin32\bin;C:\Dev-Cpp\bin;" to path.
Code: -
EXAMPLE:- HELLO.L FILE
%{
#include "y.tab.h"
int yyerror(char *errormsg);
%}
%%
("hi"|"oi")"\n" { return HI; }
("tchau"|"bye")"\n" { return BYE; }
. { yyerror("Unknown char"); }
%%
int main(void)
{
yyparse();
return 0;
}
int yywrap(void)
{
return 0;
}
HELLO.Y FILE
%{
#include <stdio.h>
#include <stdlib.h>
int yylex(void);
int yyerror(const char *s);
%}
%token HI BYE
%%
program:
hi bye
;
hi:
HI { printf("Hello World\n"); }
;
bye:
BYE { printf("Bye World\n"); exit(0); }
;
Output:
PRACTICAL: 09
AIM: Create a Lexer to take input from text file and count no of
characters, no. of lines & no. of words.
Code: -
%{
#include<stdio.h>
int lines=0, words=0,s_letters=0,c_letters=0, num=0,
spl_char=0,total=0;
%}
%%
\n { lines++; words++;} [\t ' '] words++;
[A-Z] c_letters++;
[a-z] s_letters++;
[0-9] num++;
. spl_char++;
%%
main(void)
{
yyin= fopen("practical9.txt","r");
yylex();
total=s_letters+c_letters+num+spl_char;
printf(" This File contains ...");
printf("\n\t%d lines", lines);
printf("\n\t%d words",words);
printf("\n\t%d small letters", s_letters);
printf("\n\t%d capital letters",c_letters);
printf("\n\t%d digits", num);
printf("\n\t%d special characters",spl_char);
printf("\n\tIn total %d characters.\n",total);
}
int yywrap()
{
return(1);
}
Practical9.txt FILE :
Hii
I'm Umang From Cse
Output:
PRACTICAL: 10
Code: -
%{
int vow_count=0; int const_count =0;
%}
%%
[aeiouAEIOU] {vow_count++;} [a-zA-Z] {const_count++;}
%%
main()
{
yyin= fopen("practical8.txt","r"); yylex();
printf("The number of vowels are: %d\n",vow_count);
printf("The number of consonants are: %d\n",const_count);
return 0;
}
yywrap()
{
return 1;}
Practical10.txt FILE
Hii
I'm Umang From Cse
Output:
PRACTICAL: 11
AIM: Write a Lex program to print out all numbers from the
given file.
Code: -
%{
#include<stdio.h> int num=0;
%}
%%
[0-9] num++; ECHO;
%%
main(void)
{
yyin= fopen("practical11.txt","r");
yylex();
printf("\n\t%d digits", num);}
int yywrap()
{
return(1);}
Practical11.txt FILE
23332
23
Sbfjehbcc
Output:
PRACTICAL: 12
Code: -
%{
#include<stdio.h>
%}
%%
\<[^>]*\> printf("%s\n",yytext);
.|\n;
%%
int yywrap()
{
return 1;
}
int main()
{
yyin=fopen("practical10b.txt","r");
yylex();
return 0;
}
Practical10b.txt FILE
<html>
<body>
<h1> Hello</h1>
<br>
</body>
</html>
Output: