01 - Ccs Hari Recod

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

TABLE OF CONTENTS

S.N DATE TITLE OF THE PROGRAM MARK SIGN


O S
1 Perform encryption, decryption using the
following substitution techniques.
a Caesar Cipher
b Playfair Cipher
c Hill Cipher
2 Perform encryption and decryption using
following transposition techniques.
a Rail fence
b Row & Column Transformation
3 Data Encryption Standard (DES)
4 Advanced Encryption Standard (AES)
5 RSA Algorithm
6 Diffie-Hellman Key Exchange Algorithm
7 Secure Hash Algorithm (SHA-1)
8 MD-5 Algorithm

9 Digital Signature Standard (DSA)


Reg. No: 411622149022
Ex.No. : 1a CAESAR CIPHER
Date :

AIM:
To implement a Caesar cipher substitution technique in Java.

ALGORITHM:
1. Assign the 26 letters in alphabet to the variable named ALPHABET.
2. Convert the plaintext letters into lowercase.
3. To encrypt a plaintext letter, the first set of plaintext letters and slides it to LEFT by the
number of positions of the secret shift.
4. The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler
underneath.
5. On receiving the ciphertext, the receiver who also knows the secret shift, positions his
sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift
number, 3 in this case.
6. Then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath.

PROGRAM:
import java.util.Scanner;
public class ceasercipher
{
public static final String ALPHABET="abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String plainText,int shiftKey)
{
plainText=plainText.toLowerCase();
String cipherText="";
for (int i=0; i<plainText.length();i++)
{
int charPosition=ALPHABET.indexOf(plainText.charAt(i));
int keyVal=(shiftKey+charPosition)%26;
char replaceVal=ALPHABET.charAt(keyVal);
cipherText+=replaceVal;
}
return cipherText;
}
public static String decrypt(String cipherText,int shiftKey)
{
cipherText = cipherText.toLowerCase();
String plainText = "";
for(int i=0;i<cipherText.length();i++)
{
int charPosition= ALPHABET. indexOf(cipherText. charAt(i));
int keyVal=(charPosition-shiftKey)%26;
if (keyVal< 0)
{
keyVal=ALPHABET.length()+keyVal;
}
char replaceVal=ALPHABET.charAt(keyVal);
plainText+=replaceVal;
Reg. No: 411622149022
Reg. No: 411622149022

}
return plainText;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Plain text for Encryption: ");
String message=new String();
message=sc.next();
System.out.println("Encrypted message:Cipher Text="+encrypt(message,3));
System.out.println("Decrypted message:Plain Text="+decrypt
(encrypt( message,3),3));
sc.close();
}
}

OUTPUT:
F:\bin>javac ceasercipher.java F:
\bin>java ceasercipher
Enter the Plain text for Encryption:
covid
Encrypted message:Cipher Text=frylg
Decrypted message:Plain Text=covid

RESULT:
Thus the Caesar cipher substitution technique was implemented and executed
successfully.
Reg.
Reg. No:
No: 411622149022
411622149022

Ex.No. : 1b PLAYFAIR CIPHER


Date :

AIM:
To implement a Playfair cipher substitution technique in Java.

ALGORITHM:
1. Read the keyword.
2. Then create the key table of 5x5 grid of alphabets.
3. Read the word to encrypt.
4. Ifthe input word should be even and then process it.
5. Then the plaintext message is split into pairs of two letters (digraphs).
6. Ifboththe letters are in the same column, take the letter below each one.
7. Ifboth letters are in the same row, take the letter to the right of each one.
8. If neither of the preceding two rules are true, form a rectangle with the two letters and
take the letters on the horizontal opposite corner of the rectangle.

PROGRAM:
import java.util.Scanner;
public class Playfair1
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter keyword: ");
String key=in.nextLine();
System.out.print("Enter message to encrypt: ");
String msg=in.nextLine();
PFEncryption pfEncryption=new PFEncryption();
pfEncryption.makeArray(key);
msg=pfEncryption.manageMessage(msg);
pfEncryption.doPlayFair(msg, "Encrypt");
String en=pfEncryption.getEncrypted();
System.out.println("Encrypting. .. \n\nThe encrypted text is: " + en);
System.out.println("=============================");
pfEncryption.doPlayFair(en, "Decrypt");
System.out.print("\nDecrypting... \n\nThe encrypted text is: " +
pfEncryption.getDecrypted());
}
}
class PFEncryption
{
private char [][] alphabets= new char[5][5];
private char[] uniqueChar= new char[26];
private String ch="ABCDEFGHIKLMNOPQRSTUVWXYZ";
private String encrypted="";
private String decrypted="";
void makeArray(String keyword)
Reg. No: 411622149022

{
keyword=keyword.toUpperCase().replace("J","I");
boolean present, terminate=false;
int val=0;
int uniqueLen;
for (int i=0; i<keyword.length(); i++)
{
present=false;
uniqueLen=0;
if (keyword.charAt(i)!= ' ')
{
for (int k=0; k<uniqueChar.length; k++)
{
if (Character.toString(uniqueChar[k])==null)
{
break;
}
uniqueLen++;
}
for (int j=0; j<uniqueChar.length; j++)
{
if (keyword.charAt(i)==uniqueChar[j])
{
present=true;
}
}
if (!present)
{
uniqueChar[val]=keyword.charAt(i);
val++;
}
}
ch=ch.replaceAll(Character.toString(keyword.charAt(i)), "");
}
for (int i=0; i<ch.length(); i++)
{

uniqueChar[val]=ch.charAt(i);
val++;
}
val=0;

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


{
for (int j=0; j<5; j++)
{
alphabets[i][j]=uniqueChar[val];
val++;
System.out.print(alphabets[i][j] + "\t");
}
System.out.println();
}
Reg. No: 411622149022

}
String manageMessage(String msg)
{
int val=0;
int len=msg.length()-2;
String newTxt="";
String intermediate="";
while (len>=0)
{
intermediate=msg.substring(val, val+2);
if (intermediate.charAt(0)==intermediate.charAt(1))
{
newTxt=intermediate.charAt(0) + "x" + intermediate.charAt(1);
msg=msg.replaceFirst(intermediate, newTxt);
len++;
}
len-=2;
val+=2;
}
if (msg.length()%2!=0)
{
msg=msg+'x';
}
return msg.toUpperCase().replaceAll("J","I").replaceAll(" ","");
}
void doPlayFair(String msg, String tag)
{
int val=0;
while (val<msg.length())
{
searchAndEncryptOrDecrypt(msg.substring(val,val+2),tag);
val+=2;
}}
void searchAndEncryptOrDecrypt(String doubblyCh, String tag)
{
char ch1=doubblyCh.charAt(0);
char ch2=doubblyCh.charAt(1);
int row1=0, col1=0, row2=0, col2=0;
for (int i=0; i<5; i++)
{
for (int j=0; j<5; j++)
{
if (alphabets[i][j]==ch1)
{
row1=i;
col1=j;
}
else if (alphabets[i][j]==ch2)
{
row2=i;
Reg. No: 411622149022

col2=j;
} } }
if (tag=="Encrypt")
encrypt(row1, col1, row2, col2);
else if(tag=="Decrypt")
decrypt(row1, col1, row2, col2);
}
void encrypt(int row1, int col1, int row2, int col2)
{
if (row1==row2)
{
col1=col1+1;
col2=col2+1;
if (col1>4)
col1=0;
if (col2>4)
col2=0;
encrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row1][col2]));
}
else if(col1==col2)
{
row1=row1+1;
row2=row2+1;
if (row1>4)
row1=0;
if (row2>4)
row2=0;
encrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row2][col1]));
}
else
{ encrypted+=(Character.toString(alphabets[row1][col2])+
Character.toString(alphabets[row2][col1]));
}}
void decrypt(int row1, int col1, int row2, int col2)
{
if (row1==row2)
{
col1=col1-1;
col2=col2-1;
if (col1<0)
col1=4;
if (col2<0)
col2=4;
decrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row1][col2]));
}
else if(col1==col2)
{
Reg. No: 411622149022

row1=row1-1;
row2=row2-1;
if (row1<0)
row1=4;
if (row2<0)
row2=4;
decrypted+=(Character.toString(alphabets[row1][col1])+
Character.toString(alphabets[row2][col1]));
}
else
{
decrypted+=(Character.toString(alphabets[row1][col2])+
Character.toString(alphabets[row2][col1]));
}}
String getEncrypted( )
{
return encrypted;
}
String getDecrypted( )
{
return decrypted;
}}

OUTPUT:
F:\bin>javac Playfair1.java

F:\bin>java Playfair1
Enter keyword: INFOSEC
Enter message to encrypt: cryptography
I N F O S
E C A B D
G H K L M
P Q R T U
V W X Y Z
Encrypting....

The encrypted text is: AQVTYBKPERLW


=======================================

Decrypting....

The encrypted text is: CRYPTOGRAPHY

RESULT:
Thus the Playfair cipher substitution technique was implemented and executed
successfully.
Reg.
Reg. No:
No: 411622149022
411622149022

Ex.No. : 1c HILL CIPHER


Date :

AIM:
To implement a Hill cipher substitution technique in Java.

ALGORITHM:
1. Obtain a plaintext message to encode in standard English with no spaces.
2. Split the plaintext into group of length three. To fill this, add X at the end.
3. Convert each group of letters with length three into plaintext vectors.
4. Replace each letter by the number corresponding to its position in the alphabet i.e.
A=1, B=2, C=3…Z=0.
5. Create the keyword in a 3*3 matrix.
6. Multiply the two matrices to obtain the cipher text of length three.
7. For decryption, convert each entry in the ciphertext vector into its plaintext vector by
multiplying the cipher text vector and inverse of a matrix.
8. Thus plain text is obtained fromcorresponding plaintext vector by corresponding
position in the alphabet.

PROGRAM:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class hillcipher
{
//the 3x3 key matrix for 3 characters at once
public static int[][] keymat = new int[][]
{
{ 1, 2, 1 },
{ 2, 3, 2 },
{ 2, 2, 1 },
};
public static int[][] invkeymat = new int[][]
{
{ -1, 0, 1 },
{ 2, -1, 0 },
{ -2, 2, -1},
};
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

public static void main(String[] args)


{
String text,outtext ="",outtext1="";
int ch, n;
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Plain text for Encryption: ");
//String text=new String();
text=sc.next();

text = text.toUpperCase();
text = text.replaceAll("\\s",""); //removing spaces
Reg. No: 411622149022

n = text.length() % 3; if(n!
=0)
{
for(int i = 1; i<= (3-n);i++)
{
text+= 'X';
}
}
System.out.println("Padded Text:" + text);
char[] ptextchars = text.toCharArray();
for(int i=0;i< text.length(); i+=3)
{
outtext += encrypt(ptextchars[i],ptextchars[i+1],ptextchars[i+2]);
}
System.out.println("Encypted Message: " + outtext);

char[] ptextchars1 = outtext.toCharArray();


for(int i=0;i< outtext.length(); i+=3)
{
outtext1 += decrypt(ptextchars1[i],ptextchars1[i+1],ptextchars1[i+2]);
}
System.out.println("Decrypted Message: " + outtext1);
}

private static String encrypt(char a, char b, char c)


{
String ret = "";
int x,y, z;
int posa = (int)a - 65;
int posb = (int)b - 65;
int posc = (int)c - 65;
x = posa * keymat[0][0] + posb * keymat[1][0] + posc * keymat[2][0];
y = posa * keymat[0][1] + posb * keymat[1][1] + posc * keymat[2][1];
z = posa * keymat[0][2] + posb * keymat[1][2] + posc * keymat[2][2];
a = key.charAt(x%26);
b = key.charAt(y%26);
c = key.charAt(z%26);
ret = "" + a + b + c;
return ret;
}

private static String decrypt(char a, char b, char c)


{
String ret = "";
int x,y,z;
int posa = (int)a - 65;
int posb = (int)b - 65;
int posc = (int)c - 65;
x = posa * invkeymat[0][0]+ posb * invkeymat[1][0] + posc * invkeymat[2][0];
y= posa * invkeymat[0][1]+ posb * invkeymat[1][1] + posc * invkeymat[2][1];
Reg. No: 411622149022

z = posa * invkeymat[0][2]+ posb * invkeymat[1][2] + posc * invkeymat[2][2];


a = key.charAt((x%26<0)?(26+x%26):(x%26));
b = key.charAt((y%26<0)?(26+y%26):(y%26));
c = key.charAt((z%26<0)?(26+z%26):(z%26));
ret = "" + a + b + c;
return ret;
}
}

OUTPUT:
F:\bin>javac hillcipher.java

F:\bin>java hillcipher
Enter the Plain text for Encryption:
mothertheresa
Padded Text:MO THERTHERESAXX
Encypted Message: AAHXIGPPLJEROLR
Decrypted Message: MOTHERTHERESAXX

F:\bin>java hillcipher
Enter the Plain text for Encryption:
hilcipher
Padded Text:HILCIPHER
Encypted Message: TIIWGHXIG
Decrypted Message: HILCIPHER

RESULT:
Thus the Hill cipher substitution technique was implemented and executed
successfully.
Reg. No: 411622149022
Reg.
Reg. No:
No: 411622149022
411622149022

Ex.No. : 2a RAIL FENCE CIPHER


Date :

AIM:
To implement a rail fence transposition technique in Java.

ALGORITHM :
1. In the rail fence cipher, the plaintext is written downwards and diagonally on
successive "rails" of an imaginary fence, then moving up when we reach the bottom
rail.
2. When we reach the top rail, the message is written downwards again until the whole
plaintext is written out.
3. The message is then read off in rows.

PROGRAM:
class railfenceCipherHelper
{
int depth;
String encode(String msg, int depth) throws Exception
{
int r = depth;
int l = msg.length();
int c = l / depth; int
k = 0;
char mat[][] = new char[r][c];
String enc = "";
for (int i = 0; i< c; i++)
{
for (int j = 0; j < r; j++)
{
if (k != l)
{ mat[j][i] = msg.charAt(k++); }
else
{ mat[j][i] = 'X'; }
}}
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
enc += mat[i][j];
}}
return enc;
}
String decode(String encmsg, int depth) throws Exception
{
int r = depth;
int l = encmsg.length();
int c = l / depth;
int k = 0;
char mat[][] = new char[r][c];
Reg.
Reg. No:
No: 411622149022
411622149022

String dec = "";


for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
mat[i][j] = encmsg.charAt(k++);
}}
for (int i = 0; i< c; i++)
{
for (int j = 0; j < r; j++)
{
dec += mat[j][i];
}}
return dec;
}}
class railfencecipher
{
public static void main(String[] args) throws java.lang.Exception
{
railfenceCipherHelper rf = new railfenceCipherHelper();
String msg, enc, dec;
System.out.println("Enter the Plain text: ");
msg = System.console().readLine();
int depth = 2;
enc = rf.encode(msg, depth);
dec = rf.decode(enc, depth);
System.out.println("Plain Text:"+msg);
System.out.println("Encrypted Message-Cipher Text:"+enc);
System.out.printf("Decrypted Message-:"+dec);
}
}

OUTPUT:
F:\bin>javac railfencecipher.java
F:\bin>java railfencecipher
Enter the Plain text:
paulinefreeda
Plain Text:paulinefreeda
Encrypted Message-Cipher Text:puiereaalnfed
Decrypted Message-:paulinefreeda

RESULT:
Thus the Rail Fence Transposition Technique was implemented and executed
successfully.
Reg.
Reg. No:
No: 411622149022
411622149022

Ex.No. : 2b ROW AND COLUMN TRANSFORMATION TECHNIQUE


Date :

AIM:
To implement a rail fence transposition technique in Java.

ALGORITHM:
1. Consider the plain text hello world, and let us apply the simple columnar transposition
technique as shown below

h e l l
o w o r
l d

2. The plain text characters are placed horizontally and the cipher text is created with
vertical format as: holewdlo lr.
3. Now, the receiver has to use the same table to decrypt the cipher text to plain text.

EXAMPLE:

PROGRAM:
import java.util.*;
class TransCipher {
public static void main(String args[])
{ Scanner sc = new Scanner(System.in);
System.out.println("Enter the plain text");
String pl = sc.nextLine();
sc.close();
String s = "";
int start = 0;
for (int i= 0; i< pl.length(); i++)
{ if (pl.charAt(i) == ' ') {
s = s + pl.substring(start, i);
start = i + 1;
}
}
s = s + pl.substring(start);
System.out.print(s);
System.out.println();
// end of space deletion
Reg. No: 411622149022
Reg. No: 411622149022

int k = s.length();
int l = 0;
int col = 4;
int row = s.length() / col;
char ch[][] = new char[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
{ if (l < k) {
ch[i][j] = s.charAt(l);
l++;
} else {
ch[i][j] = '#';
}
}
}
char trans[][] = new char[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
{ trans[j][i] = ch[i][j];
}}
for (int i = 0; i < col; i++)
{ for (int j = 0; j < row; j++)
{
System.out.print(trans[i][j]);
}}
System.out.println();
}
}

OUTPUT:
F:\bin>javac TransCipher.java
F:\bin>java TransCipher
Enter the plain text
altrozcarshervin
altrozcarshervin
aorrlzsvtchiraen
a l t r
o z c a
r s h e
r v I n

RESULT:
Thus the Row and Column Transposition Technique was implemented and executed
successfully.
Reg. No: 411622149022

Ex.No. : 3 DATA ENCRYPTION STANDARD (DES)


Date :

AIM:
To apply Data Encryption Standard (DES) Algorithm for a practical application like
User Message Encryption.

ALGORITHM:
1. Create a DES Key.
2. Create a Cipher instance from Cipher class, specify the following information
and separated by a slash (/).
• Algorithm name
• Mode (optional)
• Padding scheme (optional)
3. Convert String into Byte[] array format.
4. Make Cipher inencrypt mode, and encrypt it with Cipher.doFinal() method.
5. Make Cipher indecrypt mode, and decrypt it with Cipher.doFinal() method.

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,encryptedata,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);
Reg. No: 411622149022

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);
Stringknum=String.valueOf(num);
byte[] knumb=knum.getBytes();
skey=getRawKey(knumb);
skeystring=new String(skey);
System.out.println("DES
SymmerticKey="+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


{
SecretKey seckey = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE,seckey);
byte[] encrypted=cipher.doFinal(clear);
return encrypted;
}

private static byte[] decrypt(byte[] raw,byte[] encrypted) throws Exception


{
SecretKey seckey = new SecretKeySpec(raw, "DES");
Reg. No: 411622149022
Reg. No: 411622149022

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


cipher.init(Cipher.DECRYPT_MODE,seckey);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
public static void main(String args[])
{
DES des=new DES();
}

OUTPUT:

RESULT:
Thus the java program for applying Data Encryption Standard (DES) Algorithm for a
practical application of User Message Encryption is written and executed successfully.
Reg.
Reg. No:
No: 411622149022
411622149022

Ex.No. : 4 AES ALGORITHM


Date :

AIM:
To apply Advanced Encryption Standard (AES) Algorithm for a practical application
like URL Encryption.

ALGORITHM:
1. AES is based on a design principle known as a substitution–permutation.
2. AES does not use a Feistel network like DES, it uses variant of Rijndael.
3. It has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.
4. AES operates on a 4 × 4 column- major order array of bytes, termed the state

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.getBytes
("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
Reg.
Reg. No:
No: 411622149022
411622149022

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;
}

public static void main(String[] args)

{ System.out.println("Enter the secret key:

");
String secretKey = System.console().readLine();

System.out.println("Enter the original URL: ");


String originalString = System.console().readLine();

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


StringdecryptedString = AES.decrypt(encryptedString, secretKey);

System.out.println("URL Encryption Using AES Algorithm\n -------------");


System.out.println("Original URL : " + originalString);
System.out.println("Encrypted URL : " + encryptedString);
System.out.println("Decrypted URL : " + decryptedString);
}
}

OUTPUT:
C:\Security Lab New\programs>java AES
Enter the secret key:
annaUniversity
Enter the original URL:
www.annauniv.edu
URL Encryption Using AES Algorithm

Original URL : www.annauniv.edu


Encrypted URL : vibpFJW6Cvs5Y+L7t4N6YWWe07+JzS1d3CU2h3mEvEg=
Decrypted URL : www.annauniv.edu
RESULT:
Thus the java program for applying Advanced Encryption Standard (AES) Algorithm
for a practical application of URL encryption is written and executed successfully.
Reg.
Reg. No:
No: 411622149022
411622149022

Ex.No. : 5 RSA ENCRYPTION ALGORITHM


Date :

AIM:
To implement a RSA algorithm using HTML and Javascript.

ALGORITHM:
1. Choose two prime number p and q.
2. Compute the value of n and t.
3. Find the value of public key e.
4. Compute the value of private key d.
5. Do the encryption and decryption
a. Encryption is given as,
c = te mod n
b. Decryption is givenas,
t = cd mod n

PROGRAM:
rsa.html
<html>
<head>
<title>RSA Encryption</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<h1>RSA Algorithm</h1>
<h2>Implemented Using HTML & Javascript</h2>
<hr>
<table>
<tr>
<td>Enter First Prime Number:</td>
<td><input type="number" value="53" id="p"></td>
</tr>
<tr>
<td>Enter Second Prime Number:</td>
<td><input type="number" value="59" id="q"></p> </td>
</tr>
<tr>
<td>Enter the Message(cipher text):<br>[A=1, B=2,...]</td>
<td><input type="number" value="89" id="msg"></p> </td>
</tr>
<tr>
<td>Public Key:</td>
<td><p id="publickey"></p> </td>
</tr>
<tr>
<td>Exponent:</td>
<td><p id="exponent"></p> </td>
</tr>
Reg. No: 411622149022

<tr>
<td>Private Key:</td>
<td><p id="privatekey"></p></td>
</tr>
<tr>
<td>Cipher Text:</td>
<td><p id="ciphertext"></p> </td>
</tr>
<tr>
<td><button onclick="RSA();">Apply RSA</button></td>
</tr>
</table> </center>
</body>
<script type="text/javascript">

function RSA()
{
var gcd, p, q, no, n, t, e, i, x;
gcd = function (a, b) { return (!b) ? a : gcd(b, a % b); };
p = document.getElementById('p').value;
q = document.getElementById('q').value;
no = document.getElementById('msg').value;
n = p * q;
t = (p - 1) * (q - 1);
for (e = 2; e < t; e++)
{
if (gcd(e, t) == 1)
{
break;
}
}
for (i = 0; i < 10; i++)
{
x= 1 + i* t
if (x % e == 0)
{
d = x / e;
break;
}
}
ctt = Math.pow(no, e).toFixed(0);
ct = ctt % n;
dtt = Math.pow(ct, d).toFixed(0);
dt = dtt % n;
document.getElementById('publickey').innerHTML = n;
document.getElementById('exponent').innerHTML = e;
document.getElementById('privatekey').innerHTML = d;
document.getElementById('ciphertext').innerHTML = ct;
}
</script>
Reg. No: 411622149022

</html>

OUTPUT:

RESULT:
Thus the RSA algorithm was implemented using HTML and Javascript and executed
successfully.
Reg.
Reg. No:
No: 411622149022
411622149022
Ex.No. : 6 DIFFIE-HELLMAN KEY EXCHANGE ALGORITHM
Date :

AIM:
To implement a Diffie-Hellman Key Exchange algorithm.

ALGORITHM:
1. Sender and receiver publicly agree to use a modulus p and base g which is a primitive
root modulo p.
x
2. Sender chooses a secret integer x then sends Bob R1 = g mod y
p
3. Receiver chooses a secretx integer y, then sends Alice R2 = g mod p
4. Sender computes k1 = B mod p
y
5. Receiver computes k2 = A mod p
6. Sender and Receiver now share a secret key.

PROGRAM:
import java.io.*;
import java.math.BigInteger;
class dh
{
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 Sender's side:"+k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Receiver's side:"+k2);
System.out.println("Diffie-Hellman secret key was calculated.");
}
}
Reg.
Reg. No:
No: 411622149022
411622149022

OUTPUT
C:\Security Lab New\programs>javac dh.java

C:\Security Lab New\programs>java dh


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 Sender's side:9
Key calculated at Receiver's side:9
Diffie-Hellman secret key was calculated.

RESULT:
Thus the Diffie-Hellman key exchange algorithm was implemented and executed
successfully.
Reg.
Reg. No:
No: 411622149022
411622149022

Ex.No. : 7 SHA-1 ALGORITHM


Date :

AIM:
To calculate the message digest of a text using the SHA-1 algorithm in Java.
ALGORITHM:
1. Append Padding bits.
2. Append Length - 64 bits are appended to the end.
3. Prepare Processing Functions.
4. Prepare Processing Constants.
5. Initialize Buffers.
6. Processing Message in 512-bit blocks (L blocks in total message).
PROGRAM:
import java.util.Scanner;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class sha1
{
public static void main(String[] args)throws NoSuchAlgorithmException
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String message = new String();
message = sc.next();
System.out.println("Mesage Digest is=");
System.out.println(sha1(message));
}
static String sha1(String input)throws NoSuchAlgorithmException
{
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for(int i = 0;i<result.length;i++)
{
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
OUTPUT:
C:\Security Lab New\programs>java sha1
Enter the String:
CORONA VIRUS DISEASE
Mesage Digest is=
7690b7ccb987f4b3f32d2b9e7e8a69db2d0ded02

RESULT:
Thus the Secure Hash Algorithm (SHA-1) has been implemented and executed
successfully.
Reg.
Reg. No:
No: 411622149022
411622149022

Ex.No. : 8 MD-5 ALGORITHM


Date :

AIM:
To calculate the message digest of a text using MD-5 Algorithm.

ALGORITHM:
1. Create aMessageDiges object named md using MessageDigest.getInstance("MD5").
2. Prompt the user to input the text for which they want to calculate the MD5 digest.

3. Convert the input text to a byte array text.getBytes( method. This converts the text into
using sequence of bytes. a

4. Update object md with the byte array representation of the input text using
MessageDiges
md.update(textBytes) This incorporates the bytes of the input text into the digest.
method.
5. Compute the MD5 digest by calling md.digest(). This finalizes the digest computation
and returns the resulting hash value as a byte array.
6. Initialize a StringBuilder named hexStrin to store the
hexadecimal representation of the MD5 digest..
hexStrin
7. After iterating through all will contain the complete hexadecimal representation
bytes, the MD5 digest. of

8. Print out the hexadecimal string representation stored in hexString. This is the MD5
digest of the input text.

PROGRAM:

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

import java.util.Scanner;

public class MD5Calculator {

public static String calculateMD5(String text)

{ try {

// Create MessageDigest instance for MD5

MessageDigest md = MessageDigest.getInstance("MD5");

// Add text bytes to digest

md.update(text.getBytes());

// Get the MD5 digest

byte[] digest = md.digest();


// Convert byte array to hexadecimal string
Reg. No: 411622149022
Reg. No: 411622149022

StringBuilder sb = new StringBuilder();

for (byte b : digest) {

sb.append(String.format("%02x", b));

return sb.toString();

} catch (NoSuchAlgorithmException e)

{ e.printStackTrace();

return null;

public static void main(String[] args)

{ Scanner scanner = new

Scanner(System.in);

System.out.print("Enter the text to calculate MD5 digest: ");

String text = scanner.nextLine();

String md5Digest = calculateMD5(text);

System.out.println("MD5 Digest: " + md5Digest);

scanner.close();

OUTPUT:

Enter the text to calculate MD5 digest: Hello, World!

MD5 Digest: ed076287532e86365e841e92bfc50d8c


Reg. No: 411622149022
Reg. No: 411622149022

Result
Thus the program to calculate the message digest of a text using MD-5 Algorithm. has been implemented and
executed successfully
Reg.
Reg. No:
No: 411622149004
411622149022

Ex. No. : 9 DIGITAL SIGNATURE STANDARD


Date:

AIM:
To implement Digital Signature Standard Algorithm.

ALGORITHM:
1. Declare the class and required variables.
2. Create the object for the class in the main program.
3. Access the member functions using the objects.
4. Implement the SIGNATURE SCHEME - Digital Signature Standard.
5. It uses a hash function.
6. The hash code is provided as input to a signature function along with a random number K
generated for the particular signature.
7. The signature function also depends on the sender„s private key.
8. The signature consists of two components.
9. The hash code of the incoming message is generated.
10. The hash code and signature are given as input to a verification function

PROGRAM:
import java.math.BigInteger;

class DSAAlg {

final static BigInteger one = new BigInteger("1");


final static BigInteger zero = new BigInteger("0");

public static BigInteger getNextPrime(String ans)


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

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;
}

public static void main(String[] args) {


String ans = "100"; // Example input, you can change this to any other number.
BigInteger nextPrime = getNextPrime(ans);
System.out.println("Next prime after " + ans + " is: " + nextPrime);
Reg. No: 411622149022
Reg. No: 411622149022

// Example usage of findQ method


BigInteger n = new BigInteger("123456789");
BigInteger q = findQ(n);
System.out.println("Q for " + n + " is: " + q);
}
}

Output
Next prime after 100 is: 101
Q for 123456789 is: 3

RESULT:
Thus the program to calculate the message digest of a text using Digital signature Algorithm has been
implemented and executed successfully, Reg. No: 411622149022

You might also like