Sec Lab Programs
Sec Lab Programs
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
// 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);
Program
OUTPUT
test
lwkl
test
uftu
test
exxegoexsrgi
attackatonce
Ex. No. 1.B)
JAVA PROGRAM TO ENCODE A MESSAGE USING PLAYFAIR CIPHER
Date:
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:
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'
• 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.
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;
}
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];
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;
}
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;
}
}
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
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
Aim: To write a program to perform encryption and decryption using VIGENERE Cipher
Procedure:
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
Program
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
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>
DECRYPTION
Ex. No. 3 DES ALGORITHM
Date:
Aim: To write a program to perform encryption and decryption using DES ALGORITHM
Procedure:
Program
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;
Let’s test if we are able to get the decrypted string back from encrypted string.
System.out.println(originalString);
System.out.println(encryptedString);
System.out.println(decryptedString);
}
Output:
howtodoinjava.com
Tg2Nn7wUZOQ6Xc+1lenkZTQ9ZDf9a2/RBRiqJBCIX6o=
howtodoinjava.com
Aim: To write a HTML and JAVA SCRIPT program to perform encryption and decryption
using RSA ALGORITHM
Procedure:
Download
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.
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">
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
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
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):
8
// convert hash bytes to string (usually in hexadecimal form)
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 }
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 */
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
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");
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.