0% found this document useful (0 votes)
25 views

IT6712 Security Lab Record

The document describes a program to encrypt and decrypt text using the Playfair cipher substitution technique. It explains the procedures for encryption and decryption which involve setting up a 5x5 matrix with keys, separating the plaintext into letter pairs, and substituting the letters according to their positions in the matrix. The program code provided implements these encryption and decryption algorithms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

IT6712 Security Lab Record

The document describes a program to encrypt and decrypt text using the Playfair cipher substitution technique. It explains the procedures for encryption and decryption which involve setting up a 5x5 matrix with keys, separating the plaintext into letter pairs, and substituting the letters according to their positions in the matrix. The program code provided implements these encryption and decryption algorithms.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 52

EX.

NO:1A IMPLEMENT THE FOLLOWING


DATE: SUBSTITUTION & TRANSPOSITION TECHNIQUES

A.Ceasar Cipher
Aim:
To write a program for encrypting a plain text and decrypting a cipher text using Caesar
Cipher (shift cipher) using substitution technique

Procedure for Encryption:


Step 1 :Read ‘Key’ value to shift.
Step 2 :Read the Plaintext to encryption
Step 3 :Initialize Cipher Text with empty string.
Step 4 :Convert each character into Upper text.
Step 5 :Read each character ‘current’ in a PlainText.
a) Find ASCII value of current character and add key with that.
b) Find, SumASCII(current)+key
c) Subtract 65 from sum, Sum Sum – 65
d) Do modulo division with 26, Sum Sum MOD 26
e) Compute encrypted char by adding 65, Encrypted65+ Sum
f) Add Encrypted character to CipherText.
Step 6 :Repeat step 5 until all characters encrypted.

Procedure for Decryption:


Step 1 :Read ‘Key’ value to shift.

Step 2:Read the CipherText to Decrypt.

Step 3:Initialize PlainText with empty string.

Step 4:Convert each character into Upper text.

Step 5:Read each character ‘current’ in a CipherText.

a) Find ASCII value of current character and subtract key with that.
b) Find, SumASCII(current) MOD 65.
c) Subtract key from sum, Diff Sum – key
d) If Diff is less than zero, Diff26-Diff
e) Compute Decrypted character by adding 65, Decrypted65+ Diff
f) Add Decrypted character to PlainText.
Step 6:Repeat step 5 until all characters Decrypted
Program:

import java.util.Scanner;

public class CaesarCipher

public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

public static String encrypt(String plainText, int shiftKey)

plainText = plainText.toLowerCase();

String cipherText = "";

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

int charPosition = ALPHABET.indexOf(plainText.charAt(i));

int keyVal = (shiftKey - charPosition) % 26;

char replaceVal = ALPHABET.charAt(keyVal);

cipherText += replaceVal;

return cipherText;

public static String decrypt(String cipherText, int shiftKey)

cipherText = cipherText.toLowerCase();

String plainText = "";

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

int charPosition = ALPHABET.indexOf(cipherText.charAt(i));


int keyVal = (charPosition +shiftKey) % 26;

if (keyVal < 0)

keyVal = ALPHABET.length() + keyVal;

char replaceVal = ALPHABET.charAt(keyVal);

plainText += replaceVal;

return plainText;

public static void main(String[] args)

Scanner sc = new Scanner(System.in);

System.out.println("Enter the String for Encryption: ");

String message = new String();

message = sc.next();

System.out.println(encrypt(message, 25));

System.out.println(decrypt(encrypt(message, 25), 25));

sc.close();

}
Output:

C:\Program Files\Java\jdk1.6.0_20\bin>java CaesarCipher13

Enter the String for Encryption:

Plain Text: the quick brown fox jumps over the lazy dog

Cipher Text: QEBNRFZHYOLTKCLUGRJMPLSBOQEBIXWVALD

Plain Text: the quick brown fox jumps over the lazy dog

Result:

Thus the program for encrypting a plain text and decrypting a cipher text using Caesar
Cipher substitution technique is executed successfully.
EX.NO:1B Play Fair Cipher
DATE:
Aim:

To write a program to encrypt a plain text and decrypt a cipher text using play fair Cipher
substitution technique

Procedure for encryption:

Step 1: Read the key.


Step 2 : Read the Plaintext.
Step 3 : Initialize the PlayFair table array as 5x5 two dimensional array.
Step 4: Add each character of the key in the array without duplicates.
Step 5 :Add alphabets from A,B..Z in the remaining array positions without duplicates.
Step 6: Read First two characters from the Plaintext and find their locations (R1, C1), (R2, C2) in
array.

a. If R1=R2, then the characters at the position (R1, (C1+1%5)) and (R2,(C2+1%5))
are the equivalent Cipher Text.
b. Otherwise, the characters at location (R1, C2) and (R2, C1) are the equivalent
Cipher Text.

Repeat step 6 until all characters converted into Cipher Text.

Procedure for Decryption:

Step 1:Read the key.


Step 2: Read the Cipher Text.
Step 3 :Initialize the PlayFair table array as 5x5 two dimensional array.
Step 4 :Add each character of the key in the array without duplicates.
Step 5 :Add alphabets from A, B...Z in the remaining array positions without duplicates.
Step 6 :Read First two characters from the Cipher Text and find their locations (R1, C1), (R2,
C2) in array.

a. If R1=R2, then the characters at the position (R1, (C1-1%5)) and (R2, (C2-1%5))
are the equivalent Plaintext.
b. Otherwise, the characters at location (R1, C2) and (R2, C1) are the equivalent
Cipher Text.

Repeat step 6 until all characters converted into Plaintext.

Program:

import java.util.*;

