0% found this document useful (0 votes)
10 views60 pages

Crns Lab Record

The document outlines a series of programming tasks related to cryptography and network security, including the implementation of various encryption algorithms such as XOR, AND, Ceaser Cipher, Substitution Cipher, Hill Cipher, DES, Blowfish, Rijndael, RSA, and Diffie-Hellman Key Exchange. It provides specific aims, procedures, and example code in C and Java for each task. Additionally, it includes explanations of the algorithms and their workings, along with sample outputs for some of the programs.

Uploaded by

shireesh
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)
10 views60 pages

Crns Lab Record

The document outlines a series of programming tasks related to cryptography and network security, including the implementation of various encryption algorithms such as XOR, AND, Ceaser Cipher, Substitution Cipher, Hill Cipher, DES, Blowfish, Rijndael, RSA, and Diffie-Hellman Key Exchange. It provides specific aims, procedures, and example code in C and Java for each task. Additionally, it includes explanations of the algorithms and their workings, along with sample outputs for some of the programs.

Uploaded by

shireesh
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

CRYPTOGRAPHY AND NETWORK SECURITY LAB

1. Write a C program that contains a string (char pointer) with a value ‘Hello
world’. The program should XOR each character in this string with 0 and displays
the result.

2. Write a C program that contains a string (char pointer) with a value ‘Hello
world’. The program should AND or and XOR each character in this string with
127 and display the result.

3. Write a Java program to perform encryption and decryption using the following
algorithms

a. Ceaser Cipher

b. Substitution Cipher

c. Hill Cipher

4. Write a C/JAVA program to implement the DES algorithm logic.

5. Write a C/JAVA program to implement the Blowfish algorithm logic.

6. Write a C/JAVA program to implement the Rijndael algorithm logic.

7. Write the RC4 logic in Java Using Java cryptography; encrypt the text “Hello
world” using Blowfish. Create your own key using Java key tool.

8. Write a Java program to implement RSA algorithm.

9. Implement the Diffie-Hellman Key Exchange mechanism using HTML and


JavaScript.

10. Calculate the message digest of a text using the SHA-1 algorithm in JAVA.

11. Calculate the message digest of a text using the MD5 algorithm in JAVA.
1. XOR a string with a Zero

AIM:

Write a C program that contains a string (char pointer) with a value ‘Hello world’.
The program should XOR each character in this string with 0 and displays the
result.

PROCEDURE:

The given string is ABC

XOR each character with ‘0’.

ASCII Values of

A 65

B 66

C 67

Where

A  (65) 01000001

+ 00000000

01000001  A (65)

ABC

+ 000

ABC

Here, the encrypted data is same as the given data, if we are doing XOR Operation
with ‘0’, So we cannot do XOR Operation with ‘0’.
PROGRAM: *

#include<stdlib.h>

main()

char str[]="Hello World";

char str1[11];

int i,len;

len=strlen(str);

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

str1[i]=str[i]^0;

printf("%c",str1[i]);

printf("\n");

OUTPUT:

Hello World

Hello World
2. XOR a string with a 127

AIM:

Write a C program that contains a string (char pointer) with a value ‘Hello world’.
The program should AND or and XOR each character in this string with 127 and
display the result.

PROCEDURE:

a. Given String is ABC and XOR each character with 127


Ascii value of ‘A’ is 65

A 65 01000001

127 + 01111111

0 0 1 1 1 1 1 0  62 (Cipher Text)

+ 01111111 (127)

0 1 0 0 0 0 0 1  65 (Plain Text)

b. AND each character with 127

A 65 01000001

127 AND 0 1 1 1 1 1 1 1

0 1 0 0 0 0 0 1  65(A) Same data

Hence AND operation is not used.


PROGRAM: *

#include <stdio.h>

#include<stdlib.h>

void main()

clrscr();

char str[]="Hello World";

char str1[11];

char str2[11];

int i,len;

len = strlen(str);

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

str1[i] = str[i]&127;

printf("%c",str1[i]);

printf("\n");

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

str2[i] = str1[i]^127;

printf("%c",str2[i]);

printf("\n");
getch();

}
a. AND with 127

#include<stdio.h>

#include<conio.h>

#include<string.h>

void main()

char s[10],e[10],d[10];

int i,n;

printf(“Enter the String”);

scanf(“%s”, s);

n=strlen(s);

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

e[i]=s[i]&127;

printf(“Encrypted text %s”, e[i]);

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

d[i]=e[i]&127;

printf(“Decrypted text %s”,d[i]);

if(strcmp(s,d)==0)
print(“Equal”);

else

printf(“Not Equal”);

getch();

OUTPUT:

Enter the String abc

Encrypted text abc

Decrypted text abc

Equal
3. Encryption & Decryption using Cipher Algorithms

AIM:

Write a Java program to perform encryption and decryption using the following
algorithms

PROCEDURE:

a. Ceaser Cipher :

If the given plain text is THIS and Key is 5.


Plain text = THIS
Key =5

T - 19+5 = 24
H - 7+5 = 12
I - 8+5 = 13
S - 18+5 = 23

Encryption – C = (P+K) mod 26

T = 24 mod 26
= 24  Y
H = 12 mod 26
= 12  M
I = 13 mod 26
= 13  N
S = 23 mod 26
= 23  X

The Cipher text is YMNX


Decryption – P = (C-K) mod 26
T - 24-5 = 19
H - 12-5 = 7
I - 13-5 = 8
S - 23-5 = 18
The decrypted text is THIS.
PROGRAM: *

import [Link];

import [Link].*;

import [Link];

public class CeaserCipher

static Scanner sc=new Scanner([Link]);

staticBufferedReader br = new BufferedReader(new


InputStreamReader([Link]));

public static void main(String[] args) throws IOException

// TODO code application logic here

[Link]("Enter any String: ");

String str = [Link]();

[Link]("\nEnter the Key: ");

int key = [Link]();

String encrypted = encrypt(str, key);

[Link]("\nEncrypted String is: " +encrypted);

String decrypted = decrypt(encrypted, key);

[Link]("\nDecrypted String is: " +decrypted);

[Link]("\n");

}
public static String encrypt(String str, int key)

String encrypted = "";

for(int i = 0; i < [Link](); i++)

int c = [Link](i);

if ([Link](c))

c = c + (key % 26);

if (c > 'Z')

c = c - 26;

else if ([Link](c))

c = c + (key % 26);

if (c > 'z')

c = c - 26;

encrypted += (char) c;

return encrypted;

public static String decrypt(String str, int key)


{

String decrypted = "";

for(int i = 0; i < [Link](); i++)

int c = [Link](i);

if ([Link](c))

c = c - (key % 26);

if (c < 'A')

c = c + 26;

else if ([Link](c))

c = c - (key % 26);

if (c < 'a')

c = c + 26;

decrypted += (char) c;

return decrypted;

}
OUTPUT:

Enter any String: Hello World

Enter the Key: 5

Encrypted String is: MjqqtBtwqi

Decrypted String is: Hello World


b. Substitution Cipher (Mono-alphabetic Cipher):

PROCEDURE:

P[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
C[26] = z y x w v u t s r q p o n m l k j I h g f e d c b a

Plain text : hello world


Cipher text : svool dliow
Plain text : this is crns class
Cipher text : grsh rh ximh xozhh
Plain text : this is crns class

PROGRAM: *

import [Link].*;

import [Link].*;

public class SubstitutionCipher

static Scanner sc = new Scanner([Link]);

static BufferedReader br = new BufferedReader(new


InputStreamReader([Link]));

public static void main(String[] args) throws IOException

// TODO code application logic here

String a = "abcdefghijklmnopqrstuvwxyz";

String b = "zyxwvutsrqponmlkjihgfedcba";

[Link]("Enter any string: ");

String str = [Link]();


String encrypt = "";

char c;

for(int i=0;i<[Link]();i++)

c = [Link](i);

int j = [Link](c);

encrypt = encrypt+[Link](j);

[Link]("The encrypted data is: " +encrypt);

OUTPUT:

Enter any string: aceho

The encrypted data is: zxvsl


c. Hill Cipher:

PROCEDURE:

Input : Plaintext: ACT


Key : GYBNQKURP
Output : Ciphertext: POH
Input : Plaintext: GFG
Key: HILLMAGIC
Output : Ciphertext: SWK

Encryption:

We have to encrypt the message ‘ACT’ (n=3).The key is ‘GYBNQKURP’ which


can be written as the nxn matrix:

The message ‘ACT’ is written as vector:

The enciphered vector is given as:


which corresponds to ciphertext of ‘POH’
Decryption:

To decrypt the message, we turn the ciphertext back into a vector, then simply
multiply by the inverse matrix of the key matrix (IFKVIVVMI in letters).The
inverse of the matrix used in the previous example is:

For the previous Ciphertext ‘POH’:

which gives us back ‘ACT’.


Assume that all the alphabets are in upper case.
Below is the implementation of the above idea for n=3.
PROGRAM:
import [Link].*;

class Basic

String allChar="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int indexOfChar(char c)

for(int i=0;i < [Link]();i++)

if([Link](i)==c)

return i;

return -1;

char charAtIndex(int pos)

return [Link](pos);

class Hill

Hill(int block)

[Link]=block;
}

Basic b1=new Basic();

int block=2;

int key[][]=new int[block][block];

void keyInsert()throws Exception

Scanner scn=new Scanner([Link]);

[Link]("Enter key Matrix");

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

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

key[i][j]=[Link]();

void KeyInverseInsert()throws Exception

Scanner scn=new Scanner([Link]);

[Link]("Enter key Inverse Matrix:");

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

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


{

key[i][j]=[Link]();

String encryptBlock(String plain)throws Exception

plain=[Link]();

int a[][]=new int[block][1],sum=0;

int cipherMatrix[][]=new int[block][1];

String cipher="";

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

a[i][0]=[Link]([Link](i));

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

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

for(int k=0;k < block;k++)

sum=sum+key[i][k]*a[k][j];

}
cipherMatrix[i][j] = sum%26;

sum = 0;

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

cipher+=[Link](cipherMatrix[i][0]);

return cipher;

String encrypt(String plainText)throws Exception

String cipherText="";

keyInsert();

plainText=[Link]();

int len=[Link]();

// [Link]([Link](1,2+1));

while(len%block!=0)

plainText+="X";

[Link](len);

len=[Link]();

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

cipherText+=encryptBlock([Link](i,i+block));

cipherText+=" ";

return cipherText;

String decryptBlock(String cipher)throws Exception

cipher=[Link]();

int a[][]=new int[block][1],sum=0;

int plainMatrix[][]=new int[block][1];

String plain="";

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

a[i][0]=[Link]([Link](i));

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

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

for(int k=0;k < block;k++)

{
sum=sum+key[i][k]*a[k][j];

while(sum < 0)

sum+=26;

plainMatrix[i][j] = sum;

sum = 0;

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

plain+=[Link](plainMatrix[i][0]);

return plain;

String Decrypt(String cipherText)throws Exception

String plainText="";

KeyInverseInsert();

cipherText=[Link](" ", "");

cipherText=[Link]();

int len=[Link]();
for(int i=0;i < len-1;i=i+block)

plainText+=decryptBlock([Link](i,i+block));

plainText+=" ";

return plainText;

class HillCipher{

public static void main(String args[])throws Exception

String plainText,cipherText;

int block;

Scanner scn=new Scanner([Link]);

[Link]("Enter plain-text:");

plainText=[Link]();

[Link]("Enter block size of matrix:");

block=[Link]();

Hill hill=new Hill(block);

plainText=[Link](" ", "");

cipherText= [Link](plainText);

[Link]("Encrypted Text is:\n"+cipherText);

String decryptedText= [Link](cipherText);


[Link]("Decrypted Text is:\n"+decryptedText);

OUTPUT:

Enter plain-text:

meet

Enter block size of matrix:

Enter key Matrix

31

52

Encrypted Text is:

OQ FG

Enter key Inverse Matrix:

2 -1

-5 3

Decrypted Text is:

ME ET

4. Java program for DES algorithm logic


AIM:

Write a C/JAVA program to implement the DES algorithm logic.

PROCEDURE:

DES is a symmetric encryption system that uses 64-bit blocks, 8 bits of which are
used for parity checks. The key therefore has a "useful" length of 56 bits, which
means that only 56 bits are actually used in the algorithm. The algorithm involves
carrying out combinations, substitutions and permutations between the text to be
encrypted and the key, while making sure the operations can be performed in both
directions. The key is ciphered on 64 bits and made of 16 blocks of 4 bits,
generally denoted k1 to k16. Given that "only" 56 bits are actually used for
encrypting, there can be 256 different keys.

The main parts of the algorithm are as follows:

 Fractioning of the text into 64-bit blocks


 Initial permutation of blocks
 Breakdown of the blocks into two parts: left and right, named L and
R
 Permutation and substitution steps repeated 16 times
 Re-joining of the left and right parts then inverse initial permutation

ALGORITHM:

STEP-1: Read the 64-bit plain text.


STEP-2: Split it into two 32-bit blocks and store it in two different arrays.
STEP-3: Perform XOR operation between these two arrays.
STEP-4: The output obtained is stored as the second 32-bit sequence and the
original second 32-bit sequence forms the first part.
STEP-5: Thus the encrypted 64-bit cipher text is obtained in this way.
Repeat the same process for the remaining plain text characters.

PROGRAM:
JAVA PROGRAM:

import [Link];

import [Link];

import [Link];

import [Link];

class DesJava

public static void main(String[]args)throws Exception

KeyGenerator kg = [Link]("Des");

SecretKey sk;

sk = [Link]();

Cipher c=[Link]("Des");

[Link](Cipher.ENCRYPT_MODE,sk);

String input=[Link]("input your message:");

byte[]encrypt=[Link]([Link]());

[Link](Cipher.DECRYPT_MODE,sk);

byte[]decrypt=[Link](encrypt);

[Link]([Link](),"\n Encrypted
text:"+new String(encrypt)+"\n"+"\n Decrypted text:"+new String(decrypt));

[Link](0);

}}
OUTPUT:
5. Program to implement BlowFish algorithm logic

AIM:

Write a C/JAVA program to implement the BlowFish algorithm logic.

PROCEDURE:

1. BlockSize: 64-bits
2. KeySize: 32-bits to 448-bits variable size
3. Number of subkeys: 18 [P-array]
4. Number of rounds: 16
5. Number of subsitution boxes: 4 [each having 512 entries of 32-bits each]
The entire encryption process can be elaborated as:
ALGORITHM:

STEP 1: Blowfish first step is to initiate the substitution box (Sbox) and
permutation box (Pbox). The Pbox entries are shown as the Pi in the diagram
above. There are a total of 18 Pbox entries.

STEP 2: Next, we split our 64-bit plaintext into two equal blocks, L and R.

STEP 3: Next, we enter an encryption loop that runs 16 times. The following
steps take place in each loop:

a. We XOR L with Pi, where i depends on the loop’s current iteration.

b. We then XOR R with F, which is a function of L that makes use of the


Sbox split into 4 blocks. The overview of the F function is shown in the
image below.

c. Finally, L and R are swapped before the loop enters its next iteration.
STEP 4: After the loop finishes, L and R are swapped once more.

STEP 5: Next, we make use of our last two unused Pbox entries by
XORing R with P17 and L with P18.

STEP 6: Finally, we combine L and R to retrieve the cipher text.

PROGRAM:

import [Link];

import [Link];

import [Link];

import [Link];

public class BlowFish {

public static void main(String[] args) throws Exception {

KeyGenerator keygenerator = [Link]("Blowfish");


Cipher cipher = [Link]("Blowfish");

SecretKey secretkey = [Link]();

[Link](Cipher.ENCRYPT_MODE, secretkey);

String inputText = [Link]("Input your message:");

byte[] encrypted = [Link]([Link]());

[Link](Cipher.DECRYPT_MODE, secretkey);

byte[] decrypted = [Link](encrypted);

[Link]([Link](),

"\nEncrypted text: " + new String(encrypted) + "\n" +"\nDecrypted text: " + new
String(decrypted));

[Link](0);

}}

OUTPUT:
6. Program to implement Rijndael algorithm logic

AIM:

Write a C/JAVA program to implement the Rijndael algorithm logic.

PROCEDURE:

The encryption process uses a set of specially derived keys called round keys.
These are applied, along with other operations, on an array of data that holds
exactly one block of data?the data to be encrypted. This array we call the state
array.
You take the following aes steps of encryption for a 128-bit block:
1. Derive the set of round keys from the cipher key.
2. Initialize the state array with the block data (plaintext).
3. Add the initial round key to the starting state array.
4. Perform nine rounds of state manipulation.
5. Perform the tenth and final round of state manipulation.
6. Copy the final state array out as the encrypted data (ciphertext).
The reason that the rounds have been listed as "nine followed by a final tenth
round" is because the tenth round involves a slightly different manipulation from
the others.
The block to be encrypted is just a sequence of 128 bits. AES works with byte
quantities so we first convert the 128 bits into 16 bytes. We say "convert," but, in
reality, it is almost certainly stored this way already. Operations in RSN/AES are
performed on a two-dimensional byte array of four rows and four columns. At the
start of the encryption, the 16 bytes of data, numbered D0 ? D15, are loaded into
the array as shown in Table A.5.
Each round of the encryption process requires a series of steps to alter the state
array. These steps involve four types of operations called:
 SubBytes
 ShiftRows
 MixColumns
 XorRoundKey
ALGORITHM:
Steps of encryption for a 128-bit block:
1. Derive the set of round keys from the cipher key.
2. Initialize the state array with the block data (plaintext).
3. Add the initial round key to the starting state array.
4. Perform nine rounds of state manipulation.
5. Perform the tenth and final round of state manipulation.
6. Copy the final state array out as the encrypted data (ciphertext).
Each round of the encryption process requires a series of steps to alter the state
array. These steps involve four types of operations called:
 SubBytes
 ShiftRows
 The details of these operations are described shortly, but first we need to
look in more detail at the generation of the Round Keys, so called because
there is a different one for each round in the process.
 Round Keys
Operations used in computing each round. Earlier we mentioned that four
operations are required called:
 SubBytes
 ShiftRows
 MixColumns
 XorRoundKey
Decryption involves reversing all the steps taken in encryption using inverse
functions:
 InvSubBytes
 InvShiftRows
 InvMixColumns

PROGRAM:
import [Link];

import [Link];

import [Link];
import [Link];

class AesJavaaa

public static void main(String[]args)throws Exception

KeyGenerator kg = [Link]("Aes");

SecretKey sk;

sk = [Link]();

Cipher c=[Link]("Aes");

[Link](Cipher.ENCRYPT_MODE,sk);

String input=[Link]("input your message:");

byte[]encrypt=[Link]([Link]());

[Link](Cipher.DECRYPT_MODE,sk);

byte[]decrypt=[Link](encrypt);

[Link]([Link](),"\n Ecrypted
text:"+new String(encrypt)+"\n"+"\n Decrypted text:"+new String(decrypt));

[Link](0);

OUTPUT:
7. Encrypt a string using BlowFish algorithm
AIM:

Write the RC4 logic in Java Using Java cryptography; encrypt the text “Hello
world” using Blowfish. Create your own key using Java key tool.

PROCEDURE:

Steps:
Step1: Generation of sub keys: 18 sub keys {P[0]..P[17]}
Step2: initialise Substitution Boxes
Step3: Encryption

Parameters:
1. Block Size: 64-bits
2. Key Size: 32-bits to 448-bits variable size
3. number of sub keys: 18 [P-array]
4. number of rounds: 16
5. number of substitution boxes: 4 [each having 512 entries of 32-bits each]

The entire encryption process can be elaborated as:

ALGORITHM –
RC4 is a stream cipher and variable-length key algorithm. This algorithm
encrypts one byte at a time (or larger units at a time).
A key input is pseudorandom bit generator that produces a stream 8-bit number
that is unpredictable without knowledge of input key, The output of the
generator is called key-stream, is combined one byte at a time with the plaintext
stream cipher using X-OR operation.

STEPS –

1. Key-Scheduling Algorithm:

Initialization: The entries of S are set equal to the values from 0 to 255 in
ascending orders, a temporary vector T, is created.

2. Pseudo random generation algorithm (Stream Generation):

Once the vector S is initialized, the input key will not be used. In this step, for
each S[i] algorithm swap it with another byte in S according to a scheme dictated
by the current configuration of S.

3. Encrypt using X-Or ()

PROGRAM: *

import [Link].*;

class Rc4

public static void main(String args[])throws IOException

int temp=0;

String ptext;

String Key;

int s[]=new int[256];


int k[]=new int[256];

DataInputStream in=new DataInputStream([Link]);

[Link]("ENTER PLAIN TETX");

ptext=[Link]();

[Link]("ENTER KEY TEXT");

String key = [Link]();

char ptextc[]=[Link]();

char keyc[]=[Link]();

int cipher[]=new int[[Link]()];

int decrypt[]=new int[[Link]()];

int ptexti[]=new int [[Link]()];

int keyi[]=new int [[Link]()];

for(int i=0;i<[Link]();i++)

ptexti[i]=(int)ptextc[i];

for(int i=0;i<[Link]();i++)

keyi[i]=(int)keyc[i];

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

s[i]=i;
k[i]=keyi[i%[Link]()];

int j=0;

for(int l=0;l<255;l++)

int i = 0;

j=(j+s[i]+k[i])%256;

temp=s[i];

s[i]=s[j];

s[j]=temp;

int i=0;

j=0;

int z=0;

for(int l=0;l<[Link]();l++)

i=(l+1)%256;

j=(j+s[i])%256;

temp=s[i];

s[i]=s[j];

z=s[(s[i]+s[j])%256];

cipher[l]=z^ptexti[l];

decrypt[l]=z^cipher[l];
}

[Link]("\nENCRYPTED:");

display(cipher);

[Link]("\nDECRYPTED:");

display(decrypt);

static void display(int disp[])

char convert[]=new char[[Link]];

for(int l=0;l<[Link];l++)

convert[l]=(char)disp[l];

[Link](convert[l]);

OUTPUT:

ENTER PLAIN TEXT

welcome

ENTER KEY TEXT

ENCRYPTED:

uc`wqG]
DECRYPTED:

welcome

8. RSA ALGORITHM

AIM:
Write a Java program to implement RSA Algorithm.

PROCEDURE:

1. Choose two large prime numbers P and Q


2. Calculate the value n= P*Q
3. Select the public key(Encryption key) E, such that it is not a factor of
Φ(n) = (P-1)(Q-1)
4. Select the private key(Decryption key) D, such that the following equation is
true
(D*E) mod Φ(n)= 1
5. For Encryption , Calculate the cipher text CT from the plain text PT as
follows:
CT = PT^e mod n
6. Send CT as the cipher text to the receiver
7. For Decryption , Calculate the plain text PT from the cipher text CT as
follows:
PT = CT^e mod n

ALGORITHM:

STEPS –
1. Generate the RSA modulus
2. Derived Number (e)
3. Public key
4. Private Key
5. Encryption
6. Decryption

PROGRAM:

JAVA PROGRAM:

import [Link].*;

import [Link];

import [Link];

public class RSA

static Scanner sc = new Scanner([Link]);

public static void main(String[] args)

// TODO code application logic here

[Link]("Enter a Prime number: ");

BigInteger p = [Link](); // Here's one prime number..

[Link]("Enter another prime number: ");

BigInteger q = [Link](); // and another.

BigInteger n = [Link](q);

BigInteger n2 =
[Link]([Link]).multiply([Link]([Link]));
BigInteger e = generateE(n2);

BigInteger d = [Link](n2); // Here's the multiplicative inverse

[Link]("Encryption keys are: " + e + ", " + n);

[Link]("Decryption keys are: " + d + ", " + n);

public static BigInteger generateE(BigInteger fiofn)

int y, intGCD;

BigInteger e;

BigInteger gcd;

Random x = new Random();

do

y = [Link]([Link]()-1);

String z = [Link](y);

e = new BigInteger(z);

gcd = [Link](e);

intGCD = [Link]();

while(y <= 2 || intGCD != 1);

return e;

}
OUTPUT:

Enter a Prime number: 5

Enter another prime number: 11

Encryption keys are: 33, 55

Decryption keys are: 17, 55

C PROGRAM: *

#include<math.h>

#include<stdio.h>

#include<conio.h>

int gcd(int a,int h)

int t;

while(1)

t=a%h;

if(t==0)

return h;

a=h;

h=t;

void main()

{
int phi,m,e,c,p,q,d,z,n;

clrscr();

printf(“\n Enter two prime numbers as p and q:”);

scanf(“%d %d”,&p,&q);

printf(“\n Enter encryption key value:”);

scanf(“%d”, &e);

n=p*q;

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

while(e<phi)

if(gcd(e,phi)==1)

break;

else

e++;

for(d=1;d<phi;d++)

if((d*e)%phi==1)

z=d;

printf(“\n Enter plaintext value:”);

scanf(“%d”, &m);

c=pow(m,e);
c=fmod(c,n);

printf(“\n ciphertext generated is: %d”,c);

m=pow(c,z);

m=fmod(m,n);

printf(“\n decryption text is: %d”,m);

getch();

OUTPUT:

Enter two prime numbers as p and q: 3 5

Enter encryption key value: 2

Enter plaintext value: 2

ciphertext generated is: 8

decryption text is: 2

9. DIFFIE-HELLMAN

AIM:
Implement the Diffie-Hellman Key Exchange mechanism using HTML and
JavaScript.

PROCEDURE:

STEP-1: Both Alice and Bob shares the same public keys g and p.

STEP-2: Alice selects a random public key a.

STEP-3: Alice computes his secret key A as ga mod p.

STEP-4: Then Alice sends A to Bob.

STEP-5: Similarly Bob also selects a public key b and computes his secret key as
B and sends the same back to Alice.

STEP-6: Now both of them compute their common secret key as the other one’s
secret key power of a mod p.

ALGORITHM:

STEPS –

1. Choose two numbers ‘a’ and ‘n’ and exchange with the other party.
2. Both the parties already know their own private key.
3. Both the parties calculate the value of their public key and exchange with
each other.
4. Both the parties receive public key of each other.
5. Now, both the parties calculate the value of secret key.

JAVA PROGRAM:

import [Link];
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class DiffeHellman

public final static int pValue = 47;

public final static int gValue = 71;

public final static int XaValue = 9;

public final static int XbValue = 14;

public static void main(String[] args) throws Exception

// TODO code application logic here

BigInteger p = new BigInteger([Link](pValue));

BigInteger g = new BigInteger([Link](gValue));

BigInteger Xa = new BigInteger([Link](XaValue));

BigInteger Xb = new BigInteger([Link](XbValue));

createKey();

int bitLength = 512; // 512 bits

SecureRandom rnd = new SecureRandom();

p = [Link](bitLength, rnd);
g = [Link](bitLength, rnd);

createSpecificKey(p, g);

public static void createKey() throws Exception

KeyPairGenerator kpg = [Link]("DiffieHellman");

[Link](512);

KeyPair kp = [Link]();

KeyFactory kfactory = [Link]("DiffieHellman");

DHPublicKeySpec kspec = (DHPublicKeySpec)


[Link]([Link](),

[Link]);

[Link]("Public key is: " +kspec);

public static void createSpecificKey(BigInteger p, BigInteger g) throws Exception

KeyPairGenerator kpg=[Link]("DiffieHellman");

DHParameterSpec param = new DHParameterSpec(p, g); [Link](param);

KeyPair kp = [Link]();

KeyFactory kfactory = [Link]("DiffieHellman");

DHPublicKeySpec kspec = (DHPublicKeySpec)


[Link]([Link](),

[Link]);
[Link]("\nPublic key is : " +kspec);

OUTPUT:

Public key is: [Link]@5afd29

Public key is: [Link]@9971ad

C PROGRAM: *

#include<stdio.h>

#include<conio.h>

#include<type.h>

#include<math.h>

void main()

long int n, g, x,y,ya,yb,k1,k2,A,B,C,D;

clrscr();

printf(“Enter n value: “);

scanf(“%ld”, &n);

printf(“Enter g value: “);

scanf(“%ld”, &g);

printf(“Enter private key at A as x:”);

scanf(“%ld”,&x);

printf(“Enter private key at B as y:”);


scanf(“%ld”, &y);

// A= gx mod n

A= pow(g,x);

ya=A%n;

printf(“\n Public Key of A is %ld”, ya);

// B= gy mod n

B=pow(g,y);

yb=B%n;

printf(“\n Pubic Key of B is %ld”, yb);

printf(“\n Secret key generated at A is k1:”);

// k1 = Bx mod n

C= pow(yb,x);

k1 = C%n;

Printf(“ \n k1 is %ld”, k1);

printf(“\n Secret key generated at b is k2:”);

// k2 = Ay mod n

D= pow(ya,y);

K2 = D%n;

printf(“ \n k2 is %ld’, k2);

if(k1==k2)

printf(“\n Key Exchange is Successful”);

else

printf(“\n Key Exchange is failed”);


getch();

OUTPUT:

Enter n value:11

Enter f value:7

Enter private key of A at x:3

Enter private key of B at y:6

Public key of A is 2

Public key of A is 4

Secret key generated at A is K1:

K1 is 9

Secret key generated at B is k2:

K2 is 9

Key Exchange is Successful

10. SHA-1

AIM:

Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
PROCEDURE:

SHA-1 or Secure Hash Algorithm 1 is a cryptographic hash function which takes


an input and produces a 160-bit (20-byte) hash value. This hash value is known as
a message digest. This message digest is usually then rendered as a hexadecimal
number which is 40 digits long.

Example:

The procedure is used to send a non secret but signed message from sender to
receiver. In such a case following steps are followed:
1. Sender feeds a plaintext message into SHA-l algorithm and obtains a 160-bit
SHA-l hash.
2. Sender then signs the hash with his RSA private key and sends both the plaintext
message and the signed hash to the receiver.
3. After receiving the message, the receiver computes the SHA-l hash himself and
also applies the sender's public key to the signed hash to obtain the original hash H.

ALGORITHM:

Step 1 – Pre-Processing. Convert “hello world” to binary


Step 2 – Initialize Hash Values (h). Now we create 8 hash values
Step 3 – Initialize Round Constants (k)
Step 4 – Chunk Loop
Step 5 – Create Message Schedule (w)
Step 6 – Compression

PROGRAM:

import [Link];
import [Link];

public class SHAA1 {


public static String getSHA1(String input)
{
try
{
// getInstance() method is called with algorithm SHA-1
MessageDigest md = [Link]("SHA-1");
byte[] messageDigest = [Link]([Link]());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = [Link](16);
// Add preceeding 0's to make its 40bit
while ([Link]() < 40)
{
hashtext = "0" + hashtext;
}
return hashtext;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public static void main(String args[])
{
[Link]("HashCode Generated by SHA-1 for: ");
String s1 = "GeeksForGeeks";
[Link]("\n" + s1 + " : " + getSHA1(s1));
String s2 = "Hello World";
[Link]("\n" + s2 + " : " + getSHA1(s2));
}
}

OUTPUT:

HashCode Generated by SHA-1 for:

GeeksForGeeks : addf120b430021c36c232c99ef8d926aea2acd6b

Hello World : 0a4d55a8d778e5022fab701977c5d840bbc486d0

11. Message Digest Algorithm5 (MD5)


AIM:

Calculate the message digest of a text using the MD5 algorithm in JAVA.

PROCEDURE:
The MD5 hashing algorithm is a one-way cryptographic function that accepts a
message of any length as input and returns as output a fixed-length digest value to
be used for authenticating the original message.

The MD5 message digest hashing algorithm processes data in 512-bit blocks,
broken down into 16 words composed of 32 bits each. The output from MD5 is a
128-bit message digest value.

Computation of the MD5 digest value is performed in separate stages that process
each 512-bit block of data along with the value computed in the preceding stage:

 The first stage begins with the message digest values initialized using
consecutive hexadecimal numerical values
 Each stage includes four message digest passes which manipulate values
in the current data block and values processed from the previous block
 The final value computed from the last block becomes the MD5 digest for
that block

ALGORITHM:

Step1: Append Padding Bits. Padding means adding extra bits to the original
message.
Step 2: Append Length. After padding, 64 bits are inserted at the end, which is
used to record the original input length.
Step 3: Initialize MD buffer.
Step 4: Processing message in 16-word block.
Step 5: Process each 512 bit block.

PROGRAM:

import [Link];
import [Link];

public class MD5


{
public static String getMD5(String input)
{
try
{
// getInstance() method is called with algorithm SHA-1
MessageDigest md = [Link]("MD5");
byte[] messageDigest = [Link]([Link]());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = [Link](16);
// Add preceeding 0's to make its 40bit
while ([Link]() < 32)
{
hashtext = "0" + hashtext;
}
return hashtext;
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
public static void main(String args[])
{
[Link]("HashCode Generated by MD5 for: ");
String s1 = "GeeksForGeeks";
[Link]("\n" + s1 + " : " + getMD5(s1));
String s2 = "Hello World";
[Link]("\n" + s2 + " : " + getMD5(s2));
}
}

OUTPUT:

HashCode Generated by SHA-1 for:

GeeksForGeeks : e39b9c178b2c9be4e99b141d956c6ff6

Hello World : b10a8db164e0754105b7a99be72e3fe5

You might also like