IT6712 Security Lab Record
IT6712 Security Lab Record
A.Ceasar Cipher
Aim:
To write a program for encrypting a plain text and decrypting a cipher text using Caesar
Cipher (shift cipher) using substitution technique
a) Find ASCII value of current character and subtract key with that.
b) Find, SumASCII(current) MOD 65.
c) Subtract key from sum, Diff Sum – key
d) If Diff is less than zero, Diff26-Diff
e) Compute Decrypted character by adding 65, Decrypted65+ Diff
f) Add Decrypted character to PlainText.
Step 6:Repeat step 5 until all characters Decrypted
Program:
import java.util.Scanner;
plainText = plainText.toLowerCase();
cipherText += replaceVal;
return cipherText;
cipherText = cipherText.toLowerCase();
if (keyVal < 0)
plainText += replaceVal;
return plainText;
message = sc.next();
System.out.println(encrypt(message, 25));
sc.close();
}
Output:
Plain Text: the quick brown fox jumps over the lazy dog
Plain Text: the quick brown fox jumps over the lazy dog
Result:
Thus the program for encrypting a plain text and decrypting a cipher text using Caesar
Cipher substitution technique is executed successfully.
EX.NO:1B Play Fair Cipher
DATE:
Aim:
To write a program to encrypt a plain text and decrypt a cipher text using play fair Cipher
substitution technique
a. If R1=R2, then the characters at the position (R1, (C1+1%5)) and (R2,(C2+1%5))
are the equivalent Cipher Text.
b. Otherwise, the characters at location (R1, C2) and (R2, C1) are the equivalent
Cipher Text.
a. If R1=R2, then the characters at the position (R1, (C1-1%5)) and (R2, (C2-1%5))
are the equivalent Plaintext.
b. Otherwise, the characters at location (R1, C2) and (R2, C1) are the equivalent
Cipher Text.
Program:
import java.util.*;
class Basic{
String allChar="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
boolean indexOfChar(char c)
if(allChar.charAt(i)==c)
return true;
return false;
class PlayFair{
boolean repeat(char c)
if(!b.indexOfChar(c))
return true;
{
if(keyMatrix[i][j]==c || c=='J'
return true;
return false;
key=key.toUpperCase();
key=key.replaceAll("J", "I");
int a=0,b=0;
if(!repeat(key.charAt(k)))
keyMatrix[a][b++]=key.charAt(k);
if(b>4)
b=0;
a++;
}
char p='A';
while(a < 5)
while(b < 5)
if(!repeat(p))
keyMatrix[a][b++]=p;
p++;
b=0;
a++;
System.out.print("-------------------------Key Matrix-------------------");
System.out.println();
System.out.print("\t"+keyMatrix[i][j]);
System.out.println("\n---------------------------------------------------------");
}
int rowPos(char c)
if(keyMatrix[i][j]==c)
return i;
return -1;
int columnPos(char c)
if(keyMatrix[i][j]==c)
return j;
return -1;
}
String encryptChar(String plain)
plain=plain.toUpperCase();
char a=plain.charAt(0),b=plain.charAt(1);
String cipherChar="";
int r1,c1,r2,c2;
r1=rowPos(a);
c1=columnPos(a);
r2=rowPos(b);
c2=columnPos(b);
if(c1==c2)
++r1;
++r2;
if(r1>4)
r1=0;
if(r2>4)
r2=0;
cipherChar+=keyMatrix[r1][c2];
cipherChar+=keyMatrix[r2][c1];
else if(r1==r2)
++c1;
++c2;
if(c1>4)
c1=0;
if(c2>4)
c2=0;
cipherChar+=keyMatrix[r1][c1];
cipherChar+=keyMatrix[r2][c2];
else{
cipherChar+=keyMatrix[r1][c2];
cipherChar+=keyMatrix[r2][c1];
return cipherChar;
insertKey(key);
String cipherText="";
plainText=plainText.replaceAll("j", "i");
plainText=plainText.toUpperCase();
int len=plainText.length();
// System.out.println(plainText.substring(1,2+1));
if(len/2!=0)
plainText+="X";
++len;
cipherText+=encryptChar(plainText.substring(i,i+2));
cipherText+=" ";
return cipherText;
cipher=cipher.toUpperCase();
char a=cipher.charAt(0),b=cipher.charAt(1);
String plainChar="";
int r1,c1,r2,c2;
r1=rowPos(a);
c1=columnPos(a);
r2=rowPos(b);
c2=columnPos(b);
if(c1==c2)
--r1;
--r2;
if(r1 < 0)
r1=4;
if(r2 < 0)
r2=4;
plainChar+=keyMatrix[r1][c2];
plainChar+=keyMatrix[r2][c1];
else if(r1==r2)
--c1;
--c2;
if(c1 < 0)
c1=4;
if(c2 < 0)
c2=4;
plainChar+=keyMatrix[r1][c1];
plainChar+=keyMatrix[r2][c2];
else{
plainChar+=keyMatrix[r1][c2];
plainChar+=keyMatrix[r2][c1];
return plainChar;
String plainText="";
cipherText=cipherText.replaceAll("j", "i");
cipherText=cipherText.toUpperCase();
int len=cipherText.length();
plainText+=decryptChar(cipherText.substring(i,i+2));
plainText+=" ";
return plainText;
class PlayFairCipher{
String key,cipherText,plainText;
System.out.println("Enter plaintext:");
plainText=scn.nextLine();
System.out.println("Enter Key:");
key=scn.nextLine();
cipherText=p.Encrypt(plainText,key);
System.out.println("Encrypted text:");
System.out.println("---------------------------------------------------------\n"+cipherText);
System.out.println("---------------------------------------------------------");
System.out.println("Decrypted text:" );
System.out.println("---------------------------------------------------------\n"+encryptedText);
System.out.println("---------------------------------------------------------");
Output:
Enter plaintext:
TEXT
Enter Key:
-------------------------Key Matrix-------------------
A B C D E
F G H I K
L M N O P
Q R S T U
V W X Y Z
---------------------------------------------------------
Encrypted text:
---------------------------------------------------------
UD YS
---------------------------------------------------------
Decrypted text:
---------------------------------------------------------
TE XT
---------------------------------------------------------
Result:
Thus to implement a program for encrypt a plain text and decrypt a cipher text using
play fair Cipher substitution technique is executed successfully.
EX.NO:1C C. Hill Cipher
DATE:
Aim:
To write a program to encrypt and decrypt using the Hill cipher substitution technique
Program:
import java.io.*;
import java.util.*;
import java.io.*;
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]; }
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]; }
for(int i=0;i<3;i++){
System.out.print((char)(decrypt[i][0]%26+97));
}
System.out.print("\n");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j] = sc.nextFloat();
for(int i=0;i<3;i++)
mes[i][0] = msg.charAt(i)-97;
float p,q;
float[][] c = a;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
//a[i][j]=sc.nextFloat();
if(i==j)
b[i][j]=1;
else b[i][j]=0;
for(int k=0;k<3;k++) {
for(int i=0;i<3;i++) {
p = c[i][k];
q = c[k][k];
for(int j=0;j<3;j++) {
if(i!=k) {
c[i][j] = c[i][j]*q-p*c[k][j];
b[i][j] = b[i][j]*q-p*b[k][j];
}}}}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
b[i][j] = b[i][j]/c[i][i]; }
System.out.println("");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++)
System.out.print("\n"); }
}}
Output:
Inverse Matrix is :
-1.75 1.0 1.375
3.125 -1.5 -2.5625
-1.125 0.5 1.0625
Result:
Thus to implement a program to encrypt and decrypt using the Hill cipher substitution technique
is executed successfully.
Aim:
To write a program for encryption and decryption using vigenere cipher substitution
technique
char c = text.charAt(i);
continue;
j = ++j % key.length();
return res;
text = text.toUpperCase();
char c = text.charAt(i);
continue;
j = ++j % key.length();
return res;
}
String message = "Beware the Jabberwock, my son! The jaws that bite, the claws that
catch!";
Output :
String: beware the jabberwock, my son! the jaws that bite, the claws that catch!
Encrypted message:
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted message:
BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH
Result:
Thus the program for encryption and decryption using vigenere cipher
substitution technique is executed successfully.
DATE:
Aim:
To write a program for encryption and decryption using rail fence transposition technique
Procedurefor Encryption:
Program:
import java.util.*;
String text = "IF YOU CAN READ THIS YOU ARE GENIUS";
System.out.println(enc);
}
public static String RFCEncryption(String text, String keytext) {int[] arrange =
arrangeKey(keytext);
int move = 1;
int count = 0;
rfp[x][y] = ".";
if ((move % 2) != 0) {
move = 2;
} else
count++;
} else if ((move % 2) == 0) {
if (count == 0) {
move = 1;
count = 1;
} else
count--;
if (rfp[x][y].equals(" "))
rfp[x][y] = ""+Character.toUpperCase(RandomAlpha());
// display
System.out.println();
System.out.println();
System.out.println();
if (x == arrange[y]) {
if (!".".equals(rfp[y][u])) {
cb.append(rfp[y][u]);
Arrays.sort(keys);
if (keys[x].equals(key.charAt(y) + "")) {
num[y] = x;
break;
}
System.out.println(Arrays.toString(num));
return num;
Output:
[3, 1, 2, 4]
I.....S.....E.....I.....L.....E....
.F...U.C...R.A...H.S...U.A...G.N...
..T.O...A.M...D.T...X.O...R.F...I.S
...Y.....N.....Q.....Y.....E.....U.
FUCRAHSUAGNTOAMDTXORFISISEILE
Result:
Thus to implement a program for encryption and decryption using rail fence transposition
technique is executed successfully.
Algorithm:
Step 1: The 64-bit plain text block is handed over to an Initial Permutation (IP)
function.
Step 2: The Initial Permutation (IP) produces two halves of the permuted block;
say Left Plain Text (LPT) and Right Plain Text (RPT).
Step 3: Now each of LPT and RPT go through 16 rounds of encryption process.
Step 4: In the end. LPT and RPT are joined and a Final Permutation (FP) is
performed on the combined block.
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);
}
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;
}
Output:
Result:
Thus the program for data encryption standard to carry out the encryption and decryption
was successfully executed and verified.
DATE:
Aim :
Algorithm:
Step 1: Select e = 5, which is a valid choice since there is no number that is common
factor of 5 and (p − 1)(q − 1) = 6 × 12 = 72, except for 1.
Step 1: The pair of numbers (n, e) = (91, 5) forms the public key and can be made
available to anyone whom we wish to be able to send us encrypted messages.
Step 1: Input p = 7, q = 13, and e = 5 to the Extended Euclidean Algorithm. The output
will be d = 29.
Step 1: Hence, public key is (91, 5) and private keys is (91, 29).
Program:
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger e;
private BigInteger d;
private Random r;
public RSA()
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength / 2, r);
e.add(BigInteger.ONE);
d = e.modInverse(phi);
this.e = e;
this.d = d;
this.N = N;
@SuppressWarnings("deprecation")
String teststring;
teststring = in.readLine();
+ bytesToString(teststring.getBytes()));
// encrypt
// decrypt
test += Byte.toString(b);
return test;
// Encrypt message
// Decrypt message
}
Output:
19602-30114-23113-4629-89-98119659-41-116-24-1526-848-6614-56-128-123-7810820118-
30-5168-38100616267243-901090-26-92-95-917753-118-75-79-13-26454766-41-739-328769-
8986-1266344-84-12-81121-85-5390115-78-69-5260-55-113-76-8070-1950-109119-60117-
12511614-12399127727-1118911537438613-798-7638-43867-8864-80-23-763970645-45-897-
65-4567321-6547-987-0987654-56473647-324156-89-7645-5647-30-23451764898-5647-89-
7645-435678-345-67-567-345-34-89-7654-34567235-764-98-675432
Result:
Thus the program for RSA Algorithm to carry out the encryption was successfully
executed and verified
EXNO: 2.C C. Diffiee Hellman Key Exchange Algorithm
DATE:
Aim:
Algorithm:
Program:
import java.io.*;
import java.math.BigInteger;
class Diffie
BigInteger R1=g.modPow(x,p);
System.out.println("R1="+R1);
BigInteger R2=g.modPow(y,p);
System.out.println("R2="+R2);
BigInteger k1=R2.modPow(x,p);
BigInteger k2=R1.modPow(y,p);
}
Output:
Result:
Thus the program for Diffiee Hellman Key Exchange Algorithm to carry out the encryption
was successfully executed and verified .
EXNO: 2.D D. Implement Message Digest Algorithm (MD5)
DATE:
Aim:
Algorithm:
The message is "padded" (extended) so that its length (in bits) is congruent to
448, modulo 512. That is, the message is extended so that it is just 64 bits shy of being a multiple
of 512 bits long. Padding is always performed, even if the length of the message is already
congruent to 448, modulo 512. Padding is performed as follows: a single "1" bit is appended to
the message, and then "0" bits are appended so that the length in bits of the padded message
becomes congruent to 448, modulo 512. In all, at least one bit and at most 512 bits are appended.
A 64-bit representation of b (the length of the message before the padding bits
were added) is appended to the result of the previous step. In the unlikely event that b is greater
than 2^64, then only the low-order 64 bits of b are used. (These bits are appended as two 32-bit
words and appended low-order word first in accordance with the previous conventions.) At this
point the resulting message (after padding with bits and with b) has a length that is an exact
multiple of 512 bits. Equivalently, this message has a length that is an exact multiple of 16 (32-
bit) words. Let M[0 ... N-1] denote the words of the resulting message, where N is a multiple of
16.
A four-word buffer (A,B,C,D) is used to compute the message digest. Here each
of A, B, C, D is a 32-bit register. These registers are initialized to the following values in
hexadecimal, low-order bytes first):
word A: 01 23 45 67
word B: 89 ab cd ef
word C: fe dc ba 98
word D: 76 54 32 10
Step 4. Process Message in 16-Word Blocks:
We first define four auxiliary functions that each take as input three 32-bit
words and produce as output one 32-bit word.
F(X,Y,Z) = XY v not(X) Z
G(X,Y,Z) = XZ v Y not(Z)
Program:
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5
{
public static String getMD5(String input)
{
Try
{
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger number = new BigInteger(1, messageDigest);
String hashtext = number.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (hashtext.length() < 32)
{
hashtext = "0" + hashtext;
}
return hashtext;
}
catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
}
Input: welcome
Output: 6d6ede273f751292f8842f8ce08eaf0f1
Result:
Thus the program for Message Digest Algorithm (MD5) to carry out the encryption was
successfully executed and verified.
EXNO: 2.E E. Implement Secure Hash Function (SHA-1)
DATE:
Aim:
Algorithm:
64 bits are appended to the end of the padded message. These bits hold the
binary format of 64 bits indicating the length of the original message.
H0 = 0x67452301
H1 = 0xEFCDAB89
H2 = 0x98BADCFE
H3 = 0x10325476
H4 = 0xC3D2E1F0
This is the main task of SHA1 algorithm which loops through the padded and
appended message in 512-bit blocks.
Program:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.*;
int two_halfs = 0;
do {
if ((0 <= halfbyte) && (halfbyte <= 9))
else
return buf.toString();
MessageDigest md;
md = MessageDigest.getInstance("SHA-1");
md.update(text.getBytes("iso-8859-1"), 0, text.length());
sha1hash = md.digest();
return convertToHex(sha1hash);
System.out.println("Enter string:");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e)
e.printStackTrace();
Output:
Result:
Thus the program for Secure Hash Function (SHA) to carry out the encryption and
decryption was successfully executed and verified.
EXNO:3 Implement the SIGNATURE SCHEME – Digital
Signature Standard
DATE:
Aim:
Algorithm:
Step 1 : The private key is converted from the private key file encoded in PKCS#8 format.
The public key is not needed for generating the signature file.
Step 2 : The private key is converted from the private key file encoded in PKCS#8 format. The
public key is not needed for generating the signature file.
Step 4 : The initSign(privateKey) method is used at the beginning to initialize the signature object
with the private key.
Step 5 : The update() method is used repeatedly to hash the message file in chunks.
Step 6 : The sign() method is used at the end to generate the signature as a byte array from the
final hash value.
Program:
import java.security.KeyPairGenerator;
import java.security.KeyPair;
import java.security.PublicKey;
import java.security.PrivateKey;
import java.security.Signature;
import java.io.FileInputStream;
import java.util.*;
public class DigSign {
private static byte[] sign(String datafile, PrivateKey prvKey, String sigAlg) throws
Exception {
sig.initSign(prvKey);
sig.update(dataBytes, 0, nread);
nread = fis.read(dataBytes);
};
return sig.sign();
private static boolean verify(String datafile, PublicKey pubKey, String sigAlg, byte[]
sigbytes) throws Exception {
sig.initVerify(pubKey);
sig.update(dataBytes, 0, nread);
nread = fis.read(dataBytes);
};
return sig.verify(sigbytes);
// Generate a key-pair
KeyPair kp = kpg.generateKeyPair();
}
}
Output:
Signature<in hex>::[B@11d50c0
Result:
Thus the program for Digital Signature Scheme to carry out the encryption and
decryption was successfully executed and verified.