0% found this document useful (0 votes)
6 views

INS Lab Manual

The document outlines practical implementations of three encryption methods: Caesar cipher, Monoalphabetic cipher, and Playfair cipher. Each section includes a theoretical explanation of the cipher, followed by C++ code for both encryption and decryption processes. The document emphasizes the simplicity and vulnerabilities of these ciphers, particularly to frequency analysis and brute force attacks.

Uploaded by

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

INS Lab Manual

The document outlines practical implementations of three encryption methods: Caesar cipher, Monoalphabetic cipher, and Playfair cipher. Each section includes a theoretical explanation of the cipher, followed by C++ code for both encryption and decryption processes. The document emphasizes the simplicity and vulnerabilities of these ciphers, particularly to frequency analysis and brute force attacks.

Uploaded by

mangamanga1101
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

Faculty of Engineering & Technology

Information and Network Security (203105311)


B. Tech CSE 4th Year 7th Semester

PRACTICAL: 01

AIM: Implement Caesar cipher encryption-decryption.

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.

A) Caesar Cipher Encryption

Code: -
//encryption
#include <iostream>
#include <string>

using namespace std;

string encrypt(string text, int s) {


string result = "";

for (int i = 0; i < text.length(); i++) {


if (isupper(text[i])) {
char ch = (char)(((int)text[i] + s - 65) % 26 + 65);
result += ch;
} else if (islower(text[i])) {
Enrollment No.: 210303105168
CHAUDHARY UMANGKUMAR BALUBHAI
Page| 1
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

char ch = (char)(((int)text[i] + s - 97) % 26 + 97);


result += ch;
} else {
result += text[i];
}
}
return result;
}

int main() {
string plainText;
int key;

cout << "Enter Plain Text : ";


getline(cin, plainText);
cout << endl;

cout << "Enter Key : ";


cin >> key;
cout << endl;

cout << "Cipher Text : " << encrypt(plainText, key) << endl;

return 0;
}
Output:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
Page| 2
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

B) Caesar Cipher Decryption

Code: -
//decryption
#include <iostream>
#include <string>

using namespace std;

string decrypt(string text, int s) {


string result = "";

for (int i = 0; i < text.length(); i++) {


if (isupper(text[i])) {
char ch = (char)(((int)text[i] - s - 65 + 26) % 26 + 65);
result += ch;
} else if (islower(text[i])) {
char ch = (char)(((int)text[i] - s - 97 + 26) % 26 + 97);
result += ch;
} else {
result += text[i];
}
}
return result;
}

int main() {
string cipherText;
int key;

cout << "Enter Cipher Text : ";


getline(cin, cipherText);
cout << endl;

cout << "Enter Key : ";


cin >> key;
cout << endl;

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
Page| 3
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

cout << "Decrypted Text : " << decrypt(cipherText, key) <<


endl;

return 0;
}
Output:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
Page| 4
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

PRACTICAL: 02

AIM: Implement Monoalphabetic cipher encryption-decryption.

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>

using namespace std;

const char givenChar[26] = {


'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'
};

const char encryChar[26] = {


'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O',
'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K',
'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M'
};

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
Page| 5
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

string encryptionString(const string& s) {


string result;

for (char ch : s) {
if (islower(ch)) {
result += encryChar[ch - 'a'];
} else {
result += ch;
}
}

return result;
}

string decryptionString(const string& s) {


string 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);

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
Page| 6
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

cout << "Plain Text: " << plainText << endl;

string encryptedString = encryptionString(plainText);


cout << "Encrypted String: " << encryptedString << endl;

string decryptedString = decryptionString(encryptedString);


cout << "Decrypted String: " << decryptedString << endl;

return 0;
}
Output:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
Page| 7
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

PRACTICAL: 03

AIM: Implement Playfair cipher encryption-decryption.

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>

using namespace std;

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

cout << "Enter the key for playfair cipher: ";


string key = parseString();
while (key.empty())
key = parseString();
table = cipherTable(key);
cout << "Enter the plaintext to be encipher: ";
string input = parseString();
while (input.empty())
input = parseString();
string output = cipher(input);
string decodedOutput = decode(output);
keyTable(table);
printResults(output, decodedOutput);
}

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;
}

