0% found this document useful (0 votes)
17 views61 pages

C&NS Lab Manual27.03.19final

The document is a lab manual for a Cryptography and Network Security course at Jagruti Institute of Engineering & Technology, detailing various programming tasks related to encryption and decryption algorithms. It includes C and Java programs for XOR operations, DES, BlowFish, Rijndael, RSA, and different cipher algorithms like Caesar, Substitution, and Hill Cipher. Each section provides an aim, algorithm, and sample code along with expected outputs for educational purposes.

Uploaded by

rahulkumarma502
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)
17 views61 pages

C&NS Lab Manual27.03.19final

The document is a lab manual for a Cryptography and Network Security course at Jagruti Institute of Engineering & Technology, detailing various programming tasks related to encryption and decryption algorithms. It includes C and Java programs for XOR operations, DES, BlowFish, Rijndael, RSA, and different cipher algorithms like Caesar, Substitution, and Hill Cipher. Each section provides an aim, algorithm, and sample code along with expected outputs for educational purposes.

Uploaded by

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

CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.

II Sem. CSE

JAGRUTI INSTITUTE OF ENGINEERING & TECHNOLOGY


KOHEDA ROAD, IBRAHIMPATNAM (M), R.R. DIST – 501510

DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING

B.Tech. III Year II Sem.


CRYPTOGRAPHY & NETWORK SECURITY LAB MANUAL

Mr. P.JAGADEESHWAR
Assistant Professor,
CSE Department.

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

INDEX

S.No. Topic Page No.

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
1 displays the result. 3

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
2 with 127 and display the result. 4

Write a Java program to perform encryption and decryption using the


following algorithms:
a) Ceaser Cipher 5-11
b) Substitution Cipher
c) Hill Cipher
4 Write a C/Java program to implement the DES algorithm logic 12-14

5 Write a C/JAVA program to implement the BlowFish algorithm logic 15-16

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

Write the RC4 logic in Java Using Java Cryptography, encrypt the text
7 “Hello world” using BlowFish. Create your own key using Java keytool. 19-20

8 Write a Java program to implement RSA Algorithm. 21-22

Implement the Diffie-Hellman Key Exchange mechanism using HTML


and JavaScript. Consider the end user as one of the parties (Alice) and the
9 JavaScript application as other party (bob). 23-24

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

11 Calculate the message digest of a text using the SHA-1 algorithm in JAVA. 27-28
1. XOR a string with a Zero

AIM: Write a C program that contains a string (char pointer) with a value \HelloWorld’.
The program should XOR each character in this string with 0 and displays the result.

Algorithm:

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

1. In XOR operation that it will return true if one, and only one, of the two operators.
If two operators is true and two operators is false the result is false.
2. Read the string Hello World.
3. In String each character XOR with value ‘0’.
4. Display the results.

PROGRAM:

#include<stdlib.h>
main()
{
char str[]="Hello World";
char str1[11];
int i,len;
len=strlen(str);

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
for(i=0;i<len;i++)
{
str1[i]=str[i]^0;
printf("%c",str1[i]);
}
printf("\n");
}

Output:
Hello World

2. XOR a string with a 127


AIM: Write a C program that contains a string (char pointer) with a value \HelloWorld’.
The program should AND, OR and XOR each character in this string with 127 and display
the result.

Algorithm:

1. In XOR operation that it will return true if one, and only one, of the two operators.
If two operators is true and two operators is false then the result is false.

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

2. Read the string Hello World.


3. In String each character performs AND operation with value ‘127’ store in string1.
4. In String each character performs OR operation with value ‘127’ store in string2.
5. In String each character performs XOR operation with value ‘127’ store in string3.
6. Display the results.

PROGRAM:
#include <stdio.h>

#include<stdlib.h>
void main()
{
char str[]="Hello World";

char str1[11];
char str2[11];
char str3[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] = str[i]|127;

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
printf("%c",str2[i]);
}
printf("\n");
for(i=0;i<len;i++)
{
str3[i] = str[i]^127;
printf("%c",str3[i]);
}

Output:
Hello World

7 _(

3. Encryption & Decryption using Cipher Algorithms

AIM: Write a Java program to perform encryption and decryption using thefollowing
algorithms:
a) Ceaser Cipher
b) Substitution Cipher
c) Hill Cipher

Ceaser Cipher

Algorithm:
1. The method is named after Julius Caesar cipher.
2. The transformation can be represented by aligning two alphabets.
3. The cipher alphabet is the plain alphabet rotated left or right by some number of
positions.
4. The encryption can also be represented using modular arithmetic by first transforming
the letters into numbers according to the scheme, A=0, B=1, …..Z=25

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

5. Read the string plaintext p.


6. Read the key value k.
7. Check the string either capital or small letters.
8. Perform encryption of a letter p by a shift k can described mathematically as E(p) =
(p+k)mod 26.
9. Perform decryption of a letter c by a shift k can described mathematically as D(c) = (c-
k)mod 26.
10. Display the results.

PROGRAM:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CeaserCipher
{
static Scanner sc=new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
// TODO code application logic here

System.out.print("Enter any String: ");


String str = br.readLine();
System.out.print("\nEnter the Key: ");
int key = sc.nextInt();
String encrypted = encrypt(str, key);
System.out.println("\nEncrypted String is: " +encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println("\nDecrypted String is: "
+decrypted); System.out.println("\n");
}
public static String encrypt(String str, int key)
{
String encrypted = "";

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
for(int i = 0; i < str.length(); i++)
{
int c = str.charAt(i);
if (Character.isUpperCase(c))
{c = c + (key % 26);
if (c >'Z')
c = c - 26;
}
else if (Character.isLowerCase(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<str.length();i++)
{ int c = str.charAt(i);
if(Character.isUpperCase(c))
{ c = c - (key %
26);
if (c <'A')
c = c + 26;
}
else
if (Character.isLowerCase(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

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
Encrypted String is: MjqqtBtwqi
Decrypted String is: Hello World

b) Substitution Cipher

Algorithm:
1. Take the string a=”abcdefghijklmnopqrstuvwxyz”.
2. Take the string b=”zyxwvutsrqponmlkjihgfedcba”
3. Read any string.
4. In encryption compare the string a and string b, the corresponding position letters in
string b is encrypted data.
5. Display the results.

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

PROGRAM:

import java.io.*;
import java.util.*;
public class SubstitutionCipher {
static Scanner sc = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
TODO code application logic here
String a =abcdefghijklmnopqrstuvwxyz";
String b = "zyxwvutsrqponmlkjihgfedcba";

System.out.print("Enter any string: ");


String str = br.readLine();
String decrypt = "";
char c;
for(int i=0;i<str.length();i++)
{
c = str.charAt(i);
int j = a.indexOf(c);
decrypt = decrypt+b.charAt(j);
}
System.out.println("The encrypted data is: " +decrypt);
}
}

Output:
Enter any string: aceho
The encrypted data is: zxvsl

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

c.) Hill Cipher


Algorithm:
1. The Hill cipher is a substitution cipher invented by Lester S. Hill in 1929.

2. Each letter is represented by a number modulo 26. To encrypt a message, each block of n
letters is multiplied by an invertible n × n matrix, again modulus 26.

3. To decrypt the message, each block is multiplied by the inverse of the matrix used for
encryption. The matrix used for encryption is the cipher key, and it should be chosen
randomly from the set of invertible n × n matrices (modulo 26).

4. The cipher can, be adapted to an alphabet with any number of letters.

5. All arithmetic just needs to be done modulo the number of letters instead of modulo.

PROGRAM:
import java.io.*;
import java.util.*;
import java.io.*;

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
public class HillCipher {
static float[][] decrypt = new float[3][1];
static float[][] a = new float[3][3]; static
float[][] b = new float[3][3]; static
float[][] mes = new float[3][1]; static
float[][] res = new float[3][1];
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException {
// TODO code application logic here
getkeymes();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++)
{ res[i][j]=res[i][j]+a[i][k]*mes[k][j];
}
System.out.print("\nEncrypted string is : "); for(int
i=0;i<3;i++) {
System.out.print((char)(res[i][0]%26+97));
res[i][0]=res[i][0];
}
inverse();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++) {
decrypt[i][j] = decrypt[i][j]+b[i][k]*res[k][j]; }
System.out.print("\nDecrypted string is : ");

for(int i=0;i<3;i++){
System.out.print((char)(decrypt[i][0]%26+97));
}
System.out.print("\n");
}
public static void getkeymes() throws IOException {
System.out.println("Enter 3x3 matrix for key (It should be inversible): ");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
a[i][j] = sc.nextFloat();
System.out.print("\nEnter a 3 letter string: ");
String msg = br.readLine();
for(int i=0;i<3;i++)
mes[i][0] = msg.charAt(i)-97;
}
public static void inverse() {
floatp,q;
float[][] c = a;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
//a[i][j]=sc.nextFloat();
if(i==j)
b[i][j]=1;
else b[i][j]=0;
}
for(int k=0;k<3;k++) {
for(int i=0;i<3;i++) {
p = c[i][k];
q = c[k][k];
for(int 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(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
b[i][j] = b[i][j]/c[i][i]; }

System.out.println("");
System.out.println("\n Inverse Matrix is : ");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++)
System.out.print(b[i][j] + "");

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

System.out.print("\n"); }
}}

Output:
Enter a 3 letter string: hai
Encrypted string is :fdx
Inverse Matrix is :
0.083333336 0.41666666 -0.33333334
-0.41666666 -0.083333336 0.6666667
0.5833333 -0.083333336 -0.33333334
Decrypted string is: hai

ANOTHER PROGRAM FOR Hill Cipher


import java.util.*;
class Basic{
String allChar="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
int indexOfChar(char c)
{
for(int i=0;i < allChar.length();i++)
{
if(allChar.charAt(i)==c)
return i;
}
return -1;
}
char charAtIndex(int pos)
{
return allChar.charAt(pos);
}
}
class Hill{

Hill(int block)

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
{
this.block=block;
}

Basic b1=new Basic();


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

void keyInsert()throws Exception


{
Scanner scn=new Scanner(System.in);
System.out.println("Enter key Matrix");
for(int i=0;i < block;i++)
{
for(int j=0;j < block;j++)
{
key[i][j]=scn.nextInt();
}
}
}

void KeyInverseInsert()throws Exception


{
Scanner scn=new Scanner(System.in);
System.out.println("Enter key Inverse Matrix:");
for(int i=0;i < block;i++)
{
for(int j=0;j < block;j++)
{
key[i][j]=scn.nextInt();
}
}
}

String encryptBlock(String plain)throws Exception


{
plain=plain.toUpperCase();
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]=b1.indexOfChar(plain.charAt(i));
}

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

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+=b1.charAtIndex(cipherMatrix[i][0]);
}
return cipher;
}

String encrypt(String plainText)throws Exception


{
String cipherText="";
keyInsert();

plainText=plainText.toUpperCase();

int len=plainText.length();
// System.out.println(plainText.substring(1,2+1));

while(len%block!=0)
{
plainText+="X";
System.out.println(len);
len=plainText.length();
}

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


{
cipherText+=encryptBlock(plainText.substring(i,i+block));
cipherText+="";
}
return cipherText;

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
}

String decryptBlock(String cipher)throws Exception


{
cipher=cipher.toUpperCase();
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]=b1.indexOfChar(cipher.charAt(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+=b1.charAtIndex(plainMatrix[i][0]);
}
return plain;
}

String Decrypt(String cipherText)throws Exception


{
String plainText="";
KeyInverseInsert();
cipherText=cipherText.replaceAll("", "");

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
cipherText=cipherText.toUpperCase();

int len=cipherText.length();

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


{
plainText+=decryptBlock(cipherText.substring(i,i+block));
plainText+="";
}
return plainText;
}
}

class HillCipher1{
public static void main(String args[])throws Exception
{
String plainText,cipherText;
int block;
Scanner scn=new Scanner(System.in);

System.out.println("Enter plain-text:");
plainText=scn.nextLine();

System.out.println("Enter block size of matrix:");


block=scn.nextInt();
Hill hill=new Hill(block);

plainText=plainText.replaceAll("", "");
cipherText= hill.encrypt(plainText);

System.out.println("Encrypted Text is:\n"+cipherText);

String decryptedText= hill.Decrypt(cipherText);


System.out.println("Decrypted Text is:\n"+decryptedText);

}
}
/*OUTPUT
Enter plain-text:
meet
Enter block size of matrix:
2
Enter key Matrix
31
52
Encrypted Text is:

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
OQ FG
Enter key Inverse Matrix:
2 -1
-5 3
Decrypted Text is:
ME ET */

4. IMPLEMENTATION OF DES

AIM: Write a Java program to implement the DES algorithm logic.

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

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
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:

import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random ;
class DES {
byte[] skey = new byte[1000];
String skeyString;
static byte[] raw;
String inputMessage,encryptedData,decryptedMessage;
public DES()
{
try

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
{
generateSymmetricKey();
inputMessage=JOptionPane.showInputDialog(null,"Enter message to encrypt");
byte[] ibyte = inputMessage.getBytes();
byte[] ebyte=encrypt(raw, ibyte);
String encryptedData = new String(ebyte);
System.out.println("Encrypted message "+encryptedData);
JOptionPane.showMessageDialog(null,"Encrypted Data "+"\n"+encryptedData);
byte[] dbyte= decrypt(raw,ebyte);
String decryptedMessage = new String(dbyte);
System.out.println("Decrypted message "+decryptedMessage);
JOptionPane.showMessageDialog(null,"Decrypted Data "+"\n"+decryptedMessage);
}
catch(Exception e)
{
System.out.println(e);
}}
void generateSymmetricKey() {
try {
Random r = new Random();
int num = r.nextInt(10000);
String knum = String.valueOf(num);
byte[] knumb = knum.getBytes();
skey=getRawKey(knumb);
skeyString = new String(skey);
System.out.println("DES Symmetric key = "+skeyString);
}
catch(Exception e)
{
System.out.println(e);
}
}
private static byte[] getRawKey(byte[] seed) throws Exception
{
KeyGenerator kgen = KeyGenerator.getInstance("DES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(56, sr);
SecretKey skey = kgen.generateKey();
raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw,"DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
byte[] encrypted = cipher.doFinal(clear);
return encrypted; }
private static byte[] decrypt(byte[] raw, byte[] encrypted)
throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(raw,
"DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static void main(String args[])
{
DES des = new DES();
}}

Output

jiet@jiet-Veriton-Series:~/Desktop/j$ javac DES.java


jiet@jiet-Veriton-Series:~/Desktop/j$ java DES
DES Symmetric key = ��#�vk)
Encrypted message #�6�D�џ
Decrypted message hello
jiet@jiet-Veriton-Series:~/Desktop/j$ java DES
DES Symmetric key = ���h�%�
?~�#*'��}#!2�-(h��~��?Nh�´Z�Ur�
Decrypted message jagruti Institute of Engineering & technology

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

5. Program to implement BlowFish algorithm logic


AIM: Write a C/JAVA program to implement the BlowFish algorithm logic.
Step1 : Divide X i.e. plaintext into two 32 bits values and treat the left half 32 bits as XL
&
Right half 32 bits as XR.
Step 2: for i=1 to16;
XL=XL XOR Pi
XR=F(XL) XOR XR
SWAP XL and XR
do this process for 15 rounds
swap XL & XR (in 16th round i.e. undo the last swap i.e. don’t do swapping of XL
and XR )

Last steps after the above steps:

The 16th round XL value is XOR ed with P18 value, XR value is XOR ed with P17

XR=XR XOR P17


XL=XL XOR P18
Cipher text=Concatenation of XL & XR
Explanation in detail:
 We need plain text &key in order to encrypt
 In Blowfish algorithm
 we use 18 keys
 Plain text=64 bits

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Encoder;
public class Blowfish {
public static void main(String[] args) throws Exception {
// TODO code application logic here
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
Key secretKey = keyGenerator.generateKey();
Cipher cipherOut = Cipher.getInstance("Blowfish/CFB/NoPadding");
cipherOut.init(Cipher.ENCRYPT_MODE, secretKey);
BASE64Encoder encoder = new BASE64Encoder();
byte iv[] = cipherOut.getIV(); if (iv != null)
{
System.out.println("Initialization Vector of the Cipher: " + encoder.encode(iv));
}
FileInputStream fin = new FileInputStream("inputFile.txt");
FileOutputStream fout = new FileOutputStream("outputFile.txt");
CipherOutputStream cout = new CipherOutputStream(fout, cipherOut);
int input = 0;
while ((input = fin.read()) != -1)
{
cout.write(input);
}
fin.close();
cout.close();
}
}

OUTPUT:
Initialization Vector of the Cipher: dI1MXzW97oQ=
Contents of inputFile.txt: Hello World
Contents of outputFile.txt: ùJÖ˜ NåI“

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

6. Program to implement Rijndael algorithm logic


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

Algorithim
AES is based on a design principle known as a substitution–permutation network, and is efficient in both software and
hardware.[9] Unlike its predecessor DES, AES does not use a Feistel network. AES is a variant of Rijndael which has a
fixed block size of 128 bits, and a key size of 128, 192, or 256 bits. By contrast, Rijndael per se is specified with block
and key sizes that may be any multiple of 32 bits, with a minimum of 128 and a maximum of 256 bits.
AES operates on a 4 × 4 column-major order array of bytes, termed the state.[note 3] Most AES calculations are done in a
particular finite field.

For instance, if there are 16 bytes, , these bytes are represented as this two-dimensional array:

The key size used for an AES cipher specifies the number of transformation rounds that convert the input, called
the plaintext, into the final output, called the ciphertext. The number of rounds are as follows:

 10 rounds for 128-bit keys.


 12 rounds for 192-bit keys.
 14 rounds for 256-bit keys.
Each round consists of several processing steps, including one that depends on the encryption key itself. A set of
reverse rounds are applied to transform ciphertext back into the original plaintext using the same encryption key.

High-level description of the algorithm[edit]


1. KeyExpansion—round keys are derived from the cipher key using Rijndael's key schedule. AES requires
a separate 128-bit round key block for each round plus one more.
2. Initial round key addition:
1. AddRoundKey—each byte of the state is combined with a block of the round key using bitwise
xor.
3. 9, 11 or 13 rounds:
1. SubBytes—a non-linear substitution step where each byte is replaced with another according to
a lookup table.
2. ShiftRows—a transposition step where the last three rows of the state are shifted cyclically a
certain number of steps.
3. MixColumns—a linear mixing operation which operates on the columns of the state, combining
the four bytes in each column.
4. AddRoundKey
4. Final round (making 10, 12 or 14 rounds in total):
1. SubBytes
2. ShiftRows
3. AddRoundKey

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

PROGRAM:

import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class AES {
public static String asHex (byte buf[]) { StringBuffer
strbuf = new StringBuffer(buf.length * 2); int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); }
return strbuf.toString(); }

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
public static void main(String[] args) throws Exception
{ String message="Hello JIET";
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal((args.length == 0 ? message :

args[0]).getBytes()); System.out.println("encrypted string: " +


asHex(encrypted)); cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] original = cipher.doFinal(encrypted); String originalString = new
String(original);
System.out.println("Original string: " + originalString + "" + asHex(original));
}}
OUTPUT:
Input your message: Hello JIET
Encrypted text: 3ooo&&(*&*4r4 Decrypted text: Hello JIET

7. a) Write the RC4 logic in Java.


RC4 algorithm
A 256-byte state vector is used to hold the permutation of all 8-bit numbers (0 to 255). The vector is
initialized to a permutation based on the key which can be 1 to 255 bytes wide. To calculate this
initial permutation we use a temporary vector named “T”. T is also 256 bytes wide and contains a

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
repeated sequence of key bytes. for example if key is “1234” then T would be “123412341234…..”.
The key and also T are only used for the initialization phase and the encryption/decryption process
is only based on S. This process includes XORing a value selected from S with the next byte of
input; generating the next cipher/plain byte. As you notice, the process generates output, by reading
one byte at a time, calculating one byte as the result. This is why we call these algorithms stream
oriented as opposed to block cipher algorithms which work on blocks of data not single bytes.
The initial permutation is done using pseudo algorithm below:
for i = 0 to 255
S[i] = i;
T[i] = Key[i mode KeyLength]

temp = 0
for i = 0 to 255
temp = (temp + S[i] + T[i]) mod 256
swap(S[i],S[temp])

After that we need neither T nor Key. Stream generation is done using this pseudo
algorithm:
i=0
j=0
while (true)
i = (i + 1) mod 256
j = (j + S[i]) mod 256
swap(S[i],S[j])
t = (S[i] + S[j]) mod 256
val = S[t]

val is the output on each iteration and it is XORed against the input byte to produce the
next output byte. So to encrypt, the next input byte which is considered plain data is
XORed with val to produce the next cipher byte and to decrypt, the next input byte is
XORed with val to produce the next plain byte. (If number A is XORed with number B
twice, the result is A, i.e (A xor B) xor B = A)

To be able to produce the plain data from the encrypted data you need to know with
what values the encrypted bytes should be XORed. Having the correct key generates
those values so provides the algorithm with correct series of S permutations and correct
sequence of bytes to XOR with input hence making it possible to reproduce the plain
data. You can see stream generation involves a swap operation with generating each
new byte and also the selected value (the val at the last line) does not depend on the
input byte. That means a same input byte (consider character ‘A’ exists in different
location of plain data to be encrypted) is XORed with different value each time. This is
different than the example encryption scenario which we introduced at the beginning of
the article which used a static mapping between plain and cipher text making the
cryptanalysis attacks possible.

In the following RC4 is implemented as a demo program which generates a random key
using Linux’s “/dev/urandom” (so can be run on Linux only) at the beginning of
execution and then encrypts a message using the proposed RC4 algorithm with that key,
shows the encrypted message in HEX format then decrypts the data with the same key
producing the original plain message. The algorithm surely is not limited to ASCII data.
The input can be anything but for the purpose of demonstration I used a an English

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
phrase as input in this program. By a little modification you can encrypt any file using
this same code. You can see a sample output of running the program below:
Generated sample key: AJAOAALGAA
> Secret text: Find the treasure 3 meters away from that tall tree where the kid passes
by!
> Encryted message:
17144C9CC8C66D4AEEFFADABEEB7342E352C6E47BB320DF3BFF596D8C69AFF73
1760B9B8289660A9766A63762276636E6E227670676722756A67706722766A6722696
B662272637171677122607B23
> Decryted RC4 data with the same key: Find the treasure at 3 meters away from that
tall tree where the kid passes by!

The steps for RC4 encryption algorithm are as follows


1)Get the data to be encrypted and the selected key.
2)Create two string arrays.
3)Initiate one array with numbers from 0 to 255.
4)Fill the other array with the selected key.
5)Randomize the first array depending on the array of the key.
6)Randomize the first array within itself to generate the final key stream.
7)XOR the final key stream with the data to be encrypted to give cipher text.

Java Program for RC4:


import java.io.*;
public class RC4
{
public static void main(String args[])throws IOException

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
{
int temp=0;
String ptext;
String key;
int s[]=new int[256];
int k[]=new int[256];
DataInputStream in=new DataInputStream(System.in);
System.out.println("ENTER PLAIN TEXT");
ptext=in.readLine();
System.out.println("ENTER KEY TEXT");
key=in.readLine();
char ptextc[]=ptext.toCharArray();
char keyc[]=key.toCharArray();
int cipher[]=new int[ptext.length()];
int decrypt[]=new int[ptext.length()];
int ptexti[]=new int[ptext.length()];
int keyi[]=new int[key.length()];
for(int i=0;i<ptext.length();i++)
{
ptexti[i]=(int)ptextc[i];
}
for(int i=0;i<key.length();i++)
{
keyi[i]=(int)keyc[i];
}
for(int i=0;i<255;i++)
{
s[i]=i;
k[i]=keyi[i%key.length()];
}
int j=0;
for(int i=0;i<255;i++)
{
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<ptext.length();l++)
{
i=(l+1)%256;
j=(j+s[i])%256;
temp=s[i];
s[i]=s[j];
s[j]=temp;
z=s[(s[i]+s[j])%256];
cipher[l]=z^ptexti[l];
decrypt[l]=z^cipher[l];
}

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
System.out.println("ENCRYPTED");
display(cipher);
System.out.println("DECRYPTED");
display(decrypt);
}
static void display(int disp[])
{
char convert[]=new char[disp.length];
for(int l=0;l<disp.length;l++)
{
convert[l]=(char)disp[l];
System.out.println(convert[l]);
}
}
} OUTPUT:
ENTER PLAIN TEXT hello
ENTER KEY TEXT a
ENCRYPTED: x??r-
DECRYPTED: hello

7 b). Using Java Cryptography, encrypt the text “Hello world” using BlowFish.
PROGRAM:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.JOptionPane;

/**
* This program demonstrates how to encrypt/decrypt input
* using the Blowfish Cipher with the Java Cryptograhpy.
*
*/
public class BlowFishCipher {

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

// create a key generator based upon the Blowfish cipher


KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");

// create a key
SecretKey secretkey = keygenerator.generateKey();

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

// create a cipher based upon Blowfish


Cipher cipher = Cipher.getInstance("Blowfish");

// initialise cipher to with secret key


cipher.init(Cipher.ENCRYPT_MODE, secretkey);

// get the text to encrypt


String inputText = JOptionPane.showInputDialog("Input your message: ");

// encrypt message
byte[] encrypted = cipher.doFinal(inputText.getBytes());

// re-initialise the cipher to be in decrypt mode


cipher.init(Cipher.DECRYPT_MODE, secretkey);

// decrypt message
byte[] decrypted = cipher.doFinal(encrypted);

// and display the results


JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
"encrypted text: " + new String(encrypted) + "\n" +
"decrypted text: " + new String(decrypted)); // end example
System.exit(0); }} }
OUTPUT:
Input your message: Hello world Encrypted text: 3ooo&&(*&*4r4 Decrypted text: Hello world

7 c) Create your own key using Java key tool.


AIM:
Demonstrate how to provide secure data storage, secure data transmission and for
creating digital signatures (GnuPG).
INTRODUCTION:
Here’s the final guide in my PGP basics series, this time focusing on Windows
The OS in question will be Windows 7, but it should work for Win8 and Win8.1 as
Well Obviously it’s not recommended to be using Windows to access the DNM, but I
won’t go into the reasons here.
The tool well be using is GPG4Win
INSTALLING THE SOFTWARE
1. Visit www.gpg4win.org Click on the “Gpg4win 2.3.0” button

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

2. On the following screen, click the “Download Gpg4win” button.

3. When the “Welcome” screen is displayed, click the “Next” button

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
8. Write a Java program to implement RSA Algoithm.

ALGORITHM:
STEP-1: Select two co-prime numbers as p and q.
STEP-2: Compute n as the product of p and q.
STEP-3: Compute (p-1)*(q-1) and store it in z.
STEP-4: Select a random prime number e that is less than that of z.
STEP-5: Compute the private key, d as e * mod-1(z).
STEP-6: The cipher text is computed as messagee * mod n.
STEP-7: Decryption is done as cipherdmod n.

Java PROGRAM:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.Random;
import java.util.Scanner;

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
public class RSA {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// TODO code application logic here
System.out.print("Enter a Prime number: ");
BigInteger p = sc.nextBigInteger(); // Here's one prime number..
System.out.print("Enter another prime number: ");
BigInteger q = sc.nextBigInteger(); // ..and another.
BigInteger n = p.multiply(q);
BigInteger n2 = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
BigInteger e = generateE(n2);
BigInteger d = e.modInverse(n2); // Here's the multiplicative inverse
System.out.println("Encryption keys are: " + e + ", " + n);
System.out.println("Decryption keys are: " + d + ", " + n);
}
public static BigInteger generateE(BigInteger fiofn)
{
int y, intGCD;
BigInteger e;
BigInteger gcd;
Random x = new Random();
do {
y = x.nextInt(fiofn.intValue()-1);
String z = Integer.toString(y);
e = new BigInteger(z);
gcd = fiofn.gcd(e);
intGCD = gcd.intValue();
}
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

9. Diffie-Hellman
AIM: Implement the Diffie-Hellman Key Exchange mechanism using HTML
andJavaScript. Consider the end user as one of the parties (Alice) and the JavaScript
application as other party (bob).

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

ALGORITHM:
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.

PROGRAM:
import java.io.*;
import java.math.BigInteger;
class Diffie
{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter prime number:");
BigInteger p=new BigInteger(br.readLine());
System.out.print("Enter primitive root of "+p+":");
BigInteger g=new BigInteger(br.readLine());
System.out.println("Enter value for x less than "+p+":");
BigInteger x=new BigInteger(br.readLine());
BigInteger R1=g.modPow(x,p);
System.out.println("R1="+R1);
System.out.print("Enter value for y less than "+p+":");
BigInteger y=new BigInteger(br.readLine());
BigInteger R2=g.modPow(y,p);
System.out.println("R2="+R2);
BigInteger k1=R2.modPow(x,p);
System.out.println("Key calculated at Alice's side:"+k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Bob's side:"+k2);
System.out.println("deffie hellman secret key Encryption has Taken");
}
}

OUTPUT
Enter prime number:
11
Enter primitive root of 11:7
Enter value for x less than 11:
3
R1=2
Enter value for y less than 11:6
R2=4
Key calculated at Alice's side:9
Key calculated at Bob's side:9

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
deffie hellman secret key Encryption has Taken

//Another Program
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator; import
java.security.SecureRandom;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;
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(Integer.toString(pValue));
BigInteger g = new BigInteger(Integer.toString(gValue));
BigInteger Xa = new
BigInteger(Integer.toString(XaValue));
BigIntegerXb =new BigInteger(Integer.toString(XbValue));
createKey();
intbitLength = 512; // 512 bits
SecureRandom rnd = new SecureRandom();
p = BigInteger.probablePrime(bitLength, rnd);
g = BigInteger.probablePrime(bitLength, rnd);
createSpecificKey(p, g);
}
public static void createKey() throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();
KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),
DHPublicKeySpec.class);
System.out.println("Public key is: " +kspec);

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

}
public static void createSpecificKey(BigInteger p, BigInteger g) throws Exception
{
KeyPairGeneratorkpg =KeyPairGenerator.getInstance("DiffieHellman");
DHParameterSpecparam = new DHParameterSpec(p, g);
kpg.initialize(param);
KeyPair kp = kpg.generateKeyPair();
KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),
DHPublicKeySpec.class);
System.out.println("\nPublic key is : " +kspec);
}
}
OUTPUT:
Public key is: javax.crypto.spec.DHPublicKeySpec@5afd29
Public key is: javax.crypto.spec.DHPublicKeySpec@9971ad

10. SHA-1

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

ALGORITHM:
STEP-1: Read the 256-bit key values.
STEP-2: Divide into five equal-sized blocks named A, B, C, D and E.
STEP-3: The blocks B, C and D are passed to the function F.
STEP-4: The resultant value is permuted with block E.
STEP-5: The block A is shifted right by ‘s’ times and permuted with the result
of step-4.
STEP-6: Then it is permuted with a weight value and then with some other
key pair and
taken as the first block.
STEP-7: Block A is taken as the second block and the block B is shifted by ‘s’
times and
taken as the third block.

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
STEP-8: The blocks C and D are taken as the block D and E for the final
output.

PROGRAM:
import java.security.*;
public class SHA1 {
public static void main(String[] a) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " +md.getAlgorithm());
System.out.println(" Provider = " +md.getProvider());
System.out.println(" ToString = " +md.toString());

String input = "";


md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\") = " +bytesToHex(output));

input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\") = " +bytesToHex(output));

input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\"" +input+"\") = " +bytesToHex(output));
System.out.println(""); }
catch (Exception e) {

System.out.println("Exception: " +e);


}
}

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

public static String bytesToHex(byte[] b) {


char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuffer buf = new StringBuffer();
for (int j=0; j<b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]); }
return buf.toString(); }
}
OUTPUT:
Message digest object info:
Algorithm = SHA1
Provider = SUN version 1.6
ToString = SHA1 Message Digest from SUN, <initialized> SHA1("") =
DA39A3EE5E6B4B0D3255BFEF95601890AFD80709 SHA1("abc") =
A9993E364706816ABA3E25717850C26C9CD0D89D
SHA1("abcdefghijklmnopqrstuvwxyz")=32D10C7B8CF96570CA04CE37F2A19D8424
0D3A89

11. Message Digest Algorithm5 (MD5)


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

ALGORITHM:
STEP-1: Read the 128-bit plain text.
STEP-2: Divide into four blocks of 32-bits named as A, B, C and D.
STEP-3: Compute the functions f, g, h and i with operations such as,
rotations,
permutations, etc,.
STEP-4: The output of these functions are combined together as F and
performed
circular shifting and then given to key round.
STEP-5: Finally, right shift of ‘s’ times are performed and the results are
combined
together to produce the final output.

PROGRAM:
import java.security.*;

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE
public class MD5 {
public static void main(String[] a) {
// TODO code application logic here
try {
MessageDigest md = MessageDigest.getInstance("MD5");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " +md.getAlgorithm());
System.out.println(" Provider = " +md.getProvider());
System.out.println(" ToString = " +md.toString());

String input = "";


md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));

input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));

input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\"" +input+"\") = "+bytesToHex(output));
System.out.println("");
}
catch (Exception e) {
System.out.println("Exception: " +e);
}
}
public static String bytesToHex(byte[] b)
{
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuffer buf = new StringBuffer();
for (int j=0; j<b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]); }

Page
CRYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

return buf.toString(); } }

OUTPUT:
Message digest object info:
Algorithm = MD5
Provider = SUN version 1.6
ToString = MD5 Message Digest from SUN, <initialized> MD5("") =
D41D8CD98F00B204E9800998ECF8427E MD5("abc") =
900150983CD24FB0D6963F7D28E17F72 MD5("abcdefghijklmnopqrstuvwxyz") =
C3FCD3D76192E4007DFB496CCA67E13B

Page
RYPTOGRAPHY & NETWORK SECURITY LAB JIET III B.Tech.
II Sem. CSE

Page

You might also like