You are on page 1of 46

INDEX

Ex. No. 1.A) CAESAR CIPHER


Date:

Aim: To write a program to perform encryption and decryption using Caesar Cipher
Procedure:
1. Traverse the given text one character at a time .
2. For each character, transform the given character as per the rule, depending
on whether we’re encrypting or decrypting the text.
3. Return the new string generated.

Examples :

Text : ABCDEFGHIJKLMNOPQRSTUVWXYZ
Shift: 23
Cipher: XYZABCDEFGHIJKLMNOPQRSTUVW

Text : ATTACKATONCE
Shift: 4
Cipher: EXXEGOEXSRGI

// A C++ program to illustrate Caesar Cipher Technique


#include <iostream>
using namespace std;

// This function receives text and shift and


// returns the encrypted text
string encrypt(string text, int s)
{
string result = "";

// traverse text
for (int i=0;i<text.length();i++)
{
// apply transformation to each character
// Encrypt Uppercase letters
if (isupper(text[i]))
result += char(int(text[i]+s-65)%26 +65);

// Encrypt Lowercase letters


else
result += char(int(text[i]+s-97)%26 +97);
}

// Return the resulting string


return result;
}

// Driver program to test the above function


int main()
{
string text="ATTACKATONCE";
int s = 4;
cout << "Text : " << text;
cout << "\nShift: " << s;
cout << "\nCipher: " << encrypt(text, s);
return 0;
}

Program

public class Program


{
static String caesar(String value, int shift)
{
// Convert to char array.
char[] buffer = value.toCharArray();
// Loop over characters.
for (int i = 0; i < buffer.length; i++)
{
// Shift letter, moving back or forward 26 places if needed.
char letter = buffer[i];
letter = (char) (letter + shift); if (letter > 'z')
{
letter = (char) (letter - 26);
} else if (letter < 'a')
{
letter = (char) (letter + 26);
}
buffer[i] = letter;
}
// Return final string.
return new String(buffer);
}
public static void main(String[] args)
{
// Test the cipher method.
String a = "test";
System.out.println(a);
System.out.println();
String b = caesar(a, 18);
String c = caesar(b, -18);
System.out.println(b);
System.out.println(c);
System.out.println();
String d = caesar(a, 1);
String e = caesar(d, -1);
System.out.println(d);
System.out.println(e);
System.out.println();
String f = "exxegoexsrgi";
String g = caesar(f, -4);
System.out.println(f);
System.out.println(g);
}
}

OUTPUT
test
lwkl
test
uftu
test
exxegoexsrgi
attackatonce
Ex. No. 1.B)
JAVA PROGRAM TO ENCODE A MESSAGE USING PLAYFAIR CIPHER
Date:

Aim: To write a program to perform encryption using Playfair Cipher

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

The key is "monarchy"


Thus the initial entires are
'm', 'o', 'n', 'a', 'r', 'c', 'h', 'y'
followed by remaining characters of
a-z(except 'j') in that order.

2. Algorithm to encrypt the plain text: The plaintext is split into pairs of two letters
(digraphs). If there is an odd number of letters, a Z is added to the last letter.
For example:
PlainText: "instruments"
After Split: 'in' 'st' 'ru' 'me' 'nt' 'sz'

Rules for Encryption:

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

Plain Text: "instrumentsz"


Encrypted Text: gatlmzclrqtx
Encryption:
i -> g
n -> a
s -> t
t -> l
r -> m
u -> z
m -> c
e -> l
n -> r
t -> q
s -> t
z -> x

Program

package com.sanfoundry.setandstring;
import java.util.Scanner;
public class PlayfairCipherEncryption
{
private String KeyWord = new String();
private String Key = new String();
private char matrix_arr[][] = new char[5][5];
public void setKey(String k)
{
String K_adjust = new String();
3oolean flag = false;
K_adjust = K_adjust + k.charAt(0);
for (int i = 1; i < k.length(); i++)
{
for (int j = 0; j < K_adjust.length(); j++)
{
if (k.charAt(i) == K_adjust.charAt(j))
{
flag = true;
}
}
if (flag == false)
K_adjust = K_adjust + k.charAt(i);
flag = false;
}
KeyWord = K_adjust;
}
public void KeyGen()
{
Boolean flag = true;
char current;
Key = KeyWord;
for (int i = 0; i < 26; i++)
{
current = (char) (i + 97);
if (current == ‘j’)
continue;
for (int j = 0; j < KeyWord.length(); j++)
{
if (current == KeyWord.charAt(j))
{
flag = false;
break;
}
}
if (flag)
Key = Key + current;
flag = true;
}
System.out.println(Key);
matrix();
}
private void matrix()
{
int counter = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
matrix_arr[i][j] = Key.charAt(counter);
System.out.print(matrix_arr[i][j] + “ “);
counter++;
}
System.out.println();
}
}
private String format(String old_text)
{
int i = 0;
int len = 0;
String text = new String();
len = old_text.length();
for (int tmp = 0; tmp < len; tmp++)
{
if (old_text.charAt(tmp) == ‘j’)
{
text = text + ‘i’;
}
else
text = text + old_text.charAt(tmp);
}
len = text.length();
for (i = 0; i < len; i = i + 2)
{
if (text.charAt(i + 1) == text.charAt(i))
{
text = text.substring(0, i + 1) + ‘x’ + text.substring(i + 1);
}
}
return text;
}
private String[] Divid2Pairs(String new_string)
{
String Original = format(new_string);
int size = Original.length();
if (size % 2 != 0)
{
size++;
Original = Original + ‘x’;
}
String x[] = new String[size / 2];
int counter = 0;
for (int i = 0; i < size / 2; i++)
{
x[i] = Original.substring(counter, counter + 2);
counter = counter + 2;
}
return x;
}
public int[] GetDiminsions(char letter)
{
int[] key = new int[2];
if (letter == ‘j’)
letter = ‘i’;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (matrix_arr[i][j] == letter)
{
key[0] = i;
key[1] = j;
break;
}
}
}
return key;
}

public String encryptMessage(String Source)


{
String src_arr[] = Divid2Pairs(Source);
String Code = new String();
char one;
char two;
int part1[] = new int[2];
int part2[] = new int[2];
for (int i = 0; i < src_arr.length; i++)
{
one = src_arr[i].charAt(0);
two = src_arr[i].charAt(1);
part1 = GetDiminsions(one);
part2 = GetDiminsions(two);
if (part1[0] == part2[0])
{
if (part1[1] < 4)
part1[1]++;
else
part1[1] = 0;
if (part2[1] < 4)
part2[1]++;
else
part2[1] = 0;
}
else if (part1[1] == part2[1])
{
if (part1[0] < 4)
part1[0]++;
else
part1[0] = 0;
if (part2[0] < 4)
part2[0]++;
else
part2[0] = 0;
}
else
{
int temp = part1[1];
part1[1] = part2[1];
part2[1] = temp;
}

Code = Code + matrix_arr[part1[0]][part1[1]]


+ matrix_arr[part2[0]][part2[1]];
}
return Code;
}

public static void main(String[] args)


{
PlayfairCipherEncryption x = new PlayfairCipherEncryption();
Scanner sc = new Scanner(System.in);
System.out.println(“Enter a keyword:”);
String keyword = sc.next();
x.setKey(keyword);
x.KeyGen();
System.out .println(“Enter word to encrypt: (Make sure length of message is even)”);
String key_input = sc.next();
if (key_input.length() % 2 == 0)
{
System.out.println(“Encryption: “ + x.encryptMessage(key_input));
}
else
{
System.out.println(“Message length should be even”);
}

sc.close();
}
}

OUTPUT
$ javac PlayfairCipherEncryption.java
$ java PlayfairCipherEncryption
Enter a keyword:
Sanfoundry
Sanfoudrybceghiklmpqstvwxz
Sanfo
udryb
ceghi
klmpq
stvwx
Enter word to encrypt: (Make sure length of message is even)
Learningcenter
Encryption: acndogrmegavgd
USING C PGM

#include<stdio.h>
int main(){

char arr[5][5]={"MONAR","CHYBD","EFGIK","LPQST","UVWXZ"};
char pt[10];

int i, j, r1=0, r2=0, c1=0, c2=0;


printf("Playfair Keymatrix\n==================\n");
for(i=0; i<5; i++)
{
for(j=0; j<5; j++)
printf("%c ", arr[i][j]);
printf("\n");
}

printf("Enter your plain text:");


scanf("%s",pt);
printf("Your plain text = %s", pt);

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


{
for(j=0; j<5; j++)
{
if(arr[i][j] == pt[0])
{
r1=i; c1=j;
}
if(arr[i][j] == pt[1])
{
r2=i; c2=j;
}
}
}
if(r1==r2) //when both characters in same row
{
if(c2==4) //for char in last column
printf("Ciphertext = %c%c \n", arr[r1][c1+1], arr[r2][0]);
else
printf("Ciphertext = %c%c \n", arr[r1][c1+1], arr[r2][c2+1]);
}
if(c1==c2)//when both characters in same column
{
if(r2==4) //for char in last row
printf("Ciphertext = %c%c \n", arr[r1+1][c1], arr[0][c2]);
else
printf("Ciphertext = %c%c \n", arr[r1+1][c1], arr[r2+1][c2]);
}
//when characters are not in a same row and column
if(r1 != r2 && c1 != c2)
{
printf("\nCiphertext = %c%c \n", arr[r1][c2], arr[r2][c1]);
}
return 0;
}
Ex. No. 1. B ii) JAVA PROGRAM TO DECODE A MESSAGE ENCODED USING PLAYFAIR CIPHER

Aim: To write a program to perform decryption using Playfair Cipher

Procedure:
The Playfair Cipher Decryption Algorithm:
The Algorithm consistes of 2 steps:
1. Generate the key Square(5×5) at the receiver’s end:
The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext.
Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted
from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is
replaced by I.
• The initial alphabets in the key square are the unique alphabets of the key in the order
in which they appear followed by the remaining letters of the alphabet in order.

For example:
The key is "monarchy"
Thus the initial entires are
'm', 'o', 'n', 'a', 'r', 'c', 'h', 'y'
followed by remaining characters of
a-z(except 'j') in that order.

2. Algorithm to decrypt the ciphertext: The ciphertext is split into pairs of two letters
(digraphs).
For example:
CipherText: "gatlmzclrqtx"
After Split: 'ga' 'tl' 'mz' 'cl' 'rq' 'tx'
Rules for Decryption:
• If both the letters are in the same column: Take the letter above each one
(going back to the bottom if at the top).
For example:
Diagraph: "cl"
Decrypted Text: me
Decryption:
c -> m
l -> e
• If both the letters are in the same row: Take the letter to the left of each one (going
back to the rightmost if at the leftmost position).
• If neither of the above rules is true: Form a rectangle with the two letters and take
the letters on the horizontal opposite corner of the rectangle.

Program

package com.sanfoundry.setandstring;
import java.util.Scanner;
public class PlayfairCipherDecryption
{
private String KeyWord = new String();
private String Key = new String();
private char matrix_arr[][] = new char[5][5];
public void setKey(String k)
{
String K_adjust = new String();
boolean flag = false;
K_adjust = K_adjust + k.charAt(0);
for (int i = 1; i < k.length(); i++)
{
for (int j = 0; j < K_adjust.length(); j++)
{
if (k.charAt(i) == K_adjust.charAt(j))
{
flag = true;
}
}
if (flag == false)
K_adjust = K_adjust + k.charAt(i);
flag = false;
}
KeyWord = K_adjust;
}

public void KeyGen()


{
boolean flag = true;
char current;
Key = KeyWord;
for (int i = 0; i < 26; i++)
{
current = (char) (i + 97);
if (current == 'j')
continue;
for (int j = 0; j < KeyWord.length(); j++)
{
if (current == KeyWord.charAt(j))
{
flag = false;
break;
}
}
if (flag)
Key = Key + current;
flag = true;
}
System.out.println(Key);
matrix();
}
private void matrix()
{
int counter = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
matrix_arr[i][j] = Key.charAt(counter);
System.out.print(matrix_arr[i][j] + " ");
counter++;
}
System.out.println();
}

private String format(String old_text)


{
int i = 0;
int len = 0;
String text = new String();
len = old_text.length();
for (int tmp = 0; tmp < len; tmp++)
{
if (old_text.charAt(tmp) == 'j')
{
text = text + 'i';
}
else
text = text + old_text.charAt(tmp);
}

len = text.length();
for (i = 0; i < len; i = i + 2)
{
if (text.charAt(i + 1) == text.charAt(i))
{
text = text.substring(0, i + 1) + 'x' + text.substring(i + 1);
}
}
return text;
}

private String[] Divid2Pairs(String new_string)


{
String Original = format(new_string);
int size = Original.length();
if (size % 2 != 0)
{
size++;
Original = Original + 'x';
}
String x[] = new String[size / 2];
int counter = 0;
for (int i = 0; i < size / 2; i++)
{
x[i] = Original.substring(counter, counter + 2);
counter = counter + 2;
}
return x;
}

public int[] GetDiminsions(char letter)


{
int[] key = new int[2];
if (letter == 'j')
letter = 'i';
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (matrix_arr[i][j] == letter)
{
key[0] = i;
key[1] = j;
break;
}
}
}
return key;
}

public String encryptMessage(String Source)


{
String src_arr[] = Divid2Pairs(Source);
String Code = new String();
char one;
char two;
int part1[] = new int[2];
int part2[] = new int[2];
for (int i = 0; i < src_arr.length; i++)
{
one = src_arr[i].charAt(0);
two = src_arr[i].charAt(1);
part1 = GetDiminsions(one);
part2 = GetDiminsions(two);
if (part1[0] == part2[0])
{
if (part1[1] < 4)
part1[1]++;
else
part1[1] = 0;
if (part2[1] < 4)
part2[1]++;
else
part2[1] = 0;
}
else if (part1[1] == part2[1])
{
if (part1[0] < 4)
part1[0]++;
else
part1[0] = 0;
if (part2[0] < 4)
part2[0]++;
else
part2[0] = 0;
}
else
{
int temp = part1[1];
part1[1] = part2[1];
part2[1] = temp;
}
Code = Code + matrix_arr[part1[0]][part1[1]]
+ matrix_arr[part2[0]][part2[1]];
}
return Code;
}
public String decryptMessage(String Code)
{
String Original = new String();
String src_arr[] = Divid2Pairs(Code);
char one;
char two;
int part1[] = new int[2];
int part2[] = new int[2];
for (int i = 0; i < src_arr.length; i++)
{
one = src_arr[i].charAt(0);
two = src_arr[i].charAt(1);
part1 = GetDiminsions(one);
part2 = GetDiminsions(two);
if (part1[0] == part2[0])
{
if (part1[1] > 0)
part1[1]--;
else
part1[1] = 4;
if (part2[1] > 0)
part2[1]--;
else
part2[1] = 4;
}
else if (part1[1] == part2[1])
{
if (part1[0] > 0)
part1[0]--;
else
part1[0] = 4;
if (part2[0] > 0)
part2[0]--;
else
part2[0] = 4;

}
else
{
int temp = part1[1];
part1[1] = part2[1];
part2[1] = temp;
}
Original = Original + matrix_arr[part1[0]][part1[1]] + matrix_arr[part2[0]][part2[1]];
}
return Original;
}
public static void main(String[] args)
{
PlayfairCipherDecryption x = new PlayfairCipherDecryption();
Scanner sc = new Scanner(System.in);
System.out.println("Enter a keyword:");
String keyword = sc.next();
x.setKey(keyword);
x.KeyGen();
System.out.println("Enter word to encrypt: (Make sure length of message is even)");
String key_input = sc.next();
if (key_input.length() % 2 == 0)
{
System.out.println("Encryption: " + x.encryptMessage(key_input));
System.out.println("Decryption: "+ x.decryptMessage(x.encryptMessage(key_input)));
}
else
{
System.out.println("Message length should be even");
}
sc.close();
}
}
OUTPUT
$ javac PlayfairCipherDecryption.java
$ java PlayfairCipherDecryption
Enter a keyword:
sanfoundry
sanfoudrybceghiklmpqtvwxz
sanfo
udryb
ceghi
klmpq
tvwxz
Enter word to encrypt: (Make sure length of message is even)
learning
Encryption: vlndogrm
Decryption: learning
Ex. No. 1.C) Hill CIPHER
Date:

Aim: To write a program to perform encryption and decryption using Hill Cipher
Procedure:

Hill Cipher
• The Hill cipher is a poly-graphic substitution cipher (plaintext letters are substituted in
larger groups, instead of substituting letters individually i.e. Works on multiple letters at
same time).
• In this Hill cipher technique, the KEY and PLAINTEXT must be in the form of
square matrix.
• The KEY must be chosen randomly according to PLAINTEXT.

ENCRYPTION:
1. To encrypt the message, we will use the formula C=K.P mod 26 where C is
Ciphertext, K is the Key, P is Plaintext.
2. Each letter is represented by a number modulo 26. Often following simple scheme is
used.

3. By using above value table we have to write the corresponding numbers of alphabets
present in KEY and PLAINTEXT.
4. For example:
PLAINTEXT message: ATTACK, KEY:CDDG

1) Find inverse of random chosen key matrix


2) Multiply Inverse matrix with ciphertext against mod 26
Original Plaintext = [(Inverse of key matrix) x (Ciphertext)] mod 26
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=newfloat[3][3]; static float[][] mes=newfloat[3][1];
staticfloat[][ ]res=new float[3][1];
static BufferedReaderbr=new BufferedReader(newInputStreamReader(System.in));
static
Scannersc=new Scanner(System.in);
public static void main(String[]args) throws IOException {
//TODO code application logic here get keymes();
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("\nEncryptedstringis:");
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("\nDecryptedstringis:");
for(int i=0;i<3;i++) {
System.out.print((char)(decrypt[i][0]%26+97));
}
System.out.print("\n");
}
Public static void getkeymes( )throwsIOException {
System.out.println("Enter3x3matrixforkey(Itshouldbeinversible):");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j]=sc.nextFloat();
System.out.print("\nEntera3letterstring:");
Stringmsg=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(intj=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("\nInverseMatrixis:");
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:
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


Ex. No. 1. D) VIGENERE CIPHER
Date:

Aim: To write a program to perform encryption and decryption using VIGENERE Cipher
Procedure:

1.d) VIGENERE CYPHER

Program

package com.sanfoundry.setandstring;
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
$ javac VigenereCipher.java
$ java VigenereCipher
String: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Encrypted message:
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted message: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH

Ex. No. 2.A) RAIL FENCE CIPHER


Date:
Aim: To write a program to perform encryption and decryption using RAIL FENCE Cipher
Procedure:

Program

// File Name: RailFence.java


import java.util.*;
class RailFenceBasic{
int depth;
String Encryption(String plainText,int depth)throws Exception
{
int r=depth,len=plainText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String cipherText="";
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
if(k!=len)
mat[j][i]=plainText.charAt(k++);
else
mat[j][i]='X';
}
}
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
cipherText+=mat[i][j];
}
}
return cipherText;
}
String Decryption(String cipherText,int depth)throws Exception
{
int r=depth,len=cipherText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String plainText="";
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
mat[i][j]=cipherText.charAt(k++);
}
}
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
plainText+=mat[j][i];
}
}
return plainText;
}
}
class RailFence{
public static void main(String args[])throws Exception
{
RailFenceBasic rf=new RailFenceBasic();
Scanner scn=new Scanner(System.in);
int depth;
String plainText,cipherText,decryptedText;
System.out.println("Enter plain text:");
plainText=scn.nextLine();
System.out.println("Enter depth for Encryption:");
depth=scn.nextInt();
cipherText=rf.Encryption(plainText,depth);
System.out.println("Encrypted text is:\n"+cipherText);
decryptedText=rf.Decryption(cipherText, depth);
System.out.println("Decrypted text is:\n"+decryptedText);
}
}
OUTPUT
Enter plain text: railfencecipher
Enter depth for Encryption: 3
Encrypted text is: rlnchafcieieepr
Decrypted text is: railfenceciphe
Ex. No. 2.A) TRANSPOSITION CIPHER
Date:
Aim: To write a program to perform encryption and decryption using Transposition Cipher
Procedure:
The columnar transposition cipher is a fairly simple, easy to implement cipher. It is a
transposition cipher that follows a simple rule for mixing up the characters in the plaintext to
form the ciphertext.

Example
The key for the columnar transposition cipher is a keyword e.g. GERMAN. The
row length that is used is the same as the length of the keyword. To encrypt
a piece of text, e.g.
defend the east wall of the castle

we write it out in a special way in a number of rows (the keyword here


is GERMAN ):
GERMAN
d e f e n d
t h e e a s
t w a l l o
f t h e c a
s t l e x x
In the above example, the plaintext has been padded so that it neatly fits in
a rectangle. This is known as a regular columnar transposition. An irregular
columnar transposition leaves these characters blank, though this makes
decryption slightly more difficult. The columns are now reordered such that
the letters in the key word are ordered alphabetically.

AEGMNR
n e d e d f
a h t e s e
l w t l o a
c t f e a h
x t s e x l
The ciphertext is read off along the columns:

nalcxehwttdttfseeleedsoaxfeahl

Program
<!doctype html>
<html>
<head>
<title>Practical Cryptography</title>
</head>

<body id="ciphers">
<h1>Columnar Transposition Cipher</h1>
<script type="text/javascript">
function Encrypt() {
plaintext = document.getElementById("p").value.toLowerCase().replace(/[^a-z]/g, "");
if(plaintext.length < 1){ alert("please enter some plaintext"); return; }
var key = document.getElementById("key").value.toLowerCase().replace(/[^a-z]/g, "");
var pc = document.getElementById("pc").value.toLowerCase().replace(/[^a-z]/g, "");
if(pc=="") pc = "x";
while(plaintext.length % key.length != 0) plaintext += pc.charAt(0);
var colLength = plaintext.length / key.length;
var chars = "abcdefghijklmnopqrstuvwxyz";
ciphertext = ""; k=0;
for(i=0; i < key.length; i++){
while(k<26){
t = key.indexOf(chars.charAt(k));
arrkw = key.split(""); arrkw[t] = "_"; key = arrkw.join("");
if(t >= 0) break;
else k++;
}
for(j=0; j < colLength; j++) ciphertext += plaintext.charAt(j*key.length + t);
}
document.getElementById("c").value = ciphertext;
}
function Decrypt(f) {
ciphertext = document.getElementById("c").value.toLowerCase().replace(/[^a-z]/g, "");
if(ciphertext.length < 1){ alert("please enter some ciphertext (letters only)"); return; }
keyword = document.getElementById("key").value.toLowerCase().replace(/[^a-z]/g, "");
klen = keyword.length;
if(klen <= 1){ alert("keyword should be at least 2 characters long"); return; }
if(ciphertext.length % klen != 0){ alert("ciphertext has not been padded, the result may be
incorrect (incorrect keyword?)."); }
// first we put the text into columns based on keyword length
var cols = new Array(klen);
var colLength = ciphertext.length / klen;
for(i=0; i < klen; i++) cols[i] = ciphertext.substr(i*colLength,colLength);
// now we rearrange the columns so that they are in their unscrambled state
var newcols = new Array(klen);
chars="abcdefghijklmnopqrstuvwxyz"; j=0;i=0;
while(j<klen){
t=keyword.indexOf(chars.charAt(i));
if(t >= 0){
newcols[t] = cols[j++];
arrkw = keyword.split(""); arrkw[t] = "_"; keyword = arrkw.join("");
}else i++;
}
// now read off the columns row-wise
plaintext = "";
for(i=0; i < colLength; i++){
for(j=0; j < klen; j++) plaintext += newcols[j].charAt(i);
}
document.getElementById("p").value = plaintext;
}
</script>

<p>This is a JavaScript implementation of the Columnar Transposition Cipher. This


implementation pads the
plaintext so that its length is a multiple of the key length.</p>
Plaintext<br>
<textarea id="p" name="p" rows="4" cols="50">attack at dawn</textarea>
<p> keyword = <input id="key" name="key" size="10" value="zebra" type="text"> pad
character = <input id="pc" name="pc" size="1" value="x" type="text"></p>
<p><input name="btnEn" value="v Encrypt v" onclick="Encrypt()" type="button">
<input name="btnDe" value="^ Decrypt ^" onclick="Decrypt()" type="button"></p>
<p>Ciphertext<br><textarea id="c" name="c" rows="4" cols="50"></textarea> </p>
</script>
</body>
</html>
ENCRYPTION

DECRYPTION
Ex. No. 3 DES ALGORITHM
Date:

Aim: To write a program to perform encryption and decryption using DES ALGORITHM
Procedure:
Program

DATA ENCRYPTION DECRYPTION USING DES ALGORITHM

package com.anuj.security.encryption;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class DESEncryptionDecryption {
private static Cipher encryptCipher;
private static Cipher decryptCipher;
public static void main(String[] args) {
try {
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey secretKey = keygenerator.generateKey();
encryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = encryptData("Classified Information!");
decryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
decryptData(encryptedData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
}
/**
* Encrypt Data
* @param data
* @return
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
private static byte[] encryptData(String data)
throws IllegalBlockSizeException, BadPaddingException {
System.out.println("Data Before Encryption :" + data);
byte[] dataToEncrypt = data.getBytes();
byte[] encryptedData = encryptCipher.doFinal(dataToEncrypt);
System.out.println("Encryted Data: " + encryptedData);
return encryptedData;
}
/**
* Decrypt Data
* @param data
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
private static void decryptData(byte[] data)
throws IllegalBlockSizeException, BadPaddingException {
byte[] textDecrypted = decryptCipher.doFinal(data);
System.out.println("Decryted Data: " + new String(textDecrypted));
}
}
Here,
DES = Data Encryption Standard.
ECB = Electronic Codebook mode.
PKCS5Padding = PKCS #5-style padding
While initializing Cipher, we can pass Key,Certificate and AlgorithParameters as well.

OUTPUT
Data Before Encryption :Classified Information!
Encryted Data: [B@bc6007
Decryted Data: Classified Information!
Ex. No. 4 AES ALGORITHM
Date:

Aim: To write a program to perform encryption and decryption using AES ALGORITHM
Procedure:
Program

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AES {

private static SecretKeySpec secretKey;


private static byte[] key;

public static void setKey(String myKey)


{
MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
}
catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

public static String encrypt(String strToEncrypt, String secret)


{
try
{
setKey(secret);
Cipher cipher =
Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return
Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getB
ytes("UTF-8")));
}
catch (Exception e)
{
System.out.println("Error while encrypting: " +
e.toString());
}
return null;
}

public static String decrypt(String strToDecrypt, String secret)


{
try
{
setKey(secret);
Cipher cipher =
Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new
String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
}
catch (Exception e)
{
System.out.println("Error while decrypting: " +
e.toString());
}
return null;
}
}

2. Encryption and decryption example

Let’s test if we are able to get the decrypted string back from encrypted string.

public static void main(String[] args)


{
final String secretKey = "ssshhhhhhhhhhh!!!!";

String originalString = "howtodoinjava.com";


String encryptedString = AES.encrypt(originalString, secretKey) ;
String decryptedString = AES.decrypt(encryptedString, secretKey) ;

System.out.println(originalString);
System.out.println(encryptedString);
System.out.println(decryptedString);
}

Output:
howtodoinjava.com
Tg2Nn7wUZOQ6Xc+1lenkZTQ9ZDf9a2/RBRiqJBCIX6o=
howtodoinjava.com

Ex. No. 5 RSA ALGORITHM


Date:

Aim: To write a HTML and JAVA SCRIPT program to perform encryption and decryption
using RSA ALGORITHM
Procedure:

Download

Go to https://github.com/travist/jsencrypt to download this library.


Website & Demo

http://travistidwell.com/jsencrypt
How to use this library.

This library should work hand-in-hand with openssl. With that said, here is how to
use this library.

• Within your terminal (Unix based OS) type the following.

openssl genrsa -out rsa_1024_priv.pem 1024


• This generates a private key, which you can see by doing the following…

cat rsa_1024_priv.pem
You can then copy and paste this in the Private Key section of within index.html.
Next, you can then get the public key by executing the following command.
openssl rsa -pubout -in rsa_1024_priv.pem -out
rsa_1024_pub.pem
• You can see the public key by typing…
cat rsa_1024_pub.pem

Now copy and paste this in the Public key within the index.html.
Now you can then convert to and from encrypted text by doing the following in code.
Program

!doctype html>
<html>
<head>
<title>JavaScript RSA Encryption</title>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="bin/jsencrypt.min.js"></script>
<script type="text/javascript">

// Call this code when the page is done loading.


$(function() {

// Run a quick encryption/decryption when they click.


$('#testme').click(function() {

// Encrypt with the public key...


var encrypt = new JSEncrypt();
encrypt.setPublicKey($('#pubkey').val());
var encrypted = encrypt.encrypt($('#input').val());

// Decrypt with the private key...


var decrypt = new JSEncrypt();
decrypt.setPrivateKey($('#privkey').val());
var uncrypted = decrypt.decrypt(encrypted);

// Now a simple check to see if the round-trip worked.


if (uncrypted == $('#input').val()) {
alert('It works!!!');
}
else {
alert('Something went wrong ... ');
}
});
});
</script>
</head>
<body>
<label for="privkey">Private Key</label><br/>
<textarea id="privkey" rows="15" cols="65">-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ
WMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR
aY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB
AoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv
xTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH
m7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd
8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF
z/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5
rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM
V7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe
aTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil
psLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz
uku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876
-----END RSA PRIVATE KEY ---- </textarea><br/>
<label for="pubkey">Public Key</label><br/>
<textarea id="pubkey" rows="15" cols="65">-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtN
FOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76
xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4
gwQco1KRMDSmXSMkDwIDAQAB
-----END PUBLIC KEY ---- </textarea><br/>
<label for="input">Text to encrypt:</label><br/>
<textarea id="input" name="input" type="text" rows=4 cols=70>This is a
test!</textarea><br/>
<input id="testme" type="button" value="Test Me!!!" /><br/>
</body>
</html>

OUTPUT
Program and demo available in the following link
http://travistidwell.com/blog/2013/02/15/a-better-library-for-javascript-
asymmetrical-rsa-encryption/
DECRYPTION

Ex. No. 6 DIFFIE-HELLMAN KEY EXCHANGE ALGORITHM


Date:

Aim: To write a program to perform encryption and decryption using Diffie-Hellman Key
Exchange algorithm
Procedure:
Program

package diffie;
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

Ex. No. 7 SHA-1 ALGORITHM


Date:

Aim: To Calculate the message digest of a text using the SHA-1 algorithm.
Procedure:
&
Program

Here are general steps to generate a hash value from an input (message):

• First approach (suitable for small-sized message):

1 // algorithm can be "MD5", "SHA-1", "SHA-256"


2 MessageDigest digest = MessageDigest.getInstance(algorithm);
3 byte[] inputBytes = // get bytes array from message

4 byte[] hashBytes = digest.digest(inputBytes);

8
// convert hash bytes to string (usually in hexadecimal form)

• Second approach (suitable for large-size message, i.e. large file):

1 MessageDigest digest = MessageDigest.getInstance(algorithm);


2
byte[] inputBytes = // get bytes array from message
3
digest.update(inputBytes);
4
byte[] hashedBytes = digest.digest();
5
// convert hash bytes to string (usually in hexadecimal form)

Now, let’s see some examples in details.

1. Generating Hash from String


The following method takes a message and algorithm name as inputs and returns
hexadecimal form of the calculated hash value:

1 private static String hashString(String message, String


algorithm)
2
throws HashGenerationException {
3
try {
4
MessageDigest digest =
5 MessageDigest.getInstance(algorithm);
6 byte[] hashedBytes =
digest.digest(message.getBytes("UTF-8"));
7
return convertByteArrayToHexString(hashedBytes);
8
} catch (NoSuchAlgorithmException |
9 UnsupportedEncodingException ex) {
10 throw new HashGenerationException(
"Could not generate hash from String",
11
ex);
}

The HashGenerationException is a custom exception (you can find this class in


the attachment). The convertByteArrayToHexString() method is implemented
as follows:
private static String convertByteArrayToHexString(byte[]
1 arrayBytes) {
2 StringBuffer stringBuffer = new StringBuffer();
3 for (int i = 0; i < arrayBytes.length; i++) {
4 stringBuffer.append(Integer.toString((arrayBytes[i]
& 0xff) + 0x100, 16)
5
.substring(1));
6
}
7
return stringBuffer.toString();
8
}
The hashString() is a general method. Here are four public utility methods that
are specific to each algorithm (MD5, SHA-1 and SHA-256):
1 public static String generateMD5(String message) throws
2 HashGenerationException {
3 return hashString(message, "MD5");
}
4
public static String generateSHA1(String message) throws
5 HashGenerationException {
return hashString(message, "SHA-1");
6
7 }
8 public static String generateSHA256(String message) throws
9 HashGenerationException {
10 return hashString(message, "SHA-256");
}

Hence we have the following utility class:


1 package net.codejava.security;

2 import java.io.UnsupportedEncodingException;
3 import java.security.MessageDigest;
4 import java.security.NoSuchAlgorithmException;

5
/**
6
* Hash functions utility class.
7
* @author www.codejava.net
8
*
9
*/
10
public class HashGeneratorUtils {
11
private HashGeneratorUtils() {
12
13
}
14
public static String generateMD5(String message) throws
15 HashGenerationException {
16 return hashString(message, "MD5");

17 }

18 public static String generateSHA1(String message) throws


HashGenerationException {
19
return hashString(message, "SHA-1");
20
}
21
public static String generateSHA256(String message) throws
22 HashGenerationException {
23 return hashString(message, "SHA-256");
24 }

25
26 private static String hashString(String message, String
algorithm)
27
throws HashGenerationException {
28
try {
29
MessageDigest digest =
30 MessageDigest.getInstance(algorithm);
31 byte[] hashedBytes =
digest.digest(message.getBytes("UTF-8"));
32
return convertByteArrayToHexString(hashedBytes);
33
} catch (NoSuchAlgorithmException |
34 UnsupportedEncodingException ex) {
35 throw new HashGenerationException(
36 "Could not generate hash from String", ex);
37 }

38 }

39
40 private static String convertByteArrayToHexString(byte[]
arrayBytes) {
41
StringBuffer stringBuffer = new StringBuffer();
42
for (int i = 0; i < arrayBytes.length; i++) {
43
stringBuffer.append(Integer.toString((arrayBytes[i]
44 & 0xff) + 0x100, 16)
45 .substring(1));
}
return stringBuffer.toString();
}
}
Here’s a test program:
1 package net.codejava.security;
2
3 /**
4 * Test generating hash values from String.
5 * @author www.codejava.net

6 *

7 */

8 public class StringHashGeneratorExample {


9
10 public static void main(String[] args) {
11 try {
12 String inputString = args[0];
13 System.out.println("Input String: " +
inputString);
14
15
String md5Hash =
16 HashGeneratorUtils.generateMD5(inputString);
17 System.out.println("MD5 Hash: " + md5Hash);

18
19 String sha1Hash =
HashGeneratorUtils.generateSHA1(inputString);
20
System.out.println("SHA-1 Hash: " + sha1Hash);
21
22
String sha256Hash =
23 HashGeneratorUtils.generateSHA256(inputString);
24 System.out.println("SHA-256 Hash: " +
sha256Hash);
25
} catch (HashGenerationException ex) {
26
ex.printStackTrace();
27
}
28
}

OUTPUT
If the input message is “admin” the test program produces the following output:
1 Input String: admin
2 MD5 Hash: 21232f297a57a5a743894a0e4a801fc3
3 SHA-1 Hash: d033e22ae348aeb5660fc2140aec35850c4da997
4 SHA-256 Hash:
8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

Ex. No. 8 DIGITAL SIGNATURE STANDARD


Date:

Aim: To write a JAVA program to implement the Digital Signature Standard scheme.

Procedure:

Signing:

Verifying:
Correctness of the Algorithm
Program

import java.util.*;
import java.math.BigInteger;

class DSS
{
final static BigInteger one = new
BigInteger("1"); final static
BigInteger zero = new
BigInteger("0");

/* incrementally tries for next prime */


public static BigInteger getNextPrime(String ans)
{
BigInteger test = new
BigInteger(ans); while
(!test.isProbablePrime
(99))
{
test = test.add(one);
}
return test;
}

/* finds largest prime factor of n */


public static BigInteger findQ(BigInteger n)
{
BigInteger start = new BigInteger("2"); while (!n.isProbablePrime(99))
{
while (!((n.mod(start)).equals(zero)))
{
start = start.add(one);
}
n = n.divide(start);
}
return n;
}

/* finds a generator mod p */


public static BigInteger getGen(BigInteger p, BigInteger q, Random r)
{
BigInteger h = new
BigInteger(p.bitLength(), r); h =
h.mod(p);
return h.modPow((p.subtract(one)).divide(q), p);
}

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


{
Random randObj = new Random();
/* establish the global public
key components */ BigInteger p
= getNextPrime("10600");
/* approximate prime */
BigInteger q =
findQ(p.subtract(one))
; BigInteger g =
getGen(p,q,randObj);

/* public key components */


System.out.println("Simulation of Digital
Signature Algorithm");
System.out.println("Global public key
components are:"); System.out.println("p is: " +
p);
System.out.println("q is: " + q);
System.out.println("g is: " + g);
/* find the private key */
BigInteger x = new
BigInteger(q.bitLength(), randObj); x =
x.mod(q);
/*
corresponding
public key */
BigInteger y =
g.modPow(x,p)
;
/* random value message */
BigInteger k = new
BigInteger(q.bitLength(), randObj); k =
k.mod(q);
/* randomly generated hash value and
digital signature */ BigInteger r =
(g.modPow(k,p)).mod(q);
BigInteger hashVal = new
BigInteger(p.bitLength(), randObj);
BigInteger kInv = k.modInverse(q);
BigInteger s =
kInv.multiply(hashVal.add(x.multiply(r))
); s = s.mod(q);
/* secret information */
System.out.println("Secret
information are:");
System.out.println("x (private)
is: " + x); System.out.println("k
(secret) is: " + k);
System.out.println("y (public)
is: " + y); System.out.println("h
(rndhash) is: " + hashVal);
System.out.println("Generating
Digital signature:");
System.out.println("r is : " + r);
System.out.println("s is : " + s);
/* verify the
digital signature
*/ BigInteger w
=
s.modInverse(q)
;
BigInteger u1 =
(hashVal.multiply(w)).mod(q);
BigInteger u2 =
(r.multiply(w)).mod(q);
BigInteger v =
(g.modPow(u1,p)).multiply(y.modPow(u2,p))
; v = (v.mod(p)).mod(q);
System.out.println("verifying digital signature
(checkpoints):"); System.out.println("w is : " +
w);
System.out.println
("u1 is : " + u1);
System.out.println
("u2 is : " + u2);
System.out.println
("v is : " + v);
if (v.equals(r))
{
System.out.println("Success: Digital signature is verified! " + r);
}
else
{
System.out.println("Error: Incorrect Digital signature");
}
}
}

OUTPUT:
C:\javaprg>javac DSS.java C:\javaprg>java DSS
Simulation of Digital Signature Algorithm Global public key components are:
p is: 10601
q is: 53
g is: 4763
Secret information are:
x (private) is: 33 k (secret) is: 30
y (public) is: 6965
h (rndhash) is: 13010 Generating Digital signature: r is : 48
s is : 13
verifying digital signature (checkpoints): w is : 49
u1 is : 6 u2 is : 20 v is : 48
Success: Digital signature is verified! 48
RESULT:
Thus the program to implement the DSS Algorithm was executed successfully and the
output was verified.

You might also like