B.
Tech Computer Engineering
5th Semester
Computer Network Lab (CEN-
593)
Submitted To: Submitted By:
Prof M.Amjad Harshit K Gupta
Mr. Hannan Mansoor 22BCS040
Dr. Musheer Ahmad 5th Semester
Department of Computer Engineering
Faculty of Engineering and Technology,
Jamia Millia Islamia
Index
S.no Question Remarks Date
1 WAP to implement Caeser 09-08-
Cipher. (Substitution Cipher) 2024
2 WAP to implement Rail 21-08-
Fence Cipher. (Transposition 2024
Cipher)
3 WAP to implement Playfair 28-08-
Cipher . 2024
4 WAP to implement Vigenere 25-09-
Cipher. 2024
5 WAP to implement basic 16-10-
Sockets. 2024
6 Write a socket program for 06-11-
client-server, the client will 2024
send stream of 0’s and 1’s &
the server will count number
of 0’s and 1’s sent by client.
7 WAP to implement Hill 13-11-
Cipher. 2024
8 Write a socket program to 6-11-2024
implement TCP client-server
such that it can count
number of files in a folder.
9 Write a socket program such 6-11-2024
that client should be able to
send the text and server
checks that the received
number of characters are in
text.
10 Write a socket program to 6-11-2024
implement multi-client
system where server can
stop particular words.
11 WAP to implement RSA 6-11-2024
algorithm.
12 WAP to implement Vernam 6-11-2024
Cipher.
Solutions
Q1) WAP to implement Caeser Cipher. (Substitution Cipher)
#include <iostream>
#include <string>
using namespace std;
string encrypt(string text, int shift) {
string result = "";
for (char c : text) {
if (isalpha(c)) {
char base = islower(c) ? 'a' : 'A';
result += char(int(base + (c - base + shift) % 26));
} else {
result += c;
}
}
return result;
}
string decrypt(string text, int shift) {
return encrypt(text, 26 - (shift % 26));
}
int main() {
string text;
int shift;
cout << "Enter text to encrypt: ";
getline(cin, text);
cout << "Enter shift value: ";
cin >> shift;
string encryptedText = encrypt(text, shift);
cout << "Encrypted text: " << encryptedText << endl;
string decryptedText = decrypt(encryptedText, shift);
cout << "Decrypted text: " << decryptedText << endl;
return 0;
}
OUTPUT
Q2) WAP to implement Rail Fence Cipher. (Transposition Cipher)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
string encryptRailFence(string text, int key) {
if (key <= 1) return text;
vector<string> rail(key);
int direction = 1;
int row = 0;
for (char c : text) {
rail[row] += c;
row += direction;
if (row == 0 || row == key - 1) {
direction *= -1;
}
}
string cipherText = "";
for (const string &r : rail) {
cipherText += r;
}
return cipherText;
}
string decryptRailFence(string cipherText, int key) {
if (key <= 1) return cipherText;
vector<string> rail(key);
vector<int> charCount(key, 0);
int direction = 1, row = 0;
for (char c : cipherText) {
charCount[row]++;
row += direction;
if (row == 0 || row == key - 1) {
direction *= -1;
}
}
int idx = 0;
for (int i = 0; i < key; i++) {
rail[i] = cipherText.substr(idx, charCount[i]);
idx += charCount[i];
}
string plainText = "";
row = 0, direction = 1;
vector<int> railIndex(key, 0);
for (int i = 0; i < cipherText.size(); i++) {
plainText += rail[row][railIndex[row]];
railIndex[row]++;
row += direction;
if (row == 0 || row == key - 1) {
direction *= -1;
}
}
return plainText;
}
int main() {
string text;
int key;
cout << "Enter text to encrypt: ";
getline(cin, text);
cout << "Enter key (number of rails): ";
cin >> key;
string encryptedText = encryptRailFence(text, key);
cout << "Encrypted text: " << encryptedText << endl;
string decryptedText = decryptRailFence(encryptedText, key);
cout << "Decrypted text: " << decryptedText << endl;
return 0;
}
OUTPUT
Q3) WAP to implement Playfair Cipher .
#include <bits/stdc++.h>
using namespace std;
#define SIZE 30
void toLowerCase(string& str) {
for (int i = 0; i < str.length(); i++) {
if (str[i] > 64 && str[i] < 91)
str[i] += 32;
}
}
void removeSpaces(string& str) {
str.erase(remove(str.begin(), str.end(), ' '), str.end());
}
void generateKeyTable(string key, char keyT[5][5]) {
int i, j, k;
int dicty[26] = { 0 };
for (i = 0; i < key.length(); i++) {
if (key[i] != 'j')
dicty[key[i] - 97] = 2;
}
dicty['j' - 97] = 1;
i = 0;
j = 0;
for (k = 0; k < key.length(); k++) {
if (dicty[key[k] - 97] == 2) {
dicty[key[k] - 97] -= 1;
keyT[i][j] = key[k];
j++;
if (j == 5) {
i++;
j = 0;
}
}
}
for (k = 0; k < 26; k++) {
if (dicty[k] == 0) {
keyT[i][j] = (char)(k + 97);
j++;
if (j == 5) {
i++;
j = 0;
}
}
}
cout << "The Key Table is :" << endl;
cout << "------------------------" << endl;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
cout << keyT[i][j] << " ";
}
cout << endl;
}
}
void search(char keyT[5][5], char a, char b, int arr[]) {
if (a == 'j')
a = 'i';
else if (b == 'j')
b = 'i';
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (keyT[i][j] == a) {
arr[0] = i;
arr[1] = j;
} else if (keyT[i][j] == b) {
arr[2] = i;
arr[3] = j;
}
}
}
}
int mod5(int a) { return (a % 5); }
void prepare(string& str) {
if (str.length() % 2 != 0) {
str += 'z';
}
}
void encrypt(string& str, char keyT[5][5]) {
int a[4];
for (int i = 0; i < str.length(); i += 2) {
search(keyT, str[i], str[i + 1], a);
if (a[0] == a[2]) {
str[i] = keyT[a[0]][mod5(a[1] + 1)];
str[i + 1] = keyT[a[0]][mod5(a[3] + 1)];
} else if (a[1] == a[3]) {
str[i] = keyT[mod5(a[0] + 1)][a[1]];
str[i + 1] = keyT[mod5(a[2] + 1)][a[1]];
} else {
str[i] = keyT[a[0]][a[3]];
str[i + 1] = keyT[a[2]][a[1]];
}
}
}
void decrypt(string& str, char keyT[5][5]) {
int a[4];
for (int i = 0; i < str.length(); i += 2) {
search(keyT, str[i], str[i + 1], a);
if (a[0] == a[2]) {
str[i] = keyT[a[0]][mod5(a[1] + 4)];
str[i + 1] = keyT[a[0]][mod5(a[3] + 4)];
} else if (a[1] == a[3]) {
str[i] = keyT[mod5(a[0] + 4)][a[1]];
str[i + 1] = keyT[mod5(a[2] + 4)][a[1]];
} else {
str[i] = keyT[a[0]][a[3]];
str[i + 1] = keyT[a[2]][a[1]];
}
}
}
void encryptByPlayfairCipher(string& str, string& key) {
char keyT[5][5];
toLowerCase(key);
toLowerCase(str);
removeSpaces(key);
removeSpaces(str);
prepare(str);
generateKeyTable(key, keyT);
encrypt(str, keyT);
}
void decryptByPlayfairCipher(string& str, string& key) {
char keyT[5][5];
toLowerCase(key);
removeSpaces(key);
generateKeyTable(key, keyT);
decrypt(str, keyT);
}
int main() {
string str, key;
cout << "Enter key: ";
getline(cin, key);
cout << "Enter message: ";
getline(cin, str);
encryptByPlayfairCipher(str, key);
cout << "Cipher text: " << str << endl;
decryptByPlayfairCipher(str, key);
cout << "Decrypted text: " << str << endl;
return 0;
}
OUTPUT
Q4) WAP to implement Vigenere Cipher.
#include <bits/stdc++.h>
using namespace std;
string generateKey(string str, string key)
{
int strLength = str.size();
int keyLength = key.size();
string fullKey = "";
int j = 0;
for (int i = 0; i < strLength; i++) {
if (isalpha(str[i])) {
fullKey.push_back(tolower(key[j % keyLength]));
j++;
} else {
fullKey.push_back(' ');
}
}
return fullKey;
}
string encrypted(string str, string key)
{
string cipher_text;
for (int i = 0; i < str.size(); i++) {
if (isalpha(str[i])) {
char base = islower(str[i]) ? 'a' : 'A';
char x = (tolower(str[i]) - 'a' + (key[i] - 'a')) % 26 + base;
cipher_text.push_back(x);
} else {
cipher_text.push_back(str[i]);
}
}
return cipher_text;
}
string decrypted(string cipher_text, string key)
{
string orig_text;
for (int i = 0; i < cipher_text.size(); i++) {
if (isalpha(cipher_text[i])) {
char base = islower(cipher_text[i]) ? 'a' : 'A';
char x = (tolower(cipher_text[i]) - 'a' - (key[i] - 'a') + 26) % 26 + base;
orig_text.push_back(x);
} else {
orig_text.push_back(cipher_text[i]);
}
}
return orig_text;
}
int main() {
string str, key;
cout << "Enter key: ";
getline(cin, key);
cout << "Enter message: ";
getline(cin, str);
string keyy = generateKey(str, key);
string cipher_text = encrypted(str, keyy);
cout << "Cipher text: " << cipher_text << endl;
string original_text = decrypted(cipher_text, keyy);
cout << "Original text: " << original_text << endl;
return 0;
}
OUTPUT
Q5) WAP to implement basics of Socket.
Client Side:
const WebSocket = require('ws');
const readline = require('readline');
// Connect to the WebSocket server
const ws = new WebSocket('ws://192.168.59.107');
// Open a readline interface to capture user input
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
prompt: 'Message to server> ',
});
ws.on('open', () => {
console.log('Connected to the WebSocket server');
// Prompt user to send a message to the server
rl.prompt();
// Listen for user input
rl.on('line', (line) => {
if (line.trim().toLowerCase() === 'exit') {
console.log('Closing connection...');
ws.close(); // Close WebSocket if "exit" is typed
rl.close();
return;
}
// Send the user input to the server
ws.send(line.trim());
rl.prompt();
});
});
// Listen for messages from the server
ws.on('message', (message) => {
console.log(`Server says: ${message}`);
});
// Handle WebSocket closure
ws.on('close', () => {
console.log('Disconnected from the server');
rl.close();
});
// Handle WebSocket errors
ws.on('error', (error) => {
console.error(`WebSocket error: ${error.message}`);
rl.close();
});
Server Side:
const WebSocket = require('ws');
// Create a WebSocket server on IP 192.168.0.9 and port 3000
const wss = new WebSocket.Server({ port: 2000, host: '192.168.59.107' });
wss.on('connection', (ws) => {
console.log('New client connected');
ws.send('Welcome to the WebSocket server!');
// Listen for messages from the client
ws.on('message', (message) => {
console.log(`Received from client: ${message}`);
// Respond to the client
ws.send(`Server received your message: ${message}`);
});
// Handle client disconnection
ws.on('close', () => {
console.log('Client disconnected');
});
});
console.log('WebSocket server is running on ws://192.168.0.9:3000');
OUTPUT
SERVER SIDE:
Client Side:
Q6) Write a socket program for client-server, the client will send stream of 0’s and
1’s & the server will count number of 0’s and 1’s sent by client.
Client Side
const net = require('net');
const readline = require('readline');
const host = '192.168.15.107';
const port = 65432;
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
const client = new net.Socket();
client.connect(port, host, () => {
console.log("Connected to server");
rl.question("Enter a stream of 0's and 1's: ", (data) => {
client.write(data);
client.end();
rl.close();
});
});
client.on('close', () => {
console.log("Connection closed");
});
Server Side
const net = require('net');
const host = '192.168.15.107';
const port = 65432;
let zerosCount = 0;
let onesCount = 0;
let receivedData = '';
const server = net.createServer((socket) => {
console.log("Client connected");
socket.on('data', (data) => {
receivedData += data.toString();
for (const char of data.toString()) {
if (char === '0') {
zerosCount++;
} else if (char === '1') {
onesCount++;
}
}
});
socket.on('end', () => {
console.log("Client disconnected");
console.log(`The Data send by the client is: ${receivedData}`);
console.log(`Number of 0's received: ${zerosCount}`);
console.log(`Number of 1's received: ${onesCount}`);
zerosCount = 0;
onesCount = 0;
receivedData = '';
});
});
server.listen(port, host, () => {
console.log(`Server listening on ${host}:${port}`);
});
OUTPUT
Server Side:
Client Side:
Q7) WAP to implement Hill Cipher.
#include<iostream>
#include<vector>
using namespace std;
string encrypt(string msg,string key ){
int len=msg.length();
vector<vector<int>> matrix(len,vector<int>(len,0));
vector<int> msgvector(len);
vector<int> ansvector(len);
string ans;
int k=0;
for(int i=0;i<len; i++){
for(int j=0 ;j<len;j++){
matrix[i][j]=key[k++]-'A';
}
}
for(int i=0;i<len;i++){
msgvector[i]=msg[i]-'A';
}
for(int i=0;i<len;i++){
int res=0;
for(int j=0;j<len;j++){
res+=matrix[i][j]*msgvector[j];
}
res = (res % 26 + 26) % 26;
ansvector[i]=res;
}
for(int i=0;i<len;i++){
ans[i]=char(ansvector[i]+'A');
cout<<ans[i];
}
return ans;
}
int modInverse(int a, int m) {
a = (a % m + m) % m;
for (int x = 1; x < m; x++) {
if ((a * x) % m == 1) return x;
}
return -1; // No modular inverse exists
}
void getCof(vector<vector<int>>& mat, vector<vector<int>>& cof, int p, int q, int n) {
int i = 0, j = 0;
for (int row = 0; row < n; row++) {
for (int col = 0; col < n; col++) {
if (row != p && col != q) {
cof[i][j++] = mat[row][col];
if (j == n - 1) {
j = 0;
i++;
}
}
}
}
}
int getDet(vector<vector<int>>& mat, int n) {
if (n == 1) return mat[0][0];
int det = 0;
vector<vector<int>> cof(mat.size(), vector<int>(mat.size()));
int sign = 1;
for (int f = 0; f < n; f++) {
getCof(mat, cof, 0, f, n);
det += sign * mat[0][f] * getDet(cof, n - 1);
sign = -sign;
}
return det;
}
void adjoint(vector<vector<int>>& mat, vector<vector<int>>& adj) {
int n = mat.size();
if (n == 1) {
adj[0][0] = 1;
return;
}
int sign = 1;
vector<vector<int>> cof(n, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
getCof(mat, cof, i, j, n);
sign = ((i + j) % 2 == 0) ? 1 : -1;
adj[j][i] = sign * getDet(cof, n - 1); // Transpose and cofactor
}
}
}
bool inverse(vector<vector<int>>& mat, vector<vector<int>>& inv, int mod) {
int n = mat.size();
int det = getDet(mat, n);
det = (det % mod + mod) % mod; // Ensure positive determinant
int detInv = modInverse(det, mod);
if (detInv == -1) {
cout << "Singular matrix, can't find its inverse\n";
return false;
}
vector<vector<int>> adj(n, vector<int>(n));
adjoint(mat, adj);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
inv[i][j] = (adj[i][j] * detInv % mod + mod) % mod; // Modular inverse
}
}
return true;
}
string decrypt(string msg, string key) {
int len = msg.length();
vector<vector<int>> matrix(len, vector<int>(len));
vector<vector<int>> inversematrix(len, vector<int>(len));
vector<int> msgvector(len);
vector<int> ansvector(len);
string ans(len, ' ');
int k = 0;
for (int i = 0; i < len; i++) {
for (int j = 0; j < len; j++) {
matrix[i][j] = key[k++] - 'A';
}
}
for (int i = 0; i < len; i++) {
msgvector[i] = msg[i] - 'A';
}
if (!inverse(matrix, inversematrix, 26)) {
cout << "Error: Key matrix is not invertible.\n";
return "";
}
for (int i = 0; i < len; i++) {
int res = 0;
for (int j = 0; j < len; j++) {
res += inversematrix[i][j] * msgvector[j];
}
res = (res % 26 + 26) % 26;
ansvector[i] = res;
}
for (int i = 0; i < len; i++) {
ans[i] = char(ansvector[i] + 'A');
}
return ans;
}
int main (){
while (true)
{
int choice,len;
string msg,key;
cout << "\nChoose any one of the following" << endl
<< "Press 1 to encrypt" << endl
<< "Press 2 to decrypt"<<endl;
cin >> choice;
if (choice == 1)
{
cout<<"Enter the msg to be encrypted\n";
cin>>msg;
len=msg.length();
cout<<"Enter the key(size should be of "<<len*len<<")\n";
cin>>key;
string ans=encrypt(msg,key);
cout<<ans;
}
else if (choice == 2)
{
cout<<"Enter the msg to be decrypted\n";
cin>>msg;
len=msg.length();
cout<<"Enter the key(size should be of "<<len*len<<")\n";
cin>>key;
string ans=decrypt(msg,key);
cout<<ans;
}
else
{
break;
}
}
}
OUTPUT
Q8) Write a socket program to implement TCP client-server such that it can count
number of files in a folder.
Server Side:
const net = require('net');
const fs = require('fs');
const path = require('path');
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => {
const folderPath = data.toString().trim();
if (fs.existsSync(folderPath) && fs.lstatSync(folderPath).isDirectory()) {
fs.readdir(folderPath, (err, files) => {
if (err) {
socket.write('Error reading directory');
} else {
const fileCount = files.length;
socket.write(`Number of files in folder: ${fileCount}`);
}
});
} else {
socket.write('Invalid folder path');
}
});
socket.on('end', () => {
console.log('Client disconnected');
});
});
server.listen(8080, () => {
console.log('Server listening on port 8080');
});
Client Side:
const net = require('net');
const client = net.createConnection({ port: 8080 }, () => {
console.log('Connected to server');
const folderPath = 'C:\\Users\\91914\\OneDrive\\Desktop\\audio';
client.write(folderPath);
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('error', (err) => {
console.error('Error:', err.message);
});
OUTPUT
Server Side:
Client Side:
Q9) Write a socket program such that client should be able to send the text and
server checks that the received number of characters are in text.
Server Side:
const net = require('net');
const expectedLength = 10;
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => {
const receivedText = data.toString().trim();
if (receivedText.length === expectedLength) {
socket.write(`Success: The number of characters is correct.And the message is ${receivedText}`);
} else {
socket.write(`Error: The received text should have ${expectedLength} characters. Received: $
{receivedText.length}`);
}
});
socket.on('end', () => {
console.log('Client disconnected');
});
});
const host = '192.168.15.107';
const port = 8080;
server.listen(port, host, () => {
console.log(`Server listening on ${host}:${port}`);
});
Client Side:
const net = require('net');
const serverIp = '192.168.15.107';
const serverPort = 8080;
const client = net.createConnection({ host: serverIp, port: serverPort }, () => {
console.log('Connected to server');
const text = 'HellooWorld';
client.write(text);
});
client.on('data', (data) => {
console.log(data.toString());
client.end(); se
});
client.on('error', (err) => {
console.error('Error:', err.message);
});
OUTPUT
Server Side:
Client Side:
Q10) Write a socket program to implement multi-client system where server can
stop particular words.
Server Side:
const net = require('net');
const forbiddenWords = ['badword', 'blocked'];
const server = net.createServer((socket) => {
console.log('Client connected');
socket.on('data', (data) => {
let clientMessage = data.toString().trim();
forbiddenWords.forEach(word => {
const regex = new RegExp(word, 'gi');
clientMessage = clientMessage.replace(regex, '***');
});
socket.write(`Modified message: ${clientMessage}`);
});
socket.on('end', () => {
console.log('Client disconnected');
});
});
server.listen(8080, () => {
console.log('Server listening on port 8080');
});
Client Side:
const net = require('net');
const serverIp = '192.168.15.107';
const serverPort = 8080;
const client = net.createConnection({ host: serverIp, port: serverPort }, () => {
console.log('Connected to server');
const message = 'This is a message with Badword in it.';
client.write(message);
});
client.on('data', (data) => {
console.log('Server response: ' + data.toString());
client.end();
});
client.on('error', (err) => {
console.error('Error:', err.message);
});
OUTPUT:
Server Side:
Client Side:
Q11) WAP to implement RSA algorithm.
#include <iostream>
#include <cmath>
#include <vector>
#include <cstdlib>
#include <ctime>
#include <algorithm>
using namespace std;
// Function to calculate gcd
int gcd(int a, int b) {
return (b == 0) ? a : gcd(b, a % b);
}
// Function to find modular inverse
int modInverse(int e, int phi) {
for (int d = 1; d < phi; d++) {
if ((e * d) % phi == 1) {
return d;
}
}
return -1;
}
// Fast modular exponentiation
long long modExpo(long long base, long long exp, long long mod) {
long long result = 1;
base = base % mod;
while (exp > 0) {
if (exp % 2 == 1) {
result = (result * base) % mod;
}
exp = exp >> 1;
base = (base * base) % mod;
}
return result;
}
int main() {
// Step 1: Key generation
int p = 61; // First prime number
int q = 53; // Second prime number
int n = p * q; // Modulus
int phi = (p - 1) * (q - 1); // Totient
// Choose public key e
int e = 17; // e must be coprime to phi and 1 < e < phi
while (gcd(e, phi) != 1) {
e++;
}
// Compute private key d
int d = modInverse(e, phi);
// Display keys
cout << "Public Key: (" << e << ", " << n << ")\n";
cout << "Private Key: (" << d << ", " << n << ")\n";
// Step 2: Encryption
int message;
cout << "Enter a message (integer): ";
cin >> message;
// Encrypt message
long long encrypted = modExpo(message, e, n);
cout << "Encrypted Message: " << encrypted << "\n";
// Step 3: Decryption
long long decrypted = modExpo(encrypted, d, n);
cout << "Decrypted Message: " << decrypted << "\n";
return 0;
}
OUTPUT:
Q12) WAP to implement Vernam Cipher.
#include <iostream>
#include <string>
using namespace std;
// Function to encrypt/decrypt using Vernam Cipher
string vernamCipher(string text, string key) {
string result = "";
for (i = 0; i < text.length(); i++) {
// XOR operation between each character of the text and the key
result += text[i] ^ key[i];
}
return result;
}
int main() {
string plaintext, key;
// Input plaintext
cout << "Enter plaintext: ";
getline(cin, plaintext);
// Input key
cout << "Enter key (same length as plaintext): ";
getline(cin, key);
// Check if the key and plaintext are the same length
if (plaintext.length() != key.length()) {
cout << "Error: Key length must be the same as plaintext length!" << endl;
return 1;
}
// Encrypt the plaintext
string ciphertext = vernamCipher(plaintext, key);
cout << "Encrypted Ciphertext (in ASCII): ";
for (char c : ciphertext) {
cout << int(c) << " "; // Display ASCII values of the ciphertext
}
cout << endl;
// Decrypt the ciphertext
string decryptedText = vernamCipher(ciphertext, key);
cout << "Decrypted Text: " << decryptedText << endl;
return 0;
}
OUTPUT: