C&NS Lab ManualFinal27.03.19
C&NS Lab ManualFinal27.03.19
C&NS Lab ManualFinal27.03.19
II Sem. CSE
DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING
Mr. P.JAGADEESHWAR
Assistant Professor,
CSE Department.
INDEX
Write a C program that contains a string (char pointer) with a value ‘Hello
World’. The program should XOR each character in this string with 0 and
1 displays the result. 3
Write a C program that contains a string (char pointer) with a value \Hello
World’. The program should AND or and XOR each character in this string
2 with 127 and display the result. 4
Write the RC4 logic in Java Using Java Cryptography, encrypt the text
7 “Hello world” using BlowFish. Create your own key using Java keytool. 19-20
10 Calculate the message digest of a text using the SHA-1 algorithm in JAVA. 25-26
11 Calculate the message digest of a text using the SHA-1 algorithm in JAVA. 27-28
AIM: Write a C program that contains a string (char pointer) with a value \HelloWorld’. The
program should XOR each character in this string with 0 and displays the result.
Algorithm:
1. In XOR operation that it will return true if one, and only one, of the two operators.
If two operators is true and two operators is false the result is false.
PROGRAM:
#include<stdlib.h>
main()
{
char str[]="Hello World";
char str1[11];
int i,len;
len=strlen(str);
for(i=0;i<len;i++)
{
str1[i]=str[i]^0;
printf("%c",str1[i]);
}
printf("\n");
}
Output:
Hello World
Algorithm:
1. In XOR operation that it will return true if one, and only one, of the two operators.
If two operators is true and two operators is false then the result is false.
PROGRAM:
#include <stdio.h>
#include<stdlib.h>
void main()
{
char str[]="Hello World";
char str1[11];
char str2[11];
char str3[11];
int i,len;
len = strlen(str);
for(i=0;i<len;i++)
{
str1[i] = str[i]&127;
printf("%c",str1[i]);
}
printf("\n");
for(i=0;i<len;i++)
{
str2[i] = str[i]|127;
printf("%c",str2[i]);
}
printf("\n");
for(i=0;i<len;i++)
{
str3[i] = str[i]^127;
printf("%c",str3[i]);
}
Output:
Hello World
•••••••••••
7 _(
AIM: Write a Java program to perform encryption and decryption using thefollowing
algorithms:
a) Ceaser Cipher
b) Substitution Cipher
c) Hill Cipher
Ceaser Cipher
Algorithm:
1. The method is named after Julius Caesar cipher.
2. The transformation can be represented by aligning two alphabets.
3. The cipher alphabet is the plain alphabet rotated left or right by some number of positions.
4. The encryption can also be represented using modular arithmetic by first transforming the
letters into numbers according to the scheme, A=0, B=1, …..Z=25
PROGRAM:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CeaserCipher
{
static Scanner sc=new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
// TODO code application logic here
c = c - 26;
}
encrypted += (char) c;
}
return encrypted;
}
public static String decrypt(String str, int key)
{
String decrypted = "";
for(int i = 0; i<str.length();i++)
{ int c = str.charAt(i);
if(Character.isUpperCase(c))
{ c = c - (key % 26);
if (c <'A')
c = c + 26;
}
else
if (Character.isLowerCase(c))
{ c = c - (key % 26);
if (c <'a')
c = c + 26;
}
decrypted += (char) c;
}
return decrypted;
} }
Output:
Enter any String: Hello World
Enter the Key: 5
Encrypted String is: MjqqtBtwqi
Decrypted String is: Hello World
b) Substitution Cipher
Algorithm:
1. Take the string a=”abcdefghijklmnopqrstuvwxyz”.
2. Take the string b=”zyxwvutsrqponmlkjihgfedcba”
3. Read any string.
4. In encryption compare the string a and string b, the corresponding position letters in string
b is encrypted data.
PROGRAM:
import java.io.*;
import java.util.*;
public class SubstitutionCipher {
static Scanner sc = new Scanner(System.in);
static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
public static void main(String[] args) throws IOException {
TODO code application logic here
String a =abcdefghijklmnopqrstuvwxyz";
String b = "zyxwvutsrqponmlkjihgfedcba";
Output:
Enter any string: aceho
The encrypted data is: zxvsl
2. Each letter is represented by a number modulo 26. To encrypt a message, each block of n
letters is multiplied by an invertible n × n matrix, again modulus 26.
3. To decrypt the message, each block is multiplied by the inverse of the matrix used for
encryption. The matrix used for encryption is the cipher key, and it should be chosen
randomly from the set of invertible n × n matrices (modulo 26).
5. All arithmetic just needs to be done modulo the number of letters instead of modulo.
PROGRAM:
import java.io.*;
import java.util.*;
import java.io.*;
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() {
floatp,q;
float[][] c = a;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
//a[i][j]=sc.nextFloat();
if(i==j)
b[i][j]=1;
else b[i][j]=0;
}
for(int k=0;k<3;k++) {
for(int i=0;i<3;i++) {
p = c[i][k];
q = c[k][k];
for(int j=0;j<3;j++) {
if(i!=k)
{
c[i][j] = c[i][j]*q-p*c[k][j];
b[i][j] = b[i][j]*q-p*b[k][j];
}
}
}
}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
b[i][j] = b[i][j]/c[i][i]; }
System.out.println("");
System.out.println("\n Inverse Matrix is : ");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++)
System.out.print(b[i][j] + "");
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
Hill(int block)
{
this.block=block;
}
key[i][j]=scn.nextInt();
}
}
}
sum = 0;
}
}
plainText=plainText.toUpperCase();
int len=plainText.length();
// System.out.println(plainText.substring(1,2+1));
while(len%block!=0)
{
plainText+="X";
System.out.println(len);
len=plainText.length();
}
cipherText=cipherText.toUpperCase();
int len=cipherText.length();
class HillCipher1{
public static void main(String args[])throws Exception
{
String plainText,cipherText;
int block;
Scanner scn=new Scanner(System.in);
System.out.println("Enter plain-text:");
plainText=scn.nextLine();
plainText=plainText.replaceAll("", "");
cipherText= hill.encrypt(plainText);
}
}
/*OUTPUT
Enter plain-text:
meet
Enter block size of matrix:
2
Enter key Matrix
31
52
Encrypted Text is:
OQ FG
Enter key Inverse Matrix:
2 -1
-5 3
Decrypted Text is:
ME ET */
4. IMPLEMENTATION OF DES
ALGORITHM:
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
The 16th round XL value is XOR ed with P18 value, XR value is XOR ed with P17
import java.io.*;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Encoder;
public class Blowfish {
public static void main(String[] args) throws Exception {
// TODO code application logic here
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
Key secretKey = keyGenerator.generateKey();
Cipher cipherOut = Cipher.getInstance("Blowfish/CFB/NoPadding");
cipherOut.init(Cipher.ENCRYPT_MODE, secretKey);
BASE64Encoder encoder = new BASE64Encoder();
byte iv[] = cipherOut.getIV(); if (iv != null)
{
System.out.println("Initialization Vector of the Cipher: " + encoder.encode(iv));
}
FileInputStream fin = new FileInputStream("inputFile.txt");
FileOutputStream fout = new FileOutputStream("outputFile.txt");
CipherOutputStream cout = new CipherOutputStream(fout, cipherOut);
int input = 0;
while ((input = fin.read()) != -1)
{
cout.write(input);
}
fin.close();
cout.close();
}
}
OUTPUT:
Initialization Vector of the Cipher: dI1MXzW97oQ=
Contents of inputFile.txt: Hello World
Contents of outputFile.txt: ùJÖ˜ NåI“
Algorithim
AES is based on a design principle known as a substitution–permutation network, and is efficient in both software and
hardware.[9] Unlike its predecessor DES, AES does not use a Feistel network. AES is a variant of Rijndael which has a
fixed block size of 128 bits, and a key size of 128, 192, or 256 bits. By contrast, Rijndael per se is specified with block and
key sizes that may be any multiple of 32 bits, with a minimum of 128 and a maximum of 256 bits.
AES operates on a 4 × 4 column-major order array of bytes, termed the state.[note 3] Most AES calculations are done in a
particular finite field.
For instance, if there are 16 bytes, , these bytes are represented as this two-dimensional array:
The key size used for an AES cipher specifies the number of transformation rounds that convert the input, called
the plaintext, into the final output, called the ciphertext. The number of rounds are as follows:
PROGRAM:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
public class AES {
public static String asHex (byte buf[]) { StringBuffer strbuf
= new StringBuffer(buf.length * 2); int i;
for (i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); }
return strbuf.toString(); }
public static void main(String[] args) throws Exception {
String message="Hello JIET";
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.
SecretKey skey = kgen.generateKey(); byte[] raw = skey.getEncoded();
SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
// Instantiate the cipher
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal((args.length == 0 ? message :
temp = 0
for i = 0 to 255
temp = (temp + S[i] + T[i]) mod 256
swap(S[i],S[temp])
After that we need neither T nor Key. Stream generation is done using this pseudo
algorithm:
i=0
j=0
while (true)
i = (i + 1) mod 256
j = (j + S[i]) mod 256
swap(S[i],S[j])
t = (S[i] + S[j]) mod 256
val = S[t]
val is the output on each iteration and it is XORed against the input byte to produce the
next output byte. So to encrypt, the next input byte which is considered plain data is
XORed with val to produce the next cipher byte and to decrypt, the next input byte is
XORed with val to produce the next plain byte. (If number A is XORed with number B
twice, the result is A, i.e (A xor B) xor B = A)
To be able to produce the plain data from the encrypted data you need to know with what
values the encrypted bytes should be XORed. Having the correct key generates those
values so provides the algorithm with correct series of S permutations and correct
sequence of bytes to XOR with input hence making it possible to reproduce the plain
data. You can see stream generation involves a swap operation with generating each new
byte and also the selected value (the val at the last line) does not depend on the input
byte. That means a same input byte (consider character ‘A’ exists in different location of
plain data to be encrypted) is XORed with different value each time. This is different
than the example encryption scenario which we introduced at the beginning of the article
which used a static mapping between plain and cipher text making the cryptanalysis
attacks possible.
In the following RC4 is implemented as a demo program which generates a random key
using Linux’s “/dev/urandom” (so can be run on Linux only) at the beginning of
execution and then encrypts a message using the proposed RC4 algorithm with that key,
shows the encrypted message in HEX format then decrypts the data with the same key
producing the original plain message. The algorithm surely is not l imited to ASCII data.
The input can be anything but for the purpose of demonstration I used a an English
phrase as input in this program. By a little modification you can encrypt any file using
this same code. You can see a sample output of running the pro gram below:
Generated sample key: AJAOAALGAA
> Secret text: Find the treasure 3 meters away from that tall tree where the kid passes by!
> Encryted message:
17144C9CC8C66D4AEEFFADABEEB7342E352C6E47BB320DF3BFF596D8C69AFF73
1760B9B8289660A9766A63762276636E6E227670676722756A67706722766A6722696B
662272637171677122607B23
> Decryted RC4 data with the same key: Find the treasure at 3 meters away from that tall
tree where the kid passes by!
int j=0;
for(int i=0;i<255;i++)
{
j=(j+s[i]+k[i])%256;
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
int i=0;
j=0;
int z=0;
for(int l=0;l<ptext.length();l++)
{
i=(l+1)%256;
j=(j+s[i])%256;
temp=s[i];
s[i]=s[j];
s[j]=temp;
z=s[(s[i]+s[j])%256];
cipher[l]=z^ptexti[l];
decrypt[l]=z^cipher[l];
}
System.out.println("ENCRYPTED");
display(cipher);
System.out.println("DECRYPTED");
display(decrypt);
}
static void display(int disp[])
{
char convert[]=new char[disp.length];
for(int l=0;l<disp.length;l++)
{
convert[l]=(char)disp[l];
System.out.println(convert[l]);
}
}
} OUTPUT:
ENTER PLAIN TEXT hello
ENTER KEY TEXT a
ENCRYPTED: x??r-
DECRYPTED: hello
7 b). Using Java Cryptography, encrypt the text “Hello world” using BlowFish.
PROGRAM:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.JOptionPane;
/**
* This program demonstrates how to encrypt/decrypt input
* using the Blowfish Cipher with the Java Cryptograhpy.
*
*/
public class BlowFishCipher {
// create a key
SecretKey secretkey = keygenerator.generateKey();
// encrypt message
byte[] encrypted = cipher.doFinal(inputText.getBytes());
// decrypt message
byte[] decrypted = cipher.doFinal(encrypted);
// end example
System.exit(0);
}
}
OUTPUT:
Input your message: Hello world
Encrypted text: 3ooo&&(*&*4r4
Decrypted text: Hello world
ALGORITHM:
STEP-1: Select two co-prime numbers as p and q.
STEP-2: Compute n as the product of p and q.
STEP-3: Compute (p-1)*(q-1) and store it in z.
STEP-4: Select a random prime number e that is less than that of z.
STEP-5: Compute the private key, d as e * mod-1(z).
STEP-6: The cipher text is computed as messagee * mod n.
STEP-7: Decryption is done as cipherdmod n.
Java PROGRAM:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.Random;
import java.util.Scanner;
public class RSA {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// TODO code application logic here
System.out.print("Enter a Prime number: ");
BigInteger p = sc.nextBigInteger(); // Here's one prime number..
System.out.print("Enter another prime number: ");
BigInteger q = sc.nextBigInteger(); // ..and another.
BigInteger n = p.multiply(q);
BigInteger n2 = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
BigInteger e = generateE(n2);
BigInteger d = e.modInverse(n2); // Here's the multiplicative inverse
System.out.println("Encryption keys are: " + e + ", " + n);
System.out.println("Decryption keys are: " + d + ", " + n);
}
public static BigInteger generateE(BigInteger fiofn)
{
int y, intGCD;
BigInteger e;
BigInteger gcd;
Random x = new Random();
do {
y = x.nextInt(fiofn.intValue()-1);
String z = Integer.toString(y);
e = new BigInteger(z);
gcd = fiofn.gcd(e);
intGCD = gcd.intValue();
}
while(y <= 2 || intGCD != 1);
return e;
}
}
OUTPUT:
Enter a Prime number: 5
Enter another prime number: 11
Encryption keys are: 33, 55
Decryption keys are: 17, 55
9. Diffie-Hellman
AIM: Implement the Diffie-Hellman Key Exchange mechanism using HTML andJavaScript.
Consider the end user as one of the parties (Alice) and the JavaScript application as other
party (bob).
ALGORITHM:
STEP-1: Both Alice and Bob shares the same public keys g and p.
STEP-2: Alice selects a random public key a.
STEP-3: Alice computes his secret key A as ga mod p.
STEP-4: Then Alice sends A to Bob.
STEP-5: Similarly Bob also selects a public key b and computes his secret key as B
and sends the same back to Alice.
STEP-6: Now both of them compute their common secret key as the other one’s secret
key power of a mod p.
PROGRAM:
import java.io.*;
import java.math.BigInteger;
class Diffie
{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter prime number:");
BigInteger p=new BigInteger(br.readLine());
System.out.print("Enter primitive root of "+p+":");
BigInteger g=new BigInteger(br.readLine());
System.out.println("Enter value for x less than "+p+":");
BigInteger x=new BigInteger(br.readLine());
BigInteger R1=g.modPow(x,p);
System.out.println("R1="+R1);
System.out.print("Enter value for y less than "+p+":");
BigInteger y=new BigInteger(br.readLine());
BigInteger R2=g.modPow(y,p);
System.out.println("R2="+R2);
BigInteger k1=R2.modPow(x,p);
System.out.println("Key calculated at Alice's side:"+k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Bob's side:"+k2);
System.out.println("deffie hellman secret key Encryption has Taken");
}
OUTPUT
Enter prime number:
11
Enter primitive root of 11:7
Enter value for x less than 11:
3
R1=2
Enter value for y less than 11:6
R2=4
Key calculated at Alice's side:9
Key calculated at Bob's side:9
deffie hellman secret key Encryption has Taken
//Another Program
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator; import
java.security.SecureRandom;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;
public class DiffeHellman
{
public final static int pValue = 47;
public final static int gValue = 71;
public final static int XaValue = 9;
public final static int XbValue = 14;
public static void main(String[] args) throws Exception { //
TODO code application logic here
BigInteger p = new BigInteger(Integer.toString(pValue));
BigInteger g = new BigInteger(Integer.toString(gValue));
BigInteger Xa = new
BigInteger(Integer.toString(XaValue));
BigIntegerXb =new BigInteger(Integer.toString(XbValue));
createKey();
intbitLength = 512; // 512 bits
SecureRandom rnd = new SecureRandom();
p = BigInteger.probablePrime(bitLength, rnd);
g = BigInteger.probablePrime(bitLength, rnd);
createSpecificKey(p, g);
}
public static void createKey() throws Exception {
KeyPairGenerator kpg = KeyPairGenerator.getInstance("DiffieHellman");
kpg.initialize(512);
KeyPair kp = kpg.generateKeyPair();
KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),
DHPublicKeySpec.class);
System.out.println("Public key is: " +kspec);
}
public static void createSpecificKey(BigInteger p, BigInteger g) throws Exception
{
KeyPairGeneratorkpg =KeyPairGenerator.getInstance("DiffieHellman");
DHParameterSpecparam = new DHParameterSpec(p, g);
kpg.initialize(param);
KeyPair kp = kpg.generateKeyPair();
KeyFactory kfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec kspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),
DHPublicKeySpec.class);
System.out.println("\nPublic key is : " +kspec);
}
}
OUTPUT:
Public key is: javax.crypto.spec.DHPublicKeySpec@5afd29
Public key is: javax.crypto.spec.DHPublicKeySpec@9971ad
10. SHA-1
AIM: Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
ALGORITHM:
STEP-1: Read the 256-bit key values.
STEP-2: Divide into five equal-sized blocks named A, B, C, D and E.
STEP-3: The blocks B, C and D are passed to the function F.
STEP-4: The resultant value is permuted with block E.
STEP-5: The block A is shifted right by ‘s’ times and permuted with the result of step-4.
STEP-6: Then it is permuted with a weight value and then with some other key pair and
taken as the first block.
STEP-7: Block A is taken as the second block and the block B is shifted by ‘s’ times and
taken as the third block.
STEP-8: The blocks C and D are taken as the block D and E for the final output.
PROGRAM:
import java.security.*;
public class SHA1 {
public static void main(String[] a) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " +md.getAlgorithm());
System.out.println(" Provider = " +md.getProvider());
System.out.println(" ToString = " +md.toString());
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\""+input+"\") = " +bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\"" +input+"\") = " +bytesToHex(output));
System.out.println(""); }
catch (Exception e) {
ALGORITHM:
STEP-1: Read the 128-bit plain text.
STEP-2: Divide into four blocks of 32-bits named as A, B, C and D.
STEP-3: Compute the functions f, g, h and i with operations such as, rotations,
permutations, etc,.
STEP-4: The output of these functions are combined together as F and performed
circular shifting and then given to key round.
STEP-5: Finally, right shift of ‘s’ times are performed and the results are combined
together to produce the final output.
PROGRAM:
import java.security.*;
public class MD5 {
public static void main(String[] a) {
// TODO code application logic here
try {
MessageDigest md = MessageDigest.getInstance("MD5");
System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " +md.getAlgorithm());
System.out.println(" Provider = " +md.getProvider());
System.out.println(" ToString = " +md.toString());
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\""+input+"\") = " +bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("MD5(\"" +input+"\") = "+bytesToHex(output));
System.out.println("");
}
catch (Exception e) {
System.out.println("Exception: " +e);
}
}
public static String bytesToHex(byte[] b)
{
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
StringBuffer buf = new StringBuffer();
for (int j=0; j<b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]); }
return buf.toString(); } }
OUTPUT:
Message digest object info:
Algorithm = MD5
Provider = SUN version 1.6
ToString = MD5 Message Digest from SUN, <initialized> MD5("") =
D41D8CD98F00B204E9800998ECF8427E MD5("abc") =
900150983CD24FB0D6963F7D28E17F72 MD5("abcdefghijklmnopqrstuvwxyz") =
C3FCD3D76192E4007DFB496CCA67E13B