class Basic{
String allChar="ABCDEFGHIJKLMNOPQRSTUVWXYZ";

boolean indexOfChar(char c)

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

if(allChar.charAt(i)==c)

return true;

return false;

class PlayFair{

Basic b=new Basic();

char keyMatrix[][]=new char[5][5];

boolean repeat(char c)

if(!b.indexOfChar(c))

return true;

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

for(int j=0;j < keyMatrix[i].length;j++)

{
if(keyMatrix[i][j]==c || c=='J'

return true;

return false;

void insertKey(String key)

key=key.toUpperCase();

key=key.replaceAll("J", "I");

key=key.replaceAll(" ", "");

int a=0,b=0;

for(int k=0;k < key.length();k++)

if(!repeat(key.charAt(k)))

keyMatrix[a][b++]=key.charAt(k);

if(b>4)

b=0;

a++;

}
char p='A';

while(a < 5)

while(b < 5)

if(!repeat(p))

keyMatrix[a][b++]=p;

p++;

b=0;

a++;

System.out.print("-------------------------Key Matrix-------------------");

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

System.out.println();

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

System.out.print("\t"+keyMatrix[i][j]);

System.out.println("\n---------------------------------------------------------");
}

int rowPos(char c)

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

for(int j=0;j < keyMatrix[i].length;j++)

if(keyMatrix[i][j]==c)

return i;

return -1;

int columnPos(char c)

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

for(int j=0;j < keyMatrix[i].length;j++)

if(keyMatrix[i][j]==c)

return j;

return -1;

}
String encryptChar(String plain)

plain=plain.toUpperCase();

char a=plain.charAt(0),b=plain.charAt(1);

String cipherChar="";

int r1,c1,r2,c2;

r1=rowPos(a);

c1=columnPos(a);

r2=rowPos(b);

c2=columnPos(b);

if(c1==c2)

++r1;

++r2;

if(r1>4)

r1=0;

if(r2>4)

r2=0;

cipherChar+=keyMatrix[r1][c2];

cipherChar+=keyMatrix[r2][c1];

else if(r1==r2)

++c1;

++c2;
if(c1>4)

c1=0;

if(c2>4)

c2=0;

cipherChar+=keyMatrix[r1][c1];

cipherChar+=keyMatrix[r2][c2];

else{

cipherChar+=keyMatrix[r1][c2];

cipherChar+=keyMatrix[r2][c1];

return cipherChar;

String Encrypt(String plainText,String key)

insertKey(key);

String cipherText="";

plainText=plainText.replaceAll("j", "i");

plainText=plainText.replaceAll(" ", "");

plainText=plainText.toUpperCase();

int len=plainText.length();

// System.out.println(plainText.substring(1,2+1));

if(len/2!=0)

plainText+="X";
++len;

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

cipherText+=encryptChar(plainText.substring(i,i+2));

cipherText+=" ";

return cipherText;

String decryptChar(String cipher)

cipher=cipher.toUpperCase();

char a=cipher.charAt(0),b=cipher.charAt(1);

String plainChar="";

int r1,c1,r2,c2;

r1=rowPos(a);

c1=columnPos(a);

r2=rowPos(b);

c2=columnPos(b);

if(c1==c2)

--r1;

--r2;

if(r1 < 0)

r1=4;
if(r2 < 0)

r2=4;

plainChar+=keyMatrix[r1][c2];

plainChar+=keyMatrix[r2][c1];

else if(r1==r2)

--c1;

--c2;

if(c1 < 0)

c1=4;

if(c2 < 0)

c2=4;

plainChar+=keyMatrix[r1][c1];

plainChar+=keyMatrix[r2][c2];

else{

plainChar+=keyMatrix[r1][c2];

plainChar+=keyMatrix[r2][c1];

return plainChar;

String Decrypt(String cipherText,String key)

String plainText="";
cipherText=cipherText.replaceAll("j", "i");

cipherText=cipherText.replaceAll(" ", "");

cipherText=cipherText.toUpperCase();

int len=cipherText.length();

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

plainText+=decryptChar(cipherText.substring(i,i+2));

plainText+=" ";

return plainText;

class PlayFairCipher{

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

PlayFair p=new PlayFair();

Scanner scn=new Scanner(System.in);

String key,cipherText,plainText;

System.out.println("Enter plaintext:");

plainText=scn.nextLine();

System.out.println("Enter Key:");

key=scn.nextLine();

cipherText=p.Encrypt(plainText,key);

System.out.println("Encrypted text:");

System.out.println("---------------------------------------------------------\n"+cipherText);
System.out.println("---------------------------------------------------------");

String encryptedText=p.Decrypt(cipherText, key);

System.out.println("Decrypted text:" );

System.out.println("---------------------------------------------------------\n"+encryptedText);

System.out.println("---------------------------------------------------------");

Output:

C:\Program Files\Java\jdk1.6.0_20\bin>javac PlayFairCipher.java

C:\Program Files\Java\jdk1.6.0_20\bin>java PlayFairCipher

Enter plaintext:

TEXT

Enter Key:

-------------------------Key Matrix-------------------

A B C D E

F G H I K

L M N O P

Q R S T U

V W X Y Z

---------------------------------------------------------

Encrypted text:

---------------------------------------------------------

UD YS
---------------------------------------------------------

Decrypted text:

---------------------------------------------------------

TE XT

---------------------------------------------------------

Result:

Thus to implement a program for encrypt a plain text and decrypt a cipher text using
play fair Cipher substitution technique is executed successfully.
EX.NO:1C C. Hill Cipher
DATE:

Aim:
To write a program to encrypt and decrypt using the Hill cipher substitution technique

Procedure for Encryption:


Step 1: Read the key size ‘N’.
Step 2 :Read the Key matrix.
Step 3 :Read the Plaintext.
Step 4 :Split Plaintext into group of N characters.
Step 5 :Convert each group into column matrix. With the ASCII (character) Mod 26.
Step 6 :Multiply each group column matrix by Key matrix. Do modulo division by 26 with the
result.
Step 7 :Add 65 with each value in the resultant Matrix.
Step 8 :Add the ASCII character equivalent of the resultant matrix elements to the Cipher Text.

Repeat step 5 to 8 until all characters converted into Cipher Text.

Procedure for Decryption:


Step 1 :Read the key size ‘N’.
Step 2 :Read the Key matrix.
Step 3 :Read the CipherText.
Step 4 :Split CipherText into group of N characters.
Step 5 :Convert each group into column matrix. With the ASCII (character) Mod 26.
Step 6 :Multiply each group column matrix by inverse of Key matrix. Do modulo division by 26
with the result.
Step 7 :Add 65 with each value in the resultant Matrix.
Step 8 :Add the ASCII character equivalent of the resultant matrix elements to the Plaintext.

Repeat step 5 to 8 until all characters converted into Plaintext.

Program:

import java.io.*;

import java.util.*;

import java.io.*;

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++)

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() {

float p,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("\nInverse Matrix is : ");

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

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

System.out.print(b[i][j] + " ");

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

}}
Output:

C:\Program Files\Java\jdk1.6.0_20\bin>javac HillCipher.java


C:\Program Files\Java\jdk1.6.0_20\bin>java HillCipher

Enter 3x3 matrix for key (It should be inversible):


568
753
248

Enter a 3 letter string: cse


Encrypted string is : ume

Inverse Matrix is :
-1.75 1.0 1.375
3.125 -1.5 -2.5625
-1.125 0.5 1.0625

Decrypted string is : cse

Result:
Thus to implement a program to encrypt and decrypt using the Hill cipher substitution technique
is executed successfully.

EX.NO:1D Vigenere Cipher


DATE:

Aim:

To write a program for encryption and decryption using vigenere cipher substitution
technique

Procedure for Encryption:

Step 1:Read the Key.


Step 2:Read the PlainText.
Step 3:Initialize keyindex to 0 and CipherText to empty.
Step 4:Read each character (P) in the Plaintext, and key character(K) at position keyindex.
Step 5:Compute PVASCII(P) MOD 26 and KV ASCII(K) MOD 26
Step 6:Add PV and KV and do modulo division, SUM(PV+KV) MOD 26.
Step 7 :Add 65 with the Sum and Generate ASCII character corresponding to the resultant Sum.
The resultant character is the Cipher equivalent of current character. Add it to the CipherText.
Step 8 :Increment keyindex. If keyindex reaches LENGTH(Key), initialize eyindex-0)

Procedure for decryption:

Step 1:Read the Key.


Step 2:Read the CipherText.
Step 3Initialize keyindex to 0 and CipherText to empty.
Step 4:Read each character (C) in the Plaintext, and key character(K) at position keyindex.
Step 5:Compute CVASCII(C) MOD 26 and KV ASCII(K) MOD 26
Step 6:Compute Sum (26-KV)+CV MOD 26.
Step 7:Add 65 with the Sum and Generate ASCII character corresponding to the resultant Sum.
The resultant character is the PlainText equivalent of current character. Add it to the PlainText.
Step 8:Increment keyindex. If keyindex reaches LENGTH(Key), initialize keyindex-0)
Repeat steps from 4 to 8 until all characters encrypted.
Program:

public class VigenereCipher

public static String encrypt(String text, final String key)

String res = "";


text = text.toUpperCase();

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

char c = text.charAt(i);

if (c < 'A' || c > 'Z')

continue;

res += (char) ((c + key.charAt(j) - 2 * 'A') % 26 + 'A');

j = ++j % key.length();

return res;

public static String decrypt(String text, final String key)

String res = "";

text = text.toUpperCase();

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

char c = text.charAt(i);

if (c < 'A' || c > 'Z')

continue;

res += (char) ((c - key.charAt(j) + 26) % 26 + 'A');

j = ++j % key.length();

return res;
}

public static void main(String[] args)

String key = "VIGENERECIPHER";

String message = "Beware the Jabberwock, my son! The jaws that bite, the claws that
catch!";

String encryptedMsg = encrypt(message, key);

System.out.println("String: " + message);

System.out.println("Encrypted message: " + encryptedMsg);

System.out.println("Decrypted message: " + decrypt(encryptedMsg, key));

Output :

C:\Program Files\Java\jdk1.6.0_20\bin>javac VigenereCipher.java

C:\Program Files\Java\jdk1.6.0_20\bin>java VigenereCipher

String: beware the jabberwock, my son! the jaws that bite, the claws that catch!

Encrypted message:
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY

Decrypted message:
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH

Result:
Thus the program for encryption and decryption using vigenere cipher
substitution technique is executed successfully.

EX.NO:1E Rail Fence Cipher

DATE:

Aim:

To write a program for encryption and decryption using rail fence transposition technique

Procedurefor Encryption:

Step 1:Read the Key lines N.


Step 2:Read the PlainText.
Step 3:For each line l in N
Step 4:Calculate the offset corresponding to the line.
Step 5:Read the characters from the PlainText in the index l,l+offset*1,l+offset*2.
Step 6:Add the characters to the Ciphertext.
Step 7:Increment line by 1.Repeat steps 4 to 6 for all lines.

Procedure for Decryption:

Step 1:Read the Key lines N.


Step 2:Read the CipherText.
Step 3:For each line l in N
Step 4:Calculate the offset corresponding to the line.
Step 5:Read the characters from the CipherText in the index l,l+offset*1,l+offset*2.
Step 6:Add the characters to the PlainText.
Step 7:Increment line by 1.Repeat steps 4 to 6 for all lines.

Program:

import java.util.*;

public class RFwithColumnar {

public static void main(String[] args) {

String text = "IF YOU CAN READ THIS YOU ARE GENIUS";

String key = "HACK";

String enc = RFCEncryption(text, key);

System.out.println(enc);

}
public static String RFCEncryption(String text, String keytext) {int[] arrange =
arrangeKey(keytext);

int key = arrange.length;

int lentext = text.length();

int move = 1;

int count = 0;

String[][] rfp = new String[key][lentext];

// arrange dot fence

for (int x = 0; x < rfp.length; x++) {

for (int y = 0; y < rfp[x].length; y++) {

rfp[x][y] = ".";

// formatting according fence rails

for (int i = 0; i < lentext; i++) {

if ((move % 2) != 0) {

rfp[count][i] = "" + text.charAt(i);

if (count == (key - 1)) {

move = 2;

count = (key - 2);

} else

count++;

} else if ((move % 2) == 0) {

rfp[count][i] = "" + text.charAt(i);

if (count == 0) {
move = 1;

count = 1;

} else

count--;

//replace any white space with X or random

for (int x = 0; x < rfp.length; x++) {

for (int y = 0; y < rfp[x].length; y++) {

if (rfp[x][y].equals(" "))

rfp[x][y] = ""+Character.toUpperCase(RandomAlpha());

// display

System.out.println();

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

for (int u = 0; u < rfp[i].length; u++) {

System.out.print(rfp[i][u] + " ");

System.out.println();

System.out.println();

StringBuilder cb = new StringBuilder();

//encode string from fence

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


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

if (x == arrange[y]) {

for (int u = 0; u < lentext; u++) {

if (!".".equals(rfp[y][u])) {

cb.append(rfp[y][u]);

return "" + cb;

public static int[] arrangeKey(String key) {

//arrange position of grid

String[] keys = key.split("");

Arrays.sort(keys);

int[] num = new int[key.length()];

for (int x = 0; x < keys.length; x++) {

for (int y = 0; y < key.length(); y++) {

if (keys[x].equals(key.charAt(y) + "")) {

num[y] = x;

break;

}
System.out.println(Arrays.toString(num));

return num;

public static char RandomAlpha() {

//generate random alpha for null space

Random r = new Random();

return (char)(r.nextInt(26) + 'a');

Output:

C:\Program Files\Java\jdk1.6.0_20\bin>javac RFwithColumnar.java

C:\Program Files\Java\jdk1.6.0_20\bin>java RFwithColumnar

[3, 1, 2, 4]

I.....S.....E.....I.....L.....E....

.F...U.C...R.A...H.S...U.A...G.N...

..T.O...A.M...D.T...X.O...R.F...I.S

...Y.....N.....Q.....Y.....E.....U.

FUCRAHSUAGNTOAMDTXORFISISEILE

Result:
Thus to implement a program for encryption and decryption using rail fence transposition
technique is executed successfully.

EXNO:2A IMPLEMENT THE FOLLOWING ALGORITHMS


DATE:

A. Data Encryption Standard (DES)


Aim:
To write a program to implement Data Encryption Standard for encryption and
decryption

Algorithm:

Step 1: The 64-bit plain text block is handed over to an Initial Permutation (IP)
function.

Step 2: The Initial Permutation (IP) produces two halves of the permuted block;
say Left Plain Text (LPT) and Right Plain Text (RPT).

Step 3: Now each of LPT and RPT go through 16 rounds of encryption process.

Step 4: In the end. LPT and RPT are joined and a Final Permutation (FP) is
performed on the combined block.

Step 5: The result of this process produces 64-bit cipher text.

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
{
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);
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:

DES Symmetric Key = 1/4 << ? < ? 0`

Encrypted Message = <- ? c f 3 ! <- 0 ? ?

Decrypted Message = Hello world

Result:
Thus the program for data encryption standard to carry out the encryption and decryption
was successfully executed and verified.

EXNO:2.B B. RSA Algorithm

DATE:

Aim :

To write a program to implement RSA algorithm for encryption and decryption

Algorithm:

Step 1: Let two primes be p = 7 and q = 13. Thus, modulus n = pq = 7 x 13 = 91.

Step 1: Select e = 5, which is a valid choice since there is no number that is common
factor of 5 and (p − 1)(q − 1) = 6 × 12 = 72, except for 1.

Step 1: The pair of numbers (n, e) = (91, 5) forms the public key and can be made
available to anyone whom we wish to be able to send us encrypted messages.

Step 1: Input p = 7, q = 13, and e = 5 to the Extended Euclidean Algorithm. The output
will be d = 29.

Step 1: Check that the d calculated is correct by computing de = 29 × 5 = 145 = 1 mod 72

Step 1: Hence, public key is (91, 5) and private keys is (91, 29).

Program:

import java.io.DataInputStream;

import java.io.IOException;

import java.math.BigInteger;

import java.util.Random;

public class RSA

private BigInteger p;

private BigInteger q;
private BigInteger N;

private BigInteger phi;

private BigInteger e;

private BigInteger d;

private int bitlength = 1024;

private Random r;

public RSA()

r = new Random();

p = BigInteger.probablePrime(bitlength, r);

q = BigInteger.probablePrime(bitlength, r);

N = p.multiply(q);

phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

e = BigInteger.probablePrime(bitlength / 2, r);

while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)

e.add(BigInteger.ONE);

d = e.modInverse(phi);

public RSA(BigInteger e, BigInteger d, BigInteger N)

this.e = e;
this.d = d;

this.N = N;

@SuppressWarnings("deprecation")

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

RSA rsa = new RSA();

DataInputStream in = new DataInputStream(System.in);

String teststring;

System.out.println("Enter the plain text:");

teststring = in.readLine();

System.out.println("Encrypting String: " + teststring);

System.out.println("String in Bytes: "

+ bytesToString(teststring.getBytes()));

// encrypt

byte[] encrypted = rsa.encrypt(teststring.getBytes());

// decrypt

byte[] decrypted = rsa.decrypt(encrypted);

System.out.println("Decrypting Bytes: " + bytesToString(decrypted));

System.out.println("Decrypted String: " + new String(decrypted));

private static String bytesToString(byte[] encrypted)


{

String test = "";

for (byte b : encrypted)

test += Byte.toString(b);

return test;

// Encrypt message

public byte[] encrypt(byte[] message)

return (new BigInteger(message)).modPow(e, N).toByteArray();

// Decrypt message

public byte[] decrypt(byte[] message)

return (new BigInteger(message)).modPow(d, N).toByteArray();

}
Output:

Plain text : Hello

Encryption string : Hello

String in bytes : 104101108108111

Encrypted string in bytes :

19602-30114-23113-4629-89-98119659-41-116-24-1526-848-6614-56-128-123-7810820118-
30-5168-38100616267243-901090-26-92-95-917753-118-75-79-13-26454766-41-739-328769-
8986-1266344-84-12-81121-85-5390115-78-69-5260-55-113-76-8070-1950-109119-60117-
12511614-12399127727-1118911537438613-798-7638-43867-8864-80-23-763970645-45-897-
65-4567321-6547-987-0987654-56473647-324156-89-7645-5647-30-23451764898-5647-89-
7645-435678-345-67-567-345-34-89-7654-34567235-764-98-675432

Encrypted string in bytes: 104101108108111

Encrypted string: Hello

Result:

Thus the program for RSA Algorithm to carry out the encryption was successfully
executed and verified
EXNO: 2.C C. Diffiee Hellman Key Exchange Algorithm

DATE:

Aim:

To write a program to implement Diffie Hellman Key Exchange Algorithm for


encryption and Decryption

Algorithm:

Step 1: Global Public Elements:


Let q be a prime number and  where < q and  is a primitive root of q.
Step 2: User A Key Generation:
Select private XA where XA< q
Calculate public YA where YA = XA mod q
Step 3: User B Key Generation:
Select private XB where XB< q
Calculate public YB where YB = XB mod q
Step 4: Calculation of Secret Key by User A
K = (YB) XA mod q
Step 5: Calculation of Secret Key by User B:
K = (YA) XB mod q

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
deffie hellman secret key Encryption has Taken

Result:

Thus the program for Diffiee Hellman Key Exchange Algorithm to carry out the encryption
was successfully executed and verified .
EXNO: 2.D D. Implement Message Digest Algorithm (MD5)
DATE:

Aim:

To write a program to implement Message Digest Algorithm

Algorithm:

Step 1. Append Padding Bits:

The message is "padded" (extended) so that its length (in bits) is congruent to
448, modulo 512. That is, the message is extended so that it is just 64 bits shy of being a multiple
of 512 bits long. Padding is always performed, even if the length of the message is already
congruent to 448, modulo 512. Padding is performed as follows: a single "1" bit is appended to
the message, and then "0" bits are appended so that the length in bits of the padded message
becomes congruent to 448, modulo 512. In all, at least one bit and at most 512 bits are appended.

Step 2. Append Length:

A 64-bit representation of b (the length of the message before the padding bits
were added) is appended to the result of the previous step. In the unlikely event that b is greater
than 2^64, then only the low-order 64 bits of b are used. (These bits are appended as two 32-bit
words and appended low-order word first in accordance with the previous conventions.) At this
point the resulting message (after padding with bits and with b) has a length that is an exact
multiple of 512 bits. Equivalently, this message has a length that is an exact multiple of 16 (32-
bit) words. Let M[0 ... N-1] denote the words of the resulting message, where N is a multiple of
16.

Step 3. Initialize MD Buffer:

A four-word buffer (A,B,C,D) is used to compute the message digest. Here each
of A, B, C, D is a 32-bit register. These registers are initialized to the following values in
hexadecimal, low-order bytes first):

word A: 01 23 45 67

word B: 89 ab cd ef

word C: fe dc ba 98

word D: 76 54 32 10
Step 4. Process Message in 16-Word Blocks:

We first define four auxiliary functions that each take as input three 32-bit
words and produce as output one 32-bit word.

F(X,Y,Z) = XY v not(X) Z

G(X,Y,Z) = XZ v Y not(Z)

H(X,Y,Z) = X xor Y xor Z

Program:

import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5
{
public static String getMD5(String input)
{
Try
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String hashtext = number.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32)
{
hashtext = "0" + hashtext;
}
return hashtext;
}
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
}

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


{
System.out.println(getMD5("Javarmi.com"));
}
}
Output:

Input: welcome

Output: 6d6ede273f751292f8842f8ce08eaf0f1

Result:

Thus the program for Message Digest Algorithm (MD5) to carry out the encryption was
successfully executed and verified.
EXNO: 2.E E. Implement Secure Hash Function (SHA-1)
DATE:

Aim:

To write a program to implement Secure Hash Algorithm (SHA-1)

Algorithm:

Step 1: Append Padding Bits….

Message is “padded” with a 1 and as many 0’s as necessary to bring the


message length to 64 bits fewer than an even multiple of 512.

Step 2: Append Length....

64 bits are appended to the end of the padded message. These bits hold the
binary format of 64 bits indicating the length of the original message.

Step 3: Prepare Processing Functions….

SHA1 requires 80 processing functions defined as:

f(t;B,C,D) = (B AND C) OR ((NOT B) AND D) ( 0 <= t <= 19)

f(t;B,C,D) = B XOR C XOR D (20 <= t <= 39)

f(t;B,C,D) = (B AND C) OR (B AND D) OR (C AND D) (40 <= t <=59)

f(t;B,C,D) = B XOR C XOR D (60 <= t <= 79)

Step 4: Prepare Processing Constants....

SHA1 requires 80 processing constant words defined as:

K(t) = 0x5A827999 ( 0 <= t <= 19)

K(t) = 0x6ED9EBA1 (20 <= t <= 39)

K(t) = 0x8F1BBCDC (40 <= t <= 59)

K(t) = 0xCA62C1D6 (60 <= t <= 79)

Step 5: Initialize Buffers….


SHA1 requires 160 bits or 5 buffers of words (32 bits):

H0 = 0x67452301

H1 = 0xEFCDAB89

H2 = 0x98BADCFE

H3 = 0x10325476

H4 = 0xC3D2E1F0

Step 6: Processing Message in 512-bit blocks (L blocks in total message)….

This is the main task of SHA1 algorithm which loops through the padded and
appended message in 512-bit blocks.

Program:

import java.io.UnsupportedEncodingException;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.io.*;

public class AeSimpleSHA1

private static String convertToHex(byte[] data)

StringBuffer buf = new StringBuffer();

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

int halfbyte = (data[i] >>> 4) & 0x0F;

int two_halfs = 0;

do {
if ((0 <= halfbyte) && (halfbyte <= 9))

buf.append((char) ('0' + halfbyte));

else

buf.append((char) ('a' + (halfbyte - 10)));

halfbyte = data[i] & 0x0F;

} while(two_halfs++ < 1);

return buf.toString();

public static String SHA1(String text)

throws NoSuchAlgorithmException, UnsupportedEncodingException

MessageDigest md;

md = MessageDigest.getInstance("SHA-1");

byte[] sha1hash = new byte[40];

md.update(text.getBytes("iso-8859-1"), 0, text.length());

sha1hash = md.digest();

return convertToHex(sha1hash);

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

BufferedReader userInput = new BufferedReader (new InputStreamReader(System.in));

System.out.println("Enter string:");

String rawString = userInput.readLine();


try

System.out.println("SHA1 hash of string: " + AeSimpleSHA1.SHA1(rawString));

} catch (NoSuchAlgorithmException e) {

// TODO Auto-generated catch block

e.printStackTrace();

} catch (UnsupportedEncodingException e)

// TODO Auto-generated catch block

e.printStackTrace();

Output:

Input String: admin


MD5 Hash: 21232f297a57a5a743894a0e4a801fc3
SHA-1 Hash: d033e22ae348aeb5660fc2140aec35850c4da997
SHA-256 Hash: 8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

Result:

Thus the program for Secure Hash Function (SHA) to carry out the encryption and
decryption was successfully executed and verified.
EXNO:3 Implement the SIGNATURE SCHEME – Digital

Signature Standard
DATE:

Aim:

To write a program to implement the digital signature scheme in java

Algorithm:

Step 1 : The private key is converted from the private key file encoded in PKCS#8 format.
The public key is not needed for generating the signature file.

Step 2 : The private key is converted from the private key file encoded in PKCS#8 format. The
public key is not needed for generating the signature file.

Step 3 : The java.security.Signature.getInstance(algorithm) method is used to create the signature


object with the specified algorithm: "SHA1withDSA".

Step 4 : The initSign(privateKey) method is used at the beginning to initialize the signature object
with the private key.

Step 5 : The update() method is used repeatedly to hash the message file in chunks.

Step 6 : The sign() method is used at the end to generate the signature as a byte array from the
final hash value.

Program:

import java.security.KeyPairGenerator;

import java.security.KeyPair;

import java.security.PublicKey;

import java.security.PrivateKey;

import java.security.Signature;

import java.io.FileInputStream;

import java.util.*;
public class DigSign {

private static byte[] sign(String datafile, PrivateKey prvKey, String sigAlg) throws
Exception {

Signature sig = Signature.getInstance(sigAlg);

sig.initSign(prvKey);

FileInputStream fis = new FileInputStream(datafile);

byte[] dataBytes = new byte[1024];

int nread = fis.read(dataBytes);

while (nread > 0) {

sig.update(dataBytes, 0, nread);

nread = fis.read(dataBytes);

};

return sig.sign();

private static boolean verify(String datafile, PublicKey pubKey, String sigAlg, byte[]
sigbytes) throws Exception {

Signature sig = Signature.getInstance(sigAlg);

sig.initVerify(pubKey);

FileInputStream fis = new FileInputStream(datafile);

byte[] dataBytes = new byte[1024];

int nread = fis.read(dataBytes);


while (nread > 0) {

sig.update(dataBytes, 0, nread);

nread = fis.read(dataBytes);

};

return sig.verify(sigbytes);

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

// Generate a key-pair

Scanner u = new Scanner(System.in);

KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");

kpg.initialize(512); // 512 is the keysize.

KeyPair kp = kpg.generateKeyPair();

PublicKey pubk = kp.getPublic();

PrivateKey prvk = kp.getPrivate();

System.out.print("Enter the file name for Digital Signature : ");

String datafile = u.nextLine();

byte[] sigbytes = sign(datafile, prvk, "SHAwithDSA");

System.out.println("Signature(in hex):: " + sigbytes);

boolean result = verify(datafile, pubk, "SHAwithDSA", sigbytes);

System.out.println("Signature Verification Result = " + result);

}
}

Output:

Enter the file name for Digital Signature:jps.exe

Signature<in hex>::[B@11d50c0

Signature Verification Result=true

Result:
Thus the program for Digital Signature Scheme to carry out the encryption and
decryption was successfully executed and verified.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy