Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 52

JATIYA KABI KAZI NAZRUL ISLAM UNIVERSITY

TRISHAL, MYMENSINGH

Lab Report
Course Name: Network Security Lab
Course Code: CSE-436

Submitted To

Dr. Tushar Kanti Saha

Associate Professor

Dept. of CSE,JKKNIU
Submitted By
Deena Faria

Roll: 17102005
Reg:5682
Session : 2016-17

Submission Date: 31.01.2021


INDEX
Experimen Name of the Experiment Page
t No. No.
01 Write a C/C++ program to implement Caesar Cipher. 01-05

02 Write a C/C++ program to show brute-force 06-08


cryptanalysis of Caesar Cipher.

03 Write a C/C++ program to implement Playfair cipher. 09-19

04 Write a C/C++ program to implement Hill cipher. 20-26

05 Write a C/C++ program to implement Vigenère cipher. 27-32

06 Write a C/C++ program to implement RSA public-key 33-36


cryptographic algorithm.

07 Write a C/C++ program to implement Diffie-Hellman 37-39


Key exchange algorithm.

08 Write a C/C++ program to implement Elgamal Public- 40-46


key algorithm.

09 Write a C/C++ program to implement a Simple Hash 47-50


Function using simple XOR operation.
Experiment No.01

Name of the Experiment: Write a C/C++ program to implement Caesar


Cipher.

Objectives:

 Know about Caesar Cipher encryption and decryption.


 Learn the working of Caesar Cipher encryption algorithm.

Algorithm:

Step 1: Start
Step 2: Input a string
Step 3: Input an Integer between 0-25 denoting the required shift.
Step 4: Traverse the given text one character at a time.

Step 5: For each character, transform the given character as per the rule,
depending on whether we’re encrypting or decrypting the text.

Step 6: Return the new string generated.

Step 7: Stop

Code:

#include<iostream>

using namespace std;

void input();

string encryption(string text,int key);

string decryption(string text,int key);

int main()

int i,j,len,choice;
string text;

int key;

cout<<"Enter text:";

getline(cin,text);

cout<<"Enter key:";

cin>>key;

do{

cout<<"\n\nCaesar Cipher\n\n1.Press 1 for Encryption\n2.Press 2 for


decryption\n3.Press 3 for Exit\n";

cin>>choice;

switch(choice){

case 1:

text=encryption(text,key);

cout<<text;

break;

case 2:

text=decryption(text,key);

cout<<text;

break;

case 3:

cout<<"Exit";
break;

default:

cout<<"Please enter a valid choice";

break;

while(choice!=3);

return 0;

string encryption(string text,int key)

int i;

string res="";

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

if(isupper(text[i]))

res+=char(int(text[i]+key-65)%26+65);

else if(islower(text[i]))

res+=char(int(text[i]+key-97)%26+97);

else if(text[i]==' ')

res+=' ';
}

return res;

string decryption(string text,int key)

string res="";

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

if(isupper(text[i]))

res+=char(int(text[i]-key-65)%26+65);

else if(islower(text[i]))

res+=char(int(text[i]-key-97)%26+97);

else if(text[i]==' ')

res+=' ';

return res;

Input: Text= caesar cipher

Key=2.
Output:

Discussion: We have successfully implemented the Caesar Cipher algorithm in


c++.
Experiment No.02

Name of the Experiment: Write a C/C++ program to show brute-force


cryptanalysis of Caesar Cipher.

Objective:

 To learn about the brute-force cryptanalysis of Caesar Cipher.

Algorithm:

Step 1: Start.

Step 2: Input a string.

Step 3: For 0 to 25, repeat step 4, 5, and 6.

Step 4: Traverse the given text one character at a time.

Step 5: Shift each character by 1 to the next using modulo 26.

Step 6: Print result.

Step 7: Stop

Code:

#include<iostream>

using namespace std;

void crypto(string text);

int main()

string text;

cout<<"Enter text:";
getline(cin,text);

crypto(text);

return 0;

void crypto(string text)

cout<<"Brute force cryptanalysis of Caesar Cipher:\n\n";

for(int key=0;key<26;key++){

string res="";

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

if(isupper(text[i]))

res+=char(int(text[i]+key-65)%26+65);

else if(islower(text[i]))

res+=char(int(text[i]+key-97)%26+97);

else if(text[i]==' ')

res+=' ';

}
cout<<"Key"<<key<<" = "<<res;

cout<<"\n";

Input: rovvy gybvn

Output:

Discussion: We have successfully showed the brute-force cryptanalysis of


Caesar cipher.
Experiment No.03

Name of the Experiment: Write a C/C++ program to implement Playfair


cipher.

Objective:

 To learn the encryption and decryption process of playfair cipher.

Algorithm:

The Algorithm consists of 2 steps:

Step-1: Generate the key Square (5×5):

 The key square is a 5×5 grid of alphabets that acts as the key for
encrypting the plaintext. Each of the 25 alphabets must be unique and one
letter of the alphabet (usually J) is omitted from the table (as the table can
hold only 25 alphabets). If the plaintext contains J, then it is replaced by
I.
 The initial alphabets in the key square are the unique alphabets of the key
in the order in which they appear followed by the remaining letters of the
alphabet in order.

Step-2: Algorithm to encrypt the plain text: 

The plaintext is split into pairs of two letters (digraphs). If there is an odd
number of letters, a Z is added to the last letter.

Rules for Encryption:

a) If both the letters are in the same column:


 Take the letter below each one (going back to the top if at the bottom).
b) If both the letters are in the same row:
 Take the letter to the right of each one (going back to the leftmost if at the
rightmost position).
c) If neither of the above rules is true:
 Form a rectangle with the two letters and take the letters on the horizontal
opposite corner of the rectangle.
The Playfair Cipher Decryption Algorithm:
The Algorithm consists of 2 steps:

Step-1: Generate the key Square (5×5) at the receiver’s end:

The key square is a 5×5 grid of alphabets that acts as the key for encrypting the
plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet
(usually J) is omitted from the table (as the table can hold only 25 alphabets). If
the plaintext contains J, then it is replaced by I.

The initial alphabets in the key square are the unique alphabets of the key in the
order in which they appear followed by the remaining letters of the alphabet in
order.

Step-2: Algorithm to decrypt the ciphertext:

 The ciphertext is split into pairs of two letters (digraphs).


Rules for Decryption:

a) If both the letters are in the same column:


 Take the letter above each one (going back to the bottom if at the top).
b) If both the letters are in the same row:
 Take the letter to the left of each one (going back to the rightmost if at the
leftmost position).
c) If neither of the above rules is true:
 Form a rectangle with the two letters and take the letters on the horizontal
opposite corner of the rectangle.

Code:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include<ctype.h>

void toLowerCase(char plain[], int ps)


{

int i;

for (i = 0; i < ps; i++) {

if(isupper(plain[i]))

plain[i]=tolower(plain[i]);

int removeSpaces(char* plain, int ps)

int i, count = 0;

for (i = 0; i < ps; i++)

if (plain[i] != ' ')

plain[count++] = plain[i];

plain[count] = '\0';

return count;

void KeyTable(char key[], int ks, char keyT[5][5])

int i, j, k, flag = 0, *dicty;

dicty = (int*)calloc(26, sizeof(int));

for (i = 0; i < ks; i++) {

if (key[i] != 'j')

dicty[key[i] - 97] = 2;
}

dicty['j' - 97] = 1;

i = 0;

j = 0;

for (k = 0; k < ks; 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;

}
}

void search(char keyT[5][5], char a, char b, int arr[])

int i, j;

if (a == 'j')

a = 'i';

else if (b == 'j')

b = 'i';

for (i = 0; i < 5; i++) {

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

int prepare(char str[], int ptrs)

if (ptrs % 2 != 0) {

str[ptrs++] = 'z';

str[ptrs] = '\0';

return ptrs;

void encrypt(char str[], char keyT[5][5], int ps)

int i, a[4];

for (i = 0; i < ps; 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 encryption(char str[], char key[])

char ps, ks, keyT[5][5];

ks = strlen(key);

ks = removeSpaces(key, ks);

toLowerCase(key, ks);

ps = strlen(str);

toLowerCase(str, ps);

ps = removeSpaces(str, ps);

ps = prepare(str, ps);

KeyTable(key, ks, keyT);

encrypt(str, keyT, ps);


}

void decrypt(char str[], char keyT[5][5], int ps)

int i, a[4];

for (i = 0; i < ps; 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 decryption(char str[], char key[])

char ps, ks, keyT[5][5];


ks = strlen(key);

ks = removeSpaces(key, ks);

toLowerCase(key, ks);

ps = strlen(str);

toLowerCase(str, ps);

ps = removeSpaces(str, ps);

KeyTable(key, ks, keyT);

decrypt(str, keyT, ps);

int main()

char str[100], key[100];

int choice;

printf("Enter text:");

gets(str);

printf("Enter key:");

gets(key);

do

printf("\n\nPlayfair Cipher\n\n1.Press 1 for Encryption\n2.Press 2 for


decryption\n3.Press 3 for Exit\n");

scanf("%d",&choice);
switch(choice){

case 1:

encryption(str,key);

printf("Cipher text: %s\n",str);

break;

case 2:

decryption(str,key);

printf("Plain text: %s\n",str);

break;

case 3:

printf("Exit");

break;

default:

printf("Please enter a valid choice");

break;

while(choice!=3);

return 0;

Input:

Text=Bangladesh
Key=monarchy

Output:

Discussion: We have successfully implemented the Playfair cipher.


Experiment No.04

Name of the Experiment: Write a C/C++ program to implement Hill cipher.

Objective:

 Learn about Hill Cipher encryption and decryption.

Algorithm:

Step-1: Organize character alphabetically with numeric A → 1, B → 2, ..., Z →


26 or in ASCII (256 characters)

Step- 2: Create a key matrix measuring m x m

Step-3: Matrix K is an invertible matrix that has multiplicative inverse K−1 so


that K. K−1 = 1

Step-4: Plaintext P = p1 p2 ... pn, blocked with the same size as the row or
column column K

Step-5: Transpose matrix P and became

Step-6: Multiply matrix K with transposed P in modulo 26 or 256


Step-7: Then transpose to

Step-8: Change the result of step 7 into the alphabet using alphabetical
correspondence with numeric in step 1 to obtain the ciphertext

Code:

#include<stdio.h>

#include<math.h>

float encrypt[3][1], decrypt[3][1], a[3][3], b[3][3], mes[3][1], c[3][3];

void encryption();

void decryption();

void inverse();

int main()

int i, j,choice;

char text[3];

printf("Enter a 3x3 key matrix (It should have inverse matrix):\n");

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


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

scanf("%f", &a[i][j]);

c[i][j] = a[i][j];

printf("\nEnter a 3 letter string: ");

scanf("%s", text);

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

mes[i][0] = text[i] - 97;

do{

printf("\n\nHill Cipher\n\n1.Press 1 for Encryption\n2.Press 2 for


decryption\n3.Press 3 for Exit\n");

scanf("%d",&choice);

switch(choice){

case 1:

encryption();

break;

case 2:

decryption();

break;

case 3:

printf("Exit");

break;

default:

printf("Please enter a valid choice");


break;

while(choice!=3);

return 0;

void encryption() {

int i, j, k;

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

for(j = 0; j < 1; j++)

for(k = 0; k < 3; k++)

encrypt[i][j] = encrypt[i][j] + a[i][k] * mes[k][j];

printf("\nEncrypted string is: ");

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

printf("%c", (char)(fmod(encrypt[i][0], 26) + 97));

void decryption() {

int i, j, k;

inverse();

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


for(j = 0; j < 1; j++)

for(k = 0; k < 3; k++)

decrypt[i][j] = decrypt[i][j] + b[i][k] * encrypt[k][j];

printf("\nDecrypted string is: ");

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

printf("%c", (char)(fmod(decrypt[i][0], 26) + 97));

printf("\n");

void inverse() {

int i, j, k;

float p, q;

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

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

if(i == j)

b[i][j]=1;

else

b[i][j]=0;

for(k = 0; k < 3; k++) {

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

p = c[i][k];

q = c[k][k];

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


if(i != k) {

c[i][j] = c[i][j]*q - p*c[k][j];

b[i][j] = b[i][j]*q - p*b[k][j];

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

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

b[i][j] = b[i][j] / c[i][i];

printf("\n\nInverse Matrix is:\n");

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

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

printf("%d ", b[i][j]);

printf("\n");

Input:

Key matrix:

6 24 1

13 16 10

20 17 15

Text=act
Output:

Discussion: We have successfully implemented Hill Cipher encryption


algorithm.
Experiment No.05

Name of the Experiment: Write a C/C++ program to implement Vigenère


cipher.

Objective:

 To know how to encrypt and decrypt using Vigenère cipher.


 Implement Vigenère cipher in C/C++.

Algorithm:

For encryption:

Step-1: Start.

Step-2: Enter an input string as a plaintext.

Step-3: Enter a keyword string as key.

Step-4: Calculate the encrypted string:

The plaintext (P) and key (K) are added modulo 26.

Ei = (Pi + Ki) mod 26.

Step-5: Stop.

For decryption:

Step-1: Start.

Step-2: Enter an input string.

Step-3: Enter a keyword string as key.

Step-4: Calculate the decrypted string:

Di = (Ei - Ki + 26) mod 26

Where, Di denotes the offset of the i-th character of the plaintext. Like offset
of A is 0 and of B is 1 and so on.

Step-5: Stop.
Code:

#include<iostream>

using namespace std;

int i,j,choice,keylen;

string text;

string key;

string newkey;

string encryption(string text,string newkey,int textlen);

string decryption(string text,string newkey,int textlen);

string key_gen(string text,string key,int textlen);

int main()

cout<<"Enter text:";

getline(cin,text);

cout<<"Enter key:";

cin>>key;

int textlen=text.length();

keylen=key.length();

newkey=key_gen(text,key,textlen);

cout<<"\nNewkey:"<<newkey;
do

cout<<"\n\nVigenere Cipher\n\n1.Press 1 for Encryption\n2.Press 2 for


decryption\n3.Press 3 for Exit\n";

cin>>choice;

switch(choice){

case 1:

text=encryption(text,newkey,textlen);

cout<<text;

break;

case 2:

text=decryption(text,newkey,textlen);

cout<<text;

break;

case 3:

cout<<"Exit";

break;

default:

cout<<"Please enter a valid choice";

break;

while(choice!=3);

return 0;
}

string key_gen(string text,string key,int textlen)

char newkey[textlen],res[textlen];

for(i=0,j=0;i<textlen;++i,++j)

if(j==keylen)

j=0;

newkey[i]=key[j];

if(text[i]==' '){

newkey[i]=' ';

j-=1;

newkey[i]='\0';

return newkey;

string encryption(string text,string newkey,int textlen)

char res[textlen];

for(i=0;i<textlen;++i)

if(islower(text[i])||islower(newkey[i])){
text[i]=toupper(text[i]);

newkey[i]=toupper(newkey[i]);

res[i]=((text[i]+newkey[i])%26)+'A';

if(text[i]==' ')

res[i]=' ';

res[i]='\0';

return res;

string decryption(string text,string newkey,int textlen)

char res[textlen];

for(i=0;i<textlen;++i)

if(islower(text[i])||islower(newkey[i])){

text[i]=toupper(text[i]);

newkey[i]=toupper(newkey[i]);

res[i]=(((text[i]-newkey[i])+26)%26)+'A';

if(text[i]==' ')

res[i]=' ';
}

res[i]='\0';

return res;

Input: Text=network security

Key=pen

Output:

Discussion: We have successfully implemented Vigenère cipher.


Experiment No.06

Name of the Experiment: Write a C/C++ program to implement RSA public-


key cryptographic algorithm.

Objective:

 To know about RSA public-key cryptographic algorithm.

Algorithm:

Step-1: Select two different random prime numbers p and q.

Step-2: Calculate n=pq.

n is the modulus for public key and the private keys.

Step-3: Calculate the totient:


φ ( n )=( p−1 ) (q−1)

Step-4: Choose an integer e such that 1 < e <φ ( n ), and e is co-prime to φ ( n )i.e., e
and φ ( n ) share no factors other than 1; gcd(e,φ ( n ))=1.

 e is released as the public key exponent.

Step-5: Compute d to satisfy the congruence relation


de ≡ 1 ( mod φ ( n ) ) i. e . , de=1+ x φ ( n ) for some integer x.

 d is kept as the private key exponent.

The public key is made of the modulus n and the public (or encryption)


exponent e.
The personal key is made of p,q and the private (or decryption)
exponent d which must be kept secret.

Step-6: Compute ciphertext:

c=me mod n

Where, c=ciphertext, m=message, (n,e)=public key

Step-7: Compute plaintext: m=cd mod n

Where, c=ciphertext, m=message, d=private key


Code:

#include<iostream>

#include<math.h>

using namespace std;

int gcd(int a, int b) {

int t;

while(1) {

t= a%b;

if(t==0)

return b;

a = b;

b= t;

int main() {

double message;

cout<<"Enter message:";

cin>>message;

double p = 23;

double q = 13;

double n=p*q;

double track;
double phi= (p-1)*(q-1);

//public key

//e stands for encrypt

double e=2;

//for checking that 1 < e < phi(n) and gcd(e, phi(n)) = 1; i.e., e and phi(n) are
coprime.

while(e<phi) {

track = gcd(e,phi);

if(track==1)

break;

else

e++;

//private key

//d stands for decrypt

double d1=1/e;

double d=fmod(d1,phi);

double c = pow(message,e); //encrypt the message

double m = pow(c,d);

c=fmod(c,n);

m=fmod(m,n);

cout<<"Original Message = "<<message;

cout<<"\n"<<"p = "<<p;

cout<<"\n"<<"q = "<<q;
cout<<"\n"<<"n = pq = "<<n;

cout<<"\n"<<"phi = "<<phi;

cout<<"\n"<<"e = "<<e;

cout<<"\n"<<"d = "<<d;

cout<<"\n\n"<<"Encrypted message = "<<c;

cout<<"\n\n"<<"Decrypted message = "<<m<<"\n";

return 0;

Input: Message=10.

Output:

Discussion: We have successfully implemented RSA Public-key Cryptography


algorithm.
Experiment No.07

Name of the Experiment: Write a C/C++ program to implement Diffie-


Hellman Key exchange algorithm.

Objective: To know about Diffie-Hellman Key exchange algorithm.

Algorithm:

Step-1: Start

Step-2: Select global public elements; a large prime number q and a primitive
root of q, α ; α <q

Step-3: User A key generation:

Select private X A , where, X A <q, and calculate public Y A , where , Y A=α XA mod q

Step-4: User B key generation:

Select private X B , where , X B <q , and calculate public Y B , where , Y B =α XB mod q

Step-5: Calculation of secret key by user A:

K= ( Y B ) XA mod q

Step-6: Calculation of secret key by user B:

K= ( Y B ) XB mod q

Step-7: Stop.

Code:

#include<stdio.h>

#include<math.h>

long long int power(long long int a, long long int b,long long int P)

if (b == 1)
return a;

else

return (((long long int)pow(a, b)) % P);

int main()

long long int P, G, x, a, y, b, ka, kb;

P = 23;

printf("The value of P : %lld\n", P);

G = 9;

printf("The value of G : %lld\n\n", G);

a = 4;

printf("The private key a for user 'X' : %lld\n", a);

x = power(G, a, P);

b = 3;

printf("The private key b for user 'Y' : %lld\n\n", b);

y = power(G, b, P);
ka = power(y, a, P);

kb = power(x, b, P);

printf("Secret key for the user 'X' is : %lld\n", ka);

printf("Secret Key for the user 'Y' is : %lld\n", kb);

return 0;

Output:

Discussion: We have successfully implemented the Diffie-Hellman Key


Exchange Algorithm.

Experiment No.08
Name of the Experiment: Write a C/C++ program to implement Elgamal
Public-key algorithm.

Objective:

 To learn ElGamal Public key algorithm.


 To implement ElGamal Public Key algorithm in C/C++.

Algorithm:

Generation of ElGamal Key Pair

Each user of ElGamal cryptosystem generates the key pair through as follows −

Step-1: Choosing a large prime p. Generally a prime number of 1024 to 2048


bits length is chosen.

Step-2: Choosing a generator element g.

This number must be between 1 and p − 1, but cannot be any number.

It is a generator of the multiplicative group of integers modulo p. This means


for every integer m co-prime to p, there is an integer k such that gk =a mod n .

For example, 3 is generator of group 5 (Z5 = {1, 2, 3, 4}).

Step-3: Choosing the private key. The private key x is any number bigger than
1 and smaller than p−1.

Step-4: Computing part of the public key. The value y is computed from the
parameters p, g and the private key x as follows −

y=g x mod p

Step-5: Obtaining Public key. The ElGamal public key consists of the three
parameters (p, g, y).

ElGamal Encryption

Suppose sender wishes to send a plaintext to someone whose ElGamal public


key is (p, g, y), then −

Step-1: Sender represents the plaintext as a series of numbers modulo p.


Step-2: To encrypt the first plaintext P, which is represented as a number
modulo p, the encryption process to obtain the ciphertext C is as follows −

Randomly generate a number k;

Compute two values C1 and C2, where −

C 1=g k mod p

C 2=( P∗y k ) mod p

Step-3: Send the ciphertext C, consisting of the two separate values (C1, C2),
sent together.

ElGamal Decryption

To decrypt the ciphertext (C1, C2) using private key x, the following two steps
are taken −

Step-1: Compute the modular inverse of ( C 1 ) xmodulo p, which is ( C 1 )−x ,


generally referred to as decryption factor.

Step-2: Obtain the plaintext by using the following formula −


−x
C 2 × ( C 1 ) mod p=Plaintext

Code:

#include<bits/stdc++.h>

using namespace std;

bool isPrimeNumber(int n) {

if (n <= 1) return false;

if (n <= 3) return true;

if (n%2 == 0 || n%3 == 0) return false;

for (int i=5; i*i<=n; i=i+6)

if (n%i == 0 || n%(i+2) == 0)
return false;

return true;

int power(int x, unsigned int y, int p) {

int res = 1;

x = x % p;

while (y > 0){

if (y & 1)

res = (res*x) % p;

y = y >> 1;

x = (x*x) % p;

return res;

void GeneratePrimes(unordered_set<int> &s, int n) {

while (n%2 == 0){

s.insert(2);

n = n/2;

for (int i = 3; i <= sqrt(n); i = i+2){

while (n%i == 0){

s.insert(i);

n = n/i;

}
}

if (n > 2)

s.insert(n);

int findPrimitiveRoot(int n) {

unordered_set<int> s;

if (isPrimeNumber(n)==false)

return -1;

int ETF = n-1;

GeneratePrimes(s, ETF);

for (int r=2; r<=ETF; r++){

bool flag = false;

for (auto it = s.begin(); it != s.end(); it++){

if (power(r, ETF/(*it), n) == 1){

flag = true;

break;

if (flag == false)

return r;

return -1;

double modInverse(double a, double m)


{

a = fmod(a, m);

for (int x = 1; x < m; x++)

if (fmod((a * x) , m) == 1)

return x;

int main()

double K,alpha,zz,k,xa,ya,c1,c2,temp1,temp2,temp3,temp4,temp5,decrypt;

int q1=19;

xa=double(rand()%(q1-2)+1);

alpha=double(findPrimitiveRoot(q1));

double q=double(q1);

// xa=5;

zz=pow(alpha,xa);

ya=fmod(zz,q);

cout<<"Public Key: q="<<q<<", alpha="<<alpha<<", ya="<<ya;

cout<<"\nPrivate Key: xa="<<xa<<endl;

k=6;

temp1=pow(ya,k);
K=fmod(temp1,q);

double m=17;

cout<<"\nOriginal Message="<<m<<endl;

temp2=pow(alpha,k);

c1=fmod(temp2,q);

c2=fmod((K*m),q);

cout<<"\nEncrypted Message:(C1,C2)="<<c1<<","<<c2<<endl;

temp3=pow(c1,xa);

K=fmod(temp3,q);

cout<<"\nK="<<K;

temp4=modInverse(K,q);

temp5=c2*temp4;

decrypt=fmod(temp5,q);

cout<<"\nDecrypted Message="<<decrypt<<endl;

return 0;
}

Input:

17

Output:

Discussion: We have successfully implemented ElGamal Public key algorithm.

Experiment No.09
Name of the Experiment: Write a C/C++ program to implement a Simple
Hash Function using simple XOR operation.

Objective:

 To learn about cryptographic hash function using simple XOR operation.

Algorithm:

Step-1: Start.

Step-2: Enter input.

Step-3: Convert the input as a sequence of n-bit binary blocks.

Step-4: Process one block at a time:

Compute bit by bit exclusive-OR (XOR) of every block:


C i=bi 1 ⊕bi 2 ⊕ … ⊕b ℑ

Where,
C i=ith bit of the hash code ,1 ≤i ≤ n

m=number of n-bit blocks in the input


b ij=ith bit ∈ jth block

⊕=XOR operation

Step-5: Return C.

Step-6: Stop.

Code:
#include<stdio.h>

#include<string.h>

int main()

char str[50];

int ascii[50],i,j=0,block[50][50],remainder[50][50],arr_size;

printf("Enter a string:");

gets(str);

int len=strlen(str);

for(i=0;i<len;i++)

j=0;

ascii[i]=(int)str[i];

printf("ASCII code for %c is:%d\n",str[i],ascii[i]);

// printf("Binary code is:");

while(ascii[i]!=0)

remainder[i][j]=ascii[i]%2;

// printf("%d",remainder[i][j]);

ascii[i]=ascii[i]/2;

j++;

}
printf("\n\n");

i=0;

for(j=0;j<8;j++)

block[i][j]=remainder[i][j];

for(i=0;i<len-1;i++)

for(j=0;j<8;j++)

if(block[i][j]!=remainder[i+1][j])

block[i+1][j]=1;

else block[i+1][j]=0;

// printf("%d",block[i+1][j]);

// printf("\n");

printf("Hash code generated is:");

i=len-1;

for(j=7;j>=0;j--)
printf("%d",block[i][j]);

printf("\n");

return 0;

Input: word.

Output:

Discussion: We have successfully implemented a simple hash function using


simple XOR operation.

You might also like