Cryptography

Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Course Name : Cryptography and Network Security Lab

Course Code : CSE 4204


Lab List

01 Perform encryption and decryption using mono-alphabetic cipher. The program should
support the following:
• Construct an input file named plaintext.txt (consisting of 1000 alphabets,
without any space or special characters)
• Encrypt the characters of plaintext.txt and store the corresponding ciphertext
characters in ciphertext.txt
• Compute the frequency of occurrence of each alphabet in both plaintext.txt and
ciphertext.txt and tabulate the results
02 Generate and print 48-bit keys for all sixteen rounds of DES algorithm, given a 64-bit
initial key.
03 Given 64-bit output of (i-1)th round of DES, 48-bit ith round key Ki and E table, find the
48-bit input for S-box
04 Write a program to perform encryption and decryption using transposition technique
with column permutation given as key
05 Write a program to perform the following using Hill cipher:
1. Encrypt a message M with a given key matrix of size 2×2 and 3×3
2. Decrypt the cipher text obtained in (1) by computing inverse of the respective
key matrix.
06 Write a program to perform the following using Playfair cipher technique
1. Encrypt a given message M with different keys{k1,k2,...,kn}.
2. Print key and ciphertext pair Decrypt the ciphertexts obtained in (1) to get back
M
07 Implement RSA algorithm using client-server concept. The program should support the
following:
• Client generates {PU, PR} and distributes PU to server.
• Server encrypts message M using client’s public key {PU}.
• Client decrypts the message sent by server using its private key
{PR}.
08 Implement the following with respect to RC4:
• Print first n key bytes generated by key generation process.
• Illustrate encryption/ decryption by accepting one byte data as input on the
above generated keys
01. Perform encryption and decryption using mono-alphabetic cipher.
• Construct an input file named plaintext.txt (consisting of 1000 alphabets, without any space or
special characters)
• Encrypt the characters of plaintext.txt and store the corresponding ciphertext characters in
ciphertext.txt
• the frequency of occurrence of each alphabet in both plaintext.txt and ciphertext.txt and
tabulate the results

Source Code:

#include<bits/stdc++.h>
using namespace std;
char uniqtext[26]; // Global variable
/* Read plain text from plaintext.txt file */
string readPlainText() {
ifstream fin;
string ptext;
fin.open("plaintext.txt");
getline(fin, ptext); // Use getline to read the entire line
fin.close();
return ptext;
}
/* Write cipher text to ciphertext.txt file */
void writeCipherText(string ctext) {
ofstream fout;
fout.open("ciphertext.txt");
fout << ctext;
fout.close();
}
/* Function to find all possible permutations */
void permute(char a[], int l, int r, vector<string>& keyspace) {
if (l == r) {
keyspace.push_back(a);
} else {
for (int i = l; i <= r; i++) {
swap(a[l], a[i]); // Inbuilt swap function
permute(a, l + 1, r, keyspace);
swap(a[l], a[i]);
}
}
}
vector<string> genKeySpace(string plaintext) {
set<char> uniqSet;
vector<string> keyspace; // Contains all possible permutations of letters in plaintext
int count = 0;
/* Store all the unique letters of plain text in uniqSet */
for (int i = 0; i < plaintext.length(); i++) {
uniqSet.insert(plaintext[i]);
}
/* Copy uniqSet to uniqtext char array */
for (set<char>::iterator it = uniqSet.begin(); it != uniqSet.end(); it++) {
uniqtext[count++] = (*it);
}
permute(uniqtext, 0, count - 1, keyspace);
return keyspace;
}
/* Create cipher text using key */
string encrypt(string unique, string key, string plaintext) {
string ciphertext = "";
for (int i = 0; i < plaintext.length(); i++) {
int idx = unique.find(plaintext[i]);
ciphertext += key[idx];
}
return ciphertext;
}
/* Frequency = (number of occurrences of a character / length of plaintext) */
/* Show frequency of all characters of plain text and cipher text */
void showFrequency(string pt, string ct) {
map<char, int> mPlain;
map<char, int> mCipher;
for (int i = 0; i < pt.length(); i++) {
mPlain[pt[i]]++;
mCipher[ct[i]]++;
}
cout << "\nFrequency\t\tPlaintext Character\t\tCiphertext character" << endl;
cout << "=========\t\t===================\t\t====================" << endl;
for (int i = 0; i < pt.length(); i++) {
cout << (float)mPlain[pt[i]] / pt.length() << "\t\t\t\t" << pt[i] << "\t\t\t\t" << ct[i] << endl;
}
}
int main() {
srand(time(NULL));
string plaintext = readPlainText();
cout << "Plain text = \t" << plaintext << endl;
vector<string> keyspace = genKeySpace(plaintext);
string key = keyspace[rand() % keyspace.size()];
cout << "Unique chars = \t" << uniqtext << endl;
cout << "Chosen key = \t" << key << endl;
string ciphertext = encrypt(uniqtext, key, plaintext);
writeCipherText(ciphertext); // write ciphertext to file
showFrequency(plaintext, ciphertext);
return 0;
}
Input & Output:
02.Generate and print 48-bit keys for all sixteen rounds of DES algorithm, given a 64-bit initial key.

Source code

#include <iostream>
#include <fstream>
#include <bitset>
#include <string>
using namespace std;
int permChoiceOne[] = {
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4
};
int permChoiceTwo[] = {
14, 17, 11, 24, 1, 5, 3, 28,
15, 6, 21, 10, 23, 19, 12, 4,
26, 8, 16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55, 30, 40,
51, 45, 33, 48, 44, 49, 39, 56,
34, 53, 46, 42, 50, 36, 29, 32
};

int leftShiftTable[] = {1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1};

string rotateSubKey(string s, int rot) {


rot %= s.length(); // Ensure rotation is within the string length
return s.substr(rot) + s.substr(0, rot);
}
string firstPermute(string input) {
string res = "";
for (int i = 0; i < 56; i++) {
res += input[permChoiceOne[i] - 1];
}
return res;
}
string secondPermute(string input) {
string res = "";
for (int i = 0; i < 48; i++) {
res += input[permChoiceTwo[i] - 1];
}
return res;
}
void genKeys(string left, string right) {
ofstream fout;
fout.open("keygen.txt"); //saving output to keygen.txt file
for (int i = 0; i < 16; i++) {
left = rotateSubKey(left, leftShiftTable[i]);
right = rotateSubKey(right, leftShiftTable[i]);
string key = secondPermute(left + right);
cout << "key " << i + 1 << " \t: " << key << endl; // display
fout << key << endl; // save to file
}
fout.close();
}
int main() {
unsigned long long hexkey;
cout << "\nEnter 64-bit key in hexadecimal(16-digits) : ";
cin >> hex >> hexkey; // to read hex input cin >> hex >> input
string key = bitset<64>(hexkey).to_string(); // to convert hex to binary
cout << "Binary key (k) \t: " << key << endl;
key = firstPermute(key);
cout << "PC-1 key (k+) \t: " << key << endl;
cout << "\nSubKeys: " << endl;
genKeys(key.substr(0, 28), key.substr(28, 28));
cout << endl << endl;
return 0;
}
Input & Output
03. Given 64-bit output of (i-1)th round of DES, 48-bit ith round key Ki and E table, find the 48-bit input
for S-box

Source code
#include <bits/stdc++.h>
using namespace std;
int expPermute[] = {
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 };
string expansionPermute(string input)
{
string res = "";
for(int i=0; i<48; i++)
{
res += input[expPermute[i]-1];
}
return res;
}
string XOR(string input1, string input2)
{
string res = "";
for(int i=0; i<input1.length(); i++)
{
res += (input1[i] == input2[i]) ? "0" : "1";
}
return res;
}
int main()
{
int i; // round i
unsigned long long hexInput;
string Ki; // ith round key
ifstream fin;
cout << "\nEnter Round number (i) : ";
cin >> i;
cout << "Enter 64-bit (i-1)th round output in hex: " ;
cin >> hex >> hexInput;
string input = bitset<64>(hexInput).to_string();
fin.open("keygen.txt");
for(int j=1; j<=i; j++)
{
fin >> Ki;
}
// ---- To insert key manually uncomment below lines ---
// unsigned long long hexKey;
// cout << "Enter 48 bit key for ith round: " ;
// cin >> hex >> hexKey;
// Ki = bitset<48>(hexKey).to_string();
if(Ki.length() == 0)
{
cout << "\nkeygen.txt not found !!! \n" << endl;
exit(1);
}
cout << "\n64-bit Binary Input = " << input << endl ;
cout << "key for ith round (Ki) = " << Ki << endl ;
string Ri_1 = input.substr(32,32); // 32 bit Right half of input R[i-1]
cout << "\nRight half of 64-bit input, Ri_1 = " << Ri_1 << endl;
string R48 = expansionPermute(Ri_1);
cout << "Ri_1 after expansion permutation = " << R48 << endl;
string sBoxInput = XOR(R48, Ki);
cout << "\nInput to s-box : " << sBoxInput << endl << endl;
}
Input & Output

04. Write a program to perform encryption and decryption using transposition technique with column
permutation given as key

Source code
#include<bits/stdc++.h>
using namespace std ;
string encrypt(string pt , string key)
{
string ct = ""; // ciphertext
int k = 0; // plaintext iterator
int num_row = ceil((float) pt.length()/key.length());
int num_col = key.length();
char mat[num_row][num_col];
cout << "\nEncryption Matrix :" << endl;
cout << "---------------------" << endl;
for(int i=0; i<num_row ; i++)
{
for(int j=0; j<num_col; j++)
{
if(k < pt.length())
{
cout << (mat[i][j] = pt[k++]) << " ";
}
else
{
cout << (mat[i][j] = 'x') << " " ;
}
}
cout << endl;
}
for(int i=0; i<num_col; i++)
{
for(int j=0; j<num_row; j++)
{
ct += mat[j][key.find(i+'1')];
}
}
return ct;
}
string decrypt(string ct , string key)
{
string pt = ""; // plaintext
int k = 0; // ciptext iterator
int num_row = ceil((float)ct.length() / key.length());
int num_col = key.length();
char mat[num_row][num_col];
for(int i=0; i<num_col; i++)
{
for(int j=0; j<num_row; j++)
{
mat[j][key.find(i+'1')] = ct[k++];
}
}
cout << "\nDecryption Matrix :" << endl;
cout << "---------------------" << endl;
for(int i=0; i<num_row ; i++)
{
for(int j=0; j<num_col; j++)
{
cout << mat[i][j] << " ";
pt += mat[i][j];
}
cout << endl;
}
return pt;
}
int main()
{
string plaintext , key , ciphertext , decryptext;
cout << "Enter text : ";
cin >> plaintext;
cout << "Enter key : ";
cin >> key;
ciphertext = encrypt(plaintext , key);
cout << "\nEncrypted text \t: " << ciphertext << endl;
decryptext = decrypt(ciphertext , key);
cout << "\nDecrypted text \t: " << decryptext << endl;
}
Input & Output

05. Write a program to perform the following using Hill cipher:


1. Encrypt a message M with a given key matrix of size 2×2 and 3×3
2. Decrypt the cipher text obtained in (1) by computing inverse of the respective key matrix.

Source code
#include<bits/stdc++.h>
using namespace std ;
int key[3][3] ; // Global
int mod26(int x)
{
return x >= 0 ? (x%26) : 26-(abs(x)%26) ;
}
/* findDet(matrix , order_of_matrix) */ int
findDet(int m[3][3] , int n)
{
int det;
if(n == 2)
{
det = m[0][0] * m[1][1] - m[0][1]*m[1][0] ;
}
else if (n == 3)
{
det = m[0][0]*(m[1][1]*m[2][2] - m[1][2]*m[2][1]) -
m[0][1]*(m[1][0]*m[2][2] - m[2][0]*m[1][2] ) + m[0][2]*(m[1][0]*m[2][1] -
m[1][1]*m[2][0]);
}
else det = 0 ; // invalid input
return mod26(det);
}
int findDetInverse(int R , int D = 26) // R is the remainder or determinant
{
int i = 0 ;
int p[100] = {0,1};
int q[100] = {0} ; // quotient
while(R!=0)
{
q[i] = D/R ;
int oldD = D ;
D=R;
R = oldD%R ;
if(i>1)
{
p[i] = mod26(p[i-2] - p[i-1]*q[i-2]) ;
}
i++ ;
}
if (i == 1) return 1;
else return p[i] = mod26(p[i-2] - p[i-1]*q[i-2]) ; }
void multiplyMatrices(int a[1000][3] , int a_rows , int a_cols , int
b[1000][3] , int b_rows , int b_cols , int res[1000][3])
{
for(int i=0 ; i < a_rows ; i++)
{
for(int j=0 ; j < b_cols ; j++)
{
for(int k=0 ; k < b_rows ; k++)
{
res[i][j] += a[i][k]*b[k][j] ;
}
res[i][j] = mod26(res[i][j]) ;
}
}
}
/* Inverse = (matrix * detInverse) mod 26 */
/* findInverse(matrix , order_of_matrix , result_matrix) */ void
findInverse(int m[3][3] , int n , int m_inverse[3][3] )
{
int adj[3][3] = {0};
int det = findDet(m , n); // findDet(matrix , order_of_matrix)
int detInverse = findDetInverse(det);
if(n==2)
{
adj[0][0] = m[1][1];
adj[1][1] = m[0][0];
adj[0][1] = -m[0][1];
adj[1][0] = -m[1][0];
}
else if(n==3)
{
int temp[5][5] = {0} ;
// fill the 5x5 matrix
for(int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
temp[i][j] = m[i%3][j%3] ;
}
}
/* except first row and first column, multiply elements along rows
and place them along columns */
for(int i=1; i<=3 ; i++)
{
for(int j=1; j<=3 ; j++)
{
adj[j-1][i-1] = temp[i][j]*temp[i+1][j+1] -
temp[i][j+1]*temp[i+1][j];
}
}
}
for(int i=0; i<n ; i++)
{
for(int j=0; j<n ; j++)
{
m_inverse[i][j] = mod26(adj[i][j] * detInverse) ;
}
}
}
// C =PK
string encrypt(string pt, int n)
{ int P[1000][3] = {0} ; // plaintext
int C[1000][3] = {0} ; // cipher text
int ptIter = 0 ;
while(pt.length()%n != 0)
{
pt += "x" ; // pad extra x
}
int row = (pt.length())/n; // number of rows in P
for(int i=0; i<row ; i++)
{
for(int j=0; j<n; j++)
{
P[i][j] = pt[ptIter++]-'a' ;
}
}
// multiplyMatrices(mat_a , row_a , col_a , mat_b, row_b, col_b , mat_result)
multiplyMatrices(P, row , n , key , n , n , C) ;
string ct = "" ;
for(int i=0 ; i<row ; i++)
{
for(int j=0 ; j<n ;j++)
{
ct += (C[i][j] + 'a');
}
}
return ct ;
}
// P = C*(k_inverse)
string decrypt(string ct, int n)
{
int P[1000][3] = {0} ; // plaintext int
int C[1000][3] = {0} ; // cipher text
int ctIter = 0 ; int row = ct.length()/n; //number of rows in C
for(int i=0; i<row ; i++)
{
for(int j=0; j<n; j++)
{
C[i][j] = ct[ctIter++]-'a' ;
}
}
int k_inverse[3][3] = {0};
/* findInverse(matrix , order_of_matrix , result_matrix) */
findInverse(key, n , k_inverse);
/* multiplyMatrices(mat_a , row_a , col_a , mat_b, row_b, col_b , mat_result)
*/
multiplyMatrices(C, row , n , k_inverse , n , n , P) ;
string pt = "" ;
for(int i = 0 ; i<row ; i++)
{
for(int j=0 ; j<n ; j++)
{
pt += (P[i][j] + 'a');
}
}
return pt ;
}
int main(void)
{
string pt ;
int n ;
cout << "Enter the text to be encrypted : " ;
cin >> pt;
cout << "Enter order of key matrix : ";
cin >> n ;
cout<<"Enter key matrix: " <<endl;
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
cin >> key[i][j];
}
}
cout << "\nOriginal text : " << pt << endl;
string ct = encrypt(pt, n) ;
cout << "Encrypted text : " << ct << endl;
string dt = decrypt(ct, n);
cout << "Decrypted text : " << dt << endl;
}
Input & Output

06. Write a program to perform the following using Playfair cipher technique
1. Encrypt a given message M with different keys{k1,k2,...,kn}.
2. Print key and ciphertext pair Decrypt the ciphertexts obtained in (1) to get back M
Source code
#include <bits/stdc++.h>
using namespace std;
typedef struct{
int row;
int col;
}position;
char mat[5][5]; // Global Variable
void generateMatrix(string key)
{
/* flag keeps track of letters that are filled in matrix */
/* flag = 0 -> letter not already present in matrix */
/* flag = 1 -> letter already present in matrix */ int
flag[26] = {0}; int x = 0, y = 0;
/* Add all characters present in the key */
for(int i=0; i<key.length(); i++)
{
if(key[i] == 'j') key[i] = 'i'; // replace j with i
if(flag[key[i]-'a'] == 0)
{
mat[x][y++] = key[i];
flag[key[i]-'a'] = 1;
}
if(y==5) x++, y=0;
}
/* Add remaining characters */
for(char ch = 'a'; ch <= 'z'; ch++)
{
if(ch == 'j') continue; // don't fill j since j was replaced by i
if(flag[ch - 'a'] == 0)
{
mat[x][y++] = ch;
flag[ch - 'a'] = 1 ;
}
if(y==5) x++, y=0;
}
}
/* function to add filler letter('x') */ string
formatMessage(string msg)
{
for(int i=0; i<msg.length(); i++)
{
if(msg[i] == 'j') msg[i] = 'i';
}
for(int i=1; i<msg.length(); i+=2) //pairing two characters
{
if(msg[i-1] == msg[i]) msg.insert(i, "x");
}
if(msg.length()%2 != 0) msg += "x";
return msg;
}
/* Returns the position of the character */
position getPosition(char c)
{
for(int i=0; i<5; i++)
for(int j=0; j<5; j++)
if(c == mat[i][j])
{
position p = {i, j};
return p;
}
}
string encrypt(string message)
{
string ctext = "";
for(int i=0; i<message.length(); i+=2) // i is incremented by 2 inorder to check for pair values
{
position p1 = getPosition(message[i]);
position p2 = getPosition(message[i+1]);
int x1 = p1.row; int y1 = p1.col;
int x2 = p2.row; int y2 = p2.col;

if( x1 == x2 ) // same row


{
ctext += mat[x1][(y1+1)%5];
ctext += mat[x2][(y2+1)%5];
}
else if( y1 == y2 ) // same column
{
ctext += mat[ (x1+1)%5 ][ y1 ];
ctext += mat[ (x2+1)%5 ][ y2 ];
}
else {
ctext += mat[ x1 ][ y2 ];
ctext += mat[ x2 ][ y1 ];
}}
return ctext; }

string Decrypt(string message)


{
string ptext = "";
for(int i=0; i<message.length(); i+=2) // i is incremented by 2 inorder to check for pair values
{
position p1 = getPosition(message[i]);
position p2 = getPosition(message[i+1]);
int x1 = p1.row; int y1 = p1.col;
int x2 = p2.row; int y2 = p2.col;
if( x1 == x2 ) // same row
{
ptext += mat[x1][ --y1<0 ? 4: y1 ];
ptext += mat[x2][ --y2<0 ? 4: y2 ];
}
else if( y1 == y2 ) // same column
{
ptext += mat[ --x1<0 ? 4: x1 ][y1];
ptext += mat[ --x2<0 ? 4: x2 ][y2];
}
else {
ptext += mat[ x1 ][ y2 ];
ptext += mat[ x2 ][ y1 ];
}
}
return ptext;
}
int main() {
string plaintext;
cout << "Enter message : "; cin >> plaintext;
int n; // number of keys
cout << "Enter number of keys : "; cin >> n;
string key[n];
for(int i=0; i<n; i++)
{
cout<< "\nEnter key " << i+1 << " : " << key[i];
cin >> key[i];
generateMatrix(key[i]);
cout << "Key " << i+1 << " Matrix:" << endl;
for(int k=0;k<5;k++)
{
for(int j=0;j<5;j++)
{
cout << mat[k][j] << " ";
}
cout << endl;
}
cout << "Actual Message \t\t: " << plaintext << endl;
string fmsg = formatMessage(plaintext);
cout << "Formatted Message \t: " << fmsg << endl;
string ciphertext = encrypt(fmsg);
cout << "Encrypted Message \t: " << ciphertext << endl;
string decryptmsg = Decrypt(ciphertext);
cout<< "Decrypted Message \t: " << decryptmsg << endl;
}
}
Input & Output

07.Implement RSA algorithm using client-server concept. The program should support the
following:
• Client generates {PU, PR} and distributes PU to server.
• Server encrypts message M using client’s public key {PU}.
• Client decrypts the message sent by server using its private key {PR}.
Source code
/*Client Program*/
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int connectToServer(const char* ip, int port)
{
int sock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {AF_INET, htons(port), inet_addr(ip)};
if (connect(sock, (struct sockaddr*)&addr, sizeof(addr)) < 0)
{
cout << "\nRun server program first." << endl;
exit(0);
}
else
{
cout << "\nClient is connected to Server." << endl;
}
return sock;
}
int randInRange(int low, int high) // excluding high and low
{
return rand() % (high - (low + 1)) + (low + 1);
}
int gcd(int a, int b)
{
return b == 0 ? a : gcd(b, a % b);
}
// M = C^d mod n
int powermod(int a, int b, int n)
{
int res = 1;
for (int i = 0; i < b; i++)
{
res = (res * static_cast<long long>(a)) % n;
}
return res;
}
// Decrypt function
int decrypt(int C, int PR[2])
{
return powermod(C, PR[0], PR[1]);
}
int main()
{
char ip[50];
int port;
cout << "\nEnter server's IP address: ";
cin >> ip;
cout << "Enter port : ";
cin >> port;
int sock = connectToServer(ip, port);
int p, q;
cout << "\nEnter two prime numbers : ";
cin >> p >> q;
int n = p * q;
int phi = (p - 1) * (q - 1);
srand(time(NULL));
int e, d;
do
{
e = randInRange(1, phi);
} while (gcd(e, phi) != 1);
for (d = 1; d < phi; d++)
{
if ((d * e) % phi == 1)
break;
}
int PU[2] = {e, n}; // public key
int PR[2] = {d, n}; // private key
cout << "\nPublic key , PU = {" << e << ", " << n << "}" << endl;
cout << "Private key, PR = {" << d << ", " << n << "}" << endl;
send(sock, &PU, sizeof(PU), 0); // send public key to server
cout << "\nSent Public key to server." << endl;
int C; // ciphertext
recv(sock, &C, sizeof(C), 0); // receive ciphertext from server
cout << "\nCiphertext received from server : " << C << endl;
int M = decrypt(C, PR); // decrypted text
cout << "\nDecrypted Text : " << M << endl
<< endl;
return 0;
}
/*Server program*/
#include <iostream>
#include <cstdlib>
#include <arpa/inet.h>
#include <unistd.h>
using namespace std;
int createServer(int port)
{
int sersock = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr = {AF_INET, htons(port), INADDR_ANY};
bind(sersock, (struct sockaddr*)&addr, sizeof(addr));
cout << "\nServer Online. Waiting for client...." << endl;
listen(sersock, 5);
int sock = accept(sersock, NULL, NULL);
cout << "Connection Established." << endl;
return sock;
}
int powermod(int a, int b, int n)
{
int res = 1;
for (int i = 0; i < b; i++)
{
res = (res * static_cast<long long>(a)) % n;
}
return res;
}
// Encrypt function
int encrypt(int M, int PU[2]) // PU = {e, n}
{
return powermod(M, PU[0], PU[1]);
}
int main()
{
int port;
cout << "\nEnter port : ";
cin >> port;
int sock = createServer(port);
int PU[2];
recv(sock, &PU, sizeof(PU), 0); // receive public key from client
cout << "\nPublic key received from client : {" << PU[0] << ", " << PU[1] << "}" << endl;
int M; // plaintext message (M < n)
cout << "\nEnter message(M<" << PU[1] << ") to encrypt : ";
cin >> M;
int C = encrypt(M, PU);
cout << "\nEncrypted Text : " << C << endl;
send(sock, &C, sizeof(C), 0); // send ciphertext to client
cout << "\nSent ciphertext to client." << endl
<< endl;
return 0;
}
Input & Output
08.Implement the following with respect to RC4:
• Print first n key bytes generated by key generation process.
• Illustrate encryption/ decryption by accepting one byte data as input on the above
generated keys
Source Code
#include <bits/stdc++.h>
using namespace std;
int main()
{
int S[256], T[256], keyStream[256];
string ptString, keyString, dtString = "";
int pt[256], ct[256], dt[256];
cout << "Enter message : "; cin >> ptString;
cout << "Enter key : "; cin >> keyString;
int n = ptString.length();
cout << "\nPlain text \t: " ;
for(int i=0; i<n; i++)
{
pt[i] = ptString[i]; // converting char to its ASCII value
cout << pt[i] << " ";
}
// Initialization
for(int i=0; i<256; i++)
{
S[i] = i;
T[i] = (int)keyString[i%keyString.length()]; // fill T with ASCII valueof key T[256]=[keykeykeykey...]
}
// Initial permutation
int j=0;
for(int i=0; i<256; i++)
{
j = (j + S[i] + T[i]) % 256;
swap(S[i], S[j]);
}
// Stream Generation
cout << "\nKey Stream \t: ";
j=0;
for(int i=0; i<n; i++) // generate keystream of same length as plaintext
{
j = (j + S[i]) % 256;
swap(S[i], S[j]);
int t = (S[i] + S[j]) % 256;
keyStream[i] = S[t];
cout << keyStream[i] << " ";
}
// Encryption
cout << "\nCipher Text \t: ";
for(int i=0; i<n; i++)
{
ct[i] = pt[i] ^ keyStream[i]; // xor
cout << ct[i] << " ";
}
// Decryption
cout << "\nDecrypted text \t: " ;
for(int i=0; i<n; i++)
{
dt[i] = ct[i] ^ keyStream[i];
cout << dt[i] << " ";
dtString += (char)dt[i]; // change ASCII value to char
}
cout << "\nDecrypted text \t: " << dtString << endl;
}
Input & Output-1

Input & Output-2

You might also like