vector<vector<string>> cipherTable(const string& key) {


vector<vector<string>> playfairTable(5, vector<string>(5,
""));
string keyString = key +
"ABCDEFGHIKLMNOPQRSTUVWXYZ";
for (size_t k = 0; k < keyString.length(); k++) {
bool repeat = false, used = false;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (playfairTable[i][j] == string(1, keyString[k])) {
repeat = true;

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
Page| 9
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

} else if (playfairTable[i][j].empty() && !repeat


&& !used) {
playfairTable[i][j] = string(1, keyString[k]);
used = true;
}
}
}
}
return playfairTable;
}

string cipher(string in) {


length = in.length() / 2 + in.length() % 2;
for (int i = 0; i < length - 1; i++) {
if (in[2 * i] == in[2 * i + 1]) {
in.insert(2 * i + 1, "X");
length = in.length() / 2 + in.length() % 2;
}
}
vector<string> digraph(length);
for (int j = 0; j < length; j++) {
if (j == length - 1 && in.length() / 2 == length - 1)
in += "X";
digraph[j] = in.substr(2 * j, 2);
}
string out;
vector<string> encDigraphs = encodeDigraph(digraph);
for (const auto& s : encDigraphs)
out += s;
return out;
}

vector<string> encodeDigraph(const vector<string>& di) {


vector<string> encipher(length);
for (int i = 0; i < length; i++) {
char a = di[i][0];
char b = di[i][1];

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 10
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

auto pt_a = getPoint(a);


auto pt_b = getPoint(b);
int r1 = pt_a.first, c1 = pt_a.second;
int r2 = pt_b.first, c2 = pt_b.second;

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;
}

string decode(const string& out) {


string decoded;
for (size_t i = 0; i < out.length() / 2; i++) {
char a = out[2 * i];
char b = out[2 * i + 1];
auto pt_a = getPoint(a);
auto pt_b = getPoint(b);
int r1 = pt_a.first, c1 = pt_a.second;
int r2 = pt_b.first, c2 = pt_b.second;

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);

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 11
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

}
decoded += table[r1][c1] + table[r2][c2];
}
return decoded;
}

pair<int, int> getPoint(char c) {


for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (table[i][j][0] == c)
return {i, j};
}
}
return {0, 0}; // Default case (should never reach here if
input is valid)
}

void keyTable(const vector<vector<string>>& printTable) {


cout << "Playfair Cipher Key Matrix: " << endl << endl;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
cout << printTable[i][j] << " ";
}
cout << endl;
}
cout << endl;
}

void printResults(const string& encipher, const string& dec) {


cout << "Encrypted Message: " << encipher << endl <<
endl;
cout << "Decrypted Message: " << dec << endl;
}
};

int main() {
PlayfairCipher pf;

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 12
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

return 0;
}

Output:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 13
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

PRACTICAL: 04

AIM: Implement Polyalphabetic cipher encryption-decryption.

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.

For example, using the Vigenère cipher (a type of


polyalphabetic cipher) with the key "KEY":
- Plaintext: ATTACKATDAWN
- Key: KEYKEYKEYKEY
- Ciphertext: KXVOZXCVSWNS

 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.

For the example above:


- Ciphertext: KXVOZXCVSWNS
- Key: KEYKEYKEYKEY
- Plaintext: ATTACKATDAWN
Enrollment No.: 210303105168
CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 14
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

The polyalphabetic cipher improves security by reducing the


frequency of letters in the ciphertext, making it more resistant to
frequency analysis compared to monoalphabetic ciphers.
However, it can still be broken with techniques like Kasiski
examination or the use of frequency analysis on repeated
segments if the key is short.

A) Encryption

Code: -
//encryption
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

string generateKey(const string& plaintext, const string& key) {


string generatedKey = key;
while (generatedKey.size() < plaintext.size()) {
generatedKey += key;
}
return generatedKey.substr(0, plaintext.size());
}

string encrypt(const string& plaintext, const string& key) {


string cipherText;
for (size_t i = 0; i < plaintext.size(); ++i) {
char x = (plaintext[i] + key[i]) % 26 + 'A';
cipherText.push_back(x);
}
return cipherText;
}

int main() {
string plaintext, key;

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 15
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

cout << "Enter the plaintext: ";


getline(cin, plaintext);
cout << "Enter the key: ";
getline(cin, key);

transform(plaintext.begin(), plaintext.end(),
plaintext.begin(), ::toupper);
transform(key.begin(), key.end(), key.begin(), ::toupper);

string generatedKey = generateKey(plaintext, key);


string cipherText = encrypt(plaintext, generatedKey);

cout << "Ciphertext: " << cipherText << endl;

return 0;
}

Output:

B) Decryption

Code: -
//decryption
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 16
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

string generateKey(const string& ciphertext, const string& key)


{
string generatedKey = key;
while (generatedKey.size() < ciphertext.size()) {
generatedKey += key;
}
return generatedKey.substr(0, ciphertext.size());
}

string decrypt(const string& ciphertext, const string& key) {


string plaintext;
for (size_t i = 0; i < ciphertext.size(); ++i) {
char x = (ciphertext[i] - key[i] + 26) % 26 + 'A';
plaintext.push_back(x);
}
return plaintext;
}

int main() {
string ciphertext, key;

cout << "Enter the ciphertext: ";


getline(cin, ciphertext);
cout << "Enter the key: ";
getline(cin, key);

transform(ciphertext.begin(), ciphertext.end(),
ciphertext.begin(), ::toupper);
transform(key.begin(), key.end(), key.begin(), ::toupper);

string generatedKey = generateKey(ciphertext, key);


string plaintext = decrypt(ciphertext, generatedKey);

cout << "Plaintext: " << plaintext << endl;

return 0;

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 17
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

}
Output:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 18
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

PRACTICAL: 05

AIM: Implement Hill cipher encryption-decryption.

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;

void getKeyMatrix(string key, int keyMatrix[3][3]) {


int k = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
keyMatrix[i][j] = (key[k++] - 'A') % 26;
}

void encrypt(int messageVector[3][1], int keyMatrix[3][3], int


cipherMatrix[3][1]) {
Enrollment No.: 210303105168
CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 19
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

for (int i = 0; i < 3; i++) {


cipherMatrix[i][0] = 0;
for (int j = 0; j < 3; j++) {
cipherMatrix[i][0] += keyMatrix[i][j] *
messageVector[j][0];
}
cipherMatrix[i][0] = (cipherMatrix[i][0] % 26 + 26) % 26;
}
}

void HillCipherEncrypt(string plaintext, string key) {


int keyMatrix[3][3];
getKeyMatrix(key, keyMatrix);

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';

cout << "Ciphertext: " << ciphertext << endl;


}

int main() {
string plaintext, key;

cout << "Enter the plaintext (must be 3 characters): ";


cin >> plaintext;
while (plaintext.length() != 3) {
cout << "Plaintext must be exactly 3 characters. Please re-
enter: ";
cin >> plaintext;

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 20
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

cout << "Enter the key (must be 9 characters): ";


cin >> key;
while (key.length() != 9) {
cout << "Key must be exactly 9 characters. Please re-enter:
";
cin >> key;
}
HillCipherEncrypt(plaintext, key);
return 0;
}

Output:

D) Decryption

Code: -
//decryption
#include <iostream>
#include <vector>
using namespace std;

void getKeyMatrix(string key, int keyMatrix[3][3]) {


int k = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
keyMatrix[i][j] = (key[k++] - 'A') % 26;
}

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 21
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

int modInverse(int a) {
for (int x = 1; x < 26; x++)
if ((a * x) % 26 == 1)
return x;
return -1;
}

int determinant(int matrix[3][3]) {


return (matrix[0][0] * (matrix[1][1] * matrix[2][2] - matrix[1]
[2] * matrix[2][1])
- matrix[0][1] * (matrix[1][0] * matrix[2][2] - matrix[1]
[2] * matrix[2][0])
+ matrix[0][2] * (matrix[1][0] * matrix[2][1] - matrix[1]
[1] * matrix[2][0])) % 26;
}

void adjoint(int matrix[3][3], int adj[3][3]) {


adj[0][0] = (matrix[1][1] * matrix[2][2] - matrix[1][2] *
matrix[2][1]) % 26;
adj[0][1] = (matrix[0][2] * matrix[2][1] - matrix[0][1] *
matrix[2][2]) % 26;
adj[0][2] = (matrix[0][1] * matrix[1][2] - matrix[0][2] *
matrix[1][1]) % 26;
adj[1][0] = (matrix[1][2] * matrix[2][0] - matrix[1][0] *
matrix[2][2]) % 26;
adj[1][1] = (matrix[0][0] * matrix[2][2] - matrix[0][2] *
matrix[2][0]) % 26;
adj[1][2] = (matrix[1][0] * matrix[0][2] - matrix[0][0] *
matrix[1][2]) % 26;
adj[2][0] = (matrix[1][0] * matrix[2][1] - matrix[2][0] *
matrix[1][1]) % 26;
adj[2][1] = (matrix[2][0] * matrix[0][1] - matrix[0][0] *
matrix[2][1]) % 26;
adj[2][2] = (matrix[0][0] * matrix[1][1] - matrix[1][0] *
matrix[0][1]) % 26;

for (int i = 0; i < 3; i++)

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 22
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

for (int j = 0; j < 3; j++)


if (adj[i][j] < 0)
adj[i][j] += 26;
}

void inverseKeyMatrix(int keyMatrix[3][3], int invMatrix[3][3])


{
int det = determinant(keyMatrix);
int invDet = modInverse(det);

int adj[3][3];
adjoint(keyMatrix, adj);

for (int i = 0; i < 3; i++)


for (int j = 0; j < 3; j++)
invMatrix[i][j] = (adj[i][j] * invDet) % 26;
}

void decrypt(int cipherMatrix[3][1], int invKeyMatrix[3][3], int


messageVector[3][1]) {
for (int i = 0; i < 3; i++) {
messageVector[i][0] = 0;
for (int j = 0; j < 3; j++) {
messageVector[i][0] += invKeyMatrix[i][j] *
cipherMatrix[j][0];
}
messageVector[i][0] = (messageVector[i][0] % 26 + 26) %
26;
}
}

void HillCipherDecrypt(string ciphertext, string key) {


int keyMatrix[3][3];
getKeyMatrix(key, keyMatrix);

int invKeyMatrix[3][3];
inverseKeyMatrix(keyMatrix, invKeyMatrix);

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 23
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

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';

cout << "Plaintext: " << plaintext << endl;


}

int main() {
string ciphertext, key;
cout << "Enter the ciphertext: ";
cin >> ciphertext;
cout << "Enter the key: ";
cin >> key;
HillCipherDecrypt(ciphertext, key);
return 0;
}

Output:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 24
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

PRACTICAL: 06

AIM: Implement Simple Transposition encryption-decryption.

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.

Steps for Encryption:


1. Write in a Zigzag Pattern:
 The plaintext is written in a zigzag pattern across a
specified number of rows (rails).
 Each character is placed in the rails sequentially,
moving diagonally downwards and upwards.
2. Read by Rows:
 After writing the plaintext in the zigzag pattern, the
ciphertext is formed by reading the characters row by
row, from top to bottom.

Steps for Decryption:


1. Reconstruct the Zigzag Pattern:
 The ciphertext is divided into segments corresponding
to each rail.
 The characters are placed back into the zigzag pattern
based on the number of rails.
2. Read in Zigzag Order:
 The plaintext is reconstructed by reading the characters
Enrollment No.: 210303105168
CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 25
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

in the original zigzag order.

Code: -
def rail_fence_cipher(text, num_rails):

rails = [''] * num_rails


dir = 1 # direction (1 = down, -1 = up)
rail = 0 # current rail

for char in text:


rails[rail] += char
if rail == 0:
dir = 1
elif rail == num_rails - 1:
dir = -1
rail += dir
return ''.join(rails)

def rail_fence_decipher(text, num_rails):


rail_lengths = [0] * num_rails
dir = 1 # direction (1 = down, -1 = up)
rail = 0 # current rail

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)

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 26
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

rail = 0 # current rail


while len(result) < len(text):
if rail_lengths[rail] > 0:
result += rails[rail][0]
rails[rail] = rails[rail][1:]
rail_lengths[rail] -= 1
if rail == 0:
dir = 1
elif rail == num_rails - 1:
dir = -1
rail += dir

# Example usage:
text = input("Enter the text to be encrypted: ")
num_rails = int(input("Enter the number of rails: "))

encrypted_text = rail_fence_cipher(text, num_rails)


print("Encrypted text:", encrypted_text)

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

column to create the ciphertext.

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.

Steps for Encryption:


1. Write Plaintext into Grid:
 The plaintext is written into a grid with a specified number
of columns.
 If the plaintext length does not perfectly fill the grid, the
remaining cells are left empty or can be filled with
padding characters (often omitted in simpler
implementations).
2. Read Grid Column by Column:
 The ciphertext is formed by reading the characters from
the grid column by column, starting from the first column
to the last.

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 28
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

Steps for Decryption:


1. Determine Grid Dimensions:
 Calculate the number of rows needed based on the
length of the ciphertext and the number of columns.
 Calculate the number of shaded boxes (empty cells) in
the grid.
2. Write Ciphertext into Grid:
 The ciphertext is written into the grid column by
column.
3. Read Grid Row by Row:
 The plaintext is reconstructed by reading the characters
from the grid row by row.

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):

cipherText = [""] * key


for col in range(key):
pointer = col
while pointer < len(message):
cipherText[col] += message[pointer]
pointer += key
return "".join(cipherText)
def decryptMessage(key, message):
numCols = math.ceil(len(message) / key)

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 29
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

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:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 30
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

PRACTICAL: 07

AIM: Write a program to Implement LALR Parsing in C.

Code: -
#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void push(char *,int *,char);


char stacktop(char *);
void isproduct(char,char);
int ister(char);
int isnter(char);
int isstate(char);
void error();
void isreduce(char,char);
char pop(char *,int *);
void printt(char *,int *,char [],int);
void rep(char [],int);
struct action
{
char row[6][5];
};

const struct action A[12]=


{
{"sf","emp","emp","se","emp","emp"},
{"emp","sg","emp","emp","emp","acc"},
{"emp","rc","sh","emp","rc","rc"},
{"emp","re","re","emp","re","re"},
{"sf","emp","emp","se","emp","emp"},
{"emp","rg","rg","emp","rg","rg"},
{"sf","emp","emp","se","emp","emp"},
{"sf","emp","emp","se","emp","emp"},
{"emp","sg","emp","emp","sl","emp"},
{"emp","rb","sh","emp","rb","rb"},
Enrollment No.: 210303105168
CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 31
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

{"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"},

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 32
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

{'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 push(char *s,int *sp,char item)


{
if(*sp==100)
printf(" stack is full ");
else
{
*sp=*sp+1;
s[*sp]=item;
}
}

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 34
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

char stacktop(char *s)


{
char i;
i=s[top];
return i;
}
void isproduct(char x,char p)
{
int k,l;
k=ister(x);
l=isstate(p);
strcpy(temp,A[l-1].row[k-1]);
}
int ister(char x)
{
int i;
for(i=0;i<6;i++)
if(x==ter[i])
return i+1;
return 0;
}
int isnter(char x)
{
int i;
for(i=0;i<3;i++)
if(x==nter[i])
return i+1;
return 0;
}
int isstate(char p)
{
int i;
for(i=0;i<12;i++)
if(p==states[i])
return i+1;
return 0;
}

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 35
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

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;

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 36
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

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:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 37
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 38
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

PRACTICAL: 08

AIM: To Study about Lexical Analyzer Generator (LEX) and


Flex (Fast Lexical Analyzer).

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.

The grammar in the above diagram is a text file you create


with a text edtior. Yacc will read your grammar and
generate C code for a syntax analyzer or parser. The
syntax analyzer uses grammar rules that allow it to analyze
tokens from the lexical analyzer and create a syntax tree.
The syntax tree imposes a hierarchical structure the tokens.
For example, operator precedence and associativity are
apparent in the syntax tree. The next step, code generation,
does a depth-first Lexical Analyzer Syntax Analyzer a = b
+ c * d id1 = id2 + id3 * id4 = + * id1 source code tokens
syntax tree id2 id3 id4 load id3 mul id4 add id2 store id1
Code Generator generated code Lex Yacc patterns
grammar 5 walk of the syntax tree to generate code. Some
compilers produce machine code, while others, as shown
above, output assembly language.

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

 Flex is a powerful, open-source application framework


which allows to build traditional applications for browser,
mobile and desktop using the same programming model,
tool, and codebase.
 Flex provides FLEX SDK consisting of the Flex class
library (ActionScript classes), the Flex compilers, the
debugger, the MXML and ActionScript programming
languages, and other utilities to build expressive and
interactive rich internet applications (RIA)
 Flex takes care of the user interface (UI) or the client-side
functionality of a web application. Server-side
functionality dependent on server-side components written
in a traditional scripting language

How to use FLEX?


FLEX (Fast Lexical analyzer generator) is a tool for
generating scanners. Instead of writing a scanner from
scratch, you only need to identify the vocabulary of a
certain language (e.g. Simple), write a specification of
patterns using regular expressions (e.g. DIGIT [0-9]), and
FLEX will construct a scanner for you. FLEX is generally
used in the manner depicted here:

First, FLEX reads a specification of a scanner either from


an input file *.lex, or from standard input, and it generates
as output a C source file lex.yy.c. Then, lex.yy.c is
compiled and linked with the "-lfl" library to produce an
executable a.out. Finally, a.out analyzes its input stream
and transforms it into a sequence of tokens.

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 40
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

*.lex is in the form of pairs of regular expressions and C


code. (sample1.lex, sample2.lex) lex.yy.c defines a routine
yylex () that uses the specification to recognize tokens.
a.out is actually the scanner!

How to Compile & Run LEX / YACC Programs on Windows?


If you are installing Ubuntu (or any Linux based OS) on
your system either through Virtual Box or by making your
system multi-bootable, just to execute your Lex & Yacc
programs; then you might be wasting your HDD space &
your valuable time. You can easily skip this annoying
process and run your programs in Windows OS without
any hassles.

Here's how you can do it:

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.

Compilation & Execution of your Program:


1. Open Command prompt and switch to your working
directory where you have stored your lex file (".l") and
yacc file (".y")
2. Let your lex and yacc files be "hello.l" and "hello.y". Now,
follow the preceding steps to compile and run your
program.
1. For Compiling Lex file only:
 flex hello.l
 gcc lex.yy.c
2. For Compiling Lex & Yacc file both:
 flex hello.l
Enrollment No.: 210303105168
CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 41
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

 bison -dy hello.y


 gcc lex.yy.c y.tab.c
3. For Executing the Program
 a.exe

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;
}

int yyerror(char *errormsg)


{
fprintf(stderr, "%s\n", errormsg);
exit(1);
}

HELLO.Y FILE
%{

#include <stdio.h>

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 42
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

#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:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 43
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

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()
{

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 44
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

return(1);
}
Practical9.txt FILE :
Hii
I'm Umang From Cse

Output:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 45
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

PRACTICAL: 10

AIM: Write a Lex program to count number of vowels and


consonants in a given input string.

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:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 46
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

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:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 47
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

PRACTICAL: 12

AIM: Write a Lex program to printout all HTML tags in file.

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>

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 48
Div: 25(CSE)
Faculty of Engineering & Technology
Information and Network Security (203105311)
B. Tech CSE 4th Year 7th Semester

Output:

Enrollment No.: 210303105168


CHAUDHARY UMANGKUMAR BALUBHAI
P a g e | 49
Div: 25(CSE)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy