0% found this document useful (0 votes)
17 views62 pages

Cryptography and Cyber Security Manual

The document outlines the implementation of three encryption techniques: Caesar Cipher, Playfair Cipher, and Hill Cipher in Java. Each section includes the aim, algorithm, program code, output results, and a brief conclusion confirming successful execution. Additionally, it covers security concepts, viva questions, and assignment tasks related to cryptography.

Uploaded by

krithick445
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views62 pages

Cryptography and Cyber Security Manual

The document outlines the implementation of three encryption techniques: Caesar Cipher, Playfair Cipher, and Hill Cipher in Java. Each section includes the aim, algorithm, program code, output results, and a brief conclusion confirming successful execution. Additionally, it covers security concepts, viva questions, and assignment tasks related to cryptography.

Uploaded by

krithick445
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

1

EX. NO. 1A PERFORM ENCRYPTION, DECRYPTION USING CAESAR CIPHER


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

ALGORITHM:
Step 1. Assign the 26 letters in alphabet to the variable named ALPHABET.
Step 2. Convert the plaintext letters into lowercase.
Step 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.
Step 4. The plaintext letter is then encrypted to the cipher text letter on the sliding ruler
underneath.
Step 5. On receiving the cipher text, the receiver who also knows the secret shift,
positions his sliding ruler underneath the cipher text alphabet and slides it to RIGHT by
the agreed shift number, 3 in this case.
Step 6. Then replaces the cipher text letter by the plaintext letter on the sliding ruler
underneath.

PROGRAM:
class caesarCipher
{
public static String encode(String enc, int offset)
{ offset = offset % 26 + 26;
StringBuilder encoded = new StringBuilder(); for (char i : enc.toCharArray()) {
if (Character.isLetter(i)) {
if (Character.isUpperCase(i)) {
encoded.append((char) ('A' + (i - 'A' + offset) % 26));
} else {
encoded.append((char) ('a' + (i - 'a' + offset) % 26));
}
} else {
encoded.append(i);
}
}
return encoded.toString();
}
public static String decode(String enc, int offset)
{ return encode(enc, 26 - offset);
}

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


{
String msg = "JJ COLLEGE OF ENGINEERING AND TECHNOLOGY";
System.out.println("Simulating Caesar Cipher\n ");
1
2

System.out.println("Input : " + msg); System.out.printf("Encrypted Message : ");


System.out.println(caesarCipher.encode(msg, 3));
System.out.printf("Decrypted Message : ");
System.out.println(caesarCipher.decode(caesarCipher.encode(msg, 3), 3));
}
}
CAESARCIPHER OUTPUT:
C:\Users\abacussys1\Desktop>javac caesarCipher.java
C:\Users\abacussys1\Desktop>java caesarCipher
Simulating Caesar Cipher
Input : JJ COLLEGE OF ENGINEERING AND TECHNOLOGY
Encrypted Message : MM FROOHJH RI HQJLQHHULQJ DQG WHFKQRORJB
Decrypted Message : JJ COLLEGE OF ENGINEERING AND TECHNOLOGY

RESULT:

Thus the Caesar cipher substitution technique was implemented and executed
successfully.

2
3

EX. NO. 1B PERFORM ENCRYPTION, DECRYPTION USING PLAYFAIR


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

ALGORITHM:
Step 1. Read the keyword.
Step 2. Then create the key table of 5x5 grid of alphabets.
Step 3. Read the word to encrypt.
Step 4. If the input word should be even and then process it.
Step 5. Then the plaintext message is split into pairs of two letters (digraphs).
Step 6. If both the letters are in the same column, take the letter below each one.
Step 7. If both letters are in the same row, take the letter to the right of each one.
Step 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.awt.Point;
class playfairCipher {
private static char[][] charTable;
private static Point[] positions;
private static String prepareText(String s, boolean chgJtoI)
{
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return chgJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTbl(String key, boolean chgJtoI)
{ charTable = new char[5][5]; positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", chgJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++)
{
char c = s.charAt(i);
if (positions[c - 'A'] == null)
{
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5); k++;
}
}
}
private static String codec(StringBuilder txt, int dir)
{ int len = txt.length();
for (int i = 0; i < len; i += 2)
{
char a = txt.charAt(i);
char b = txt.charAt(i + 1);
3
4

int row1 = positions[a - 'A'].y; int row2 = positions[b - 'A'].y;


int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + dir) % 5; col2 = (col2 + dir) % 5;
}
else if (col1 == col2)
{
row1 = (row1 + dir) % 5; row2 = (row2 + dir) % 5;
}
else
{
int tmp = col1; col1 = col2; col2 = tmp;
}
txt.setCharAt(i, charTable[row1][col1]);
txt.setCharAt(i + 1, charTable[row2][col2]);
}
return txt.toString();
}
private static String encode(String s)
{
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
if (i == sb.length() - 1)
{
sb.append(sb.length() % 2 == 1 ? 'X' : "");
}
else if (sb.charAt(i) == sb.charAt(i + 1))
{
sb.insert(i + 1, 'X');
}
}
return codec(sb, 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
public static void main(String[] args) throws java.lang.Exception
{
String key = "CSE";
String txt = "JJ COLLEGE OF ENGINEERING AND TECHNOLOGY";
/* make sure string length is even */ /* change J to I */ boolean chgJtoI = true;
createTbl(key, chgJtoI);
String enc = encode(prepareText(txt, chgJtoI));
System.out.println("Simulating Playfair Cipher\n----------------------");
4
5

System.out.println("Input Message : " + txt);


System.out.println("Encrypted Message : " + enc);
System.out.println("Decrypted Message : " + decode(enc));
}
}

PLAYFAIR CIPHER OUTPUT

C:\Users\abacussys1\Desktop>javac playfairCipher.java
C:\Users\abacussys1\Desktop>java playfairCipher
Simulating Playfair Cipher
----------------------
Input Message : JJ COLLEGE OF ENGINEERING AND TECHNOLOGY
Encrypted Message : GZDBKMMSMGLIAMHDMAGXHOHEKHRAADOKMKHX
Decrypted Message : IXICOLLEGEOFENGINEERINGANDTECHNOLOGY

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

5
6

EX. NO. 1C PERFORM ENCRYPTION, DECRYPTION USING HILL CIPHER


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

ALGORITHM:
Step 1. Obtain a plaintext message to encode in Standard English with no spaces.
Step 2. Split the plaintext into group of length three. To fill this, add X at the end.
Step 3. Convert each group of letters with length three into plaintext vectors.
Step 4. Replace each letter by the number corresponding to its position in the alphabet i.e.
A=1, B=2, C=3…Z=0.
Step 5. Create the keyword in a 3*3 matrix.
Step 6. Multiply the two matrices to obtain the cipher text of length three.
Step 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.
Step 8. Thus plain text is obtained from corresponding plaintext vector by corresponding
position in the alphabet.

PROGRAM:
class hillCipher
{
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";
private static String encode(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 decode(char a, char b, char c)
{
String ret = "";
int x, y, z;
int posa = (int) a - 65;
int posb = (int) b - 65;
6
7

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];
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; }
public static void main(String[] args) throws java.lang.Exception { String msg;
String enc = ""; String dec = "";
int n;
msg = ("JJ COLLEGE OF ENGINEERING AND TECHNOLOGY");
System.out.println("simulation of Hill Cipher\n ");
System.out.println("Input message : " + msg); msg = msg.toUpperCase();
msg = msg.replaceAll("\\s", "");
n = msg.length() % 3;
if (n != 0)
{
for (int i = 1; i <= (3 - n); i++)
{
msg += 'X';
}
}
System.out.println("padded message : " + msg);
char[] pdchars = msg.toCharArray();
for (int i = 0; i < msg.length(); i += 3) {
enc += encode(pdchars[i], pdchars[i + 1], pdchars[i + 2]);
} System.out.println("encoded message : " + enc);
char[] dechars = enc.toCharArray();
for (int i = 0; i < enc.length(); i += 3) {
dec += decode(dechars[i], dechars[i + 1], dechars[i + 2]);
}System.out.println("decoded message : " + dec);
}
}

HILL CIPHER OUTPUT:


C:\Users\abacussys1\Desktop>javac hillCipher.java
C:\Users\abacussys1\Desktop>java hillCipher
simulation of Hill Cipher
Input message : JJ COLLEGE OF ENGINEERING AND TECHNOLOGY
padded message : JJCOLLEGEOFENGINEERINGANDTECHNOLOGYX
encoded message : FXDGFVYIUGZCPIHDUZHGUGMTXTTQZDMLYWAZ
decoded message : JJCOLLEGEOFENGINEERINGANDTECHNOLOGYX
7
8

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

VIVA QUESTIONS:
1. Specify the four categories of security threats.
Interruption, Interception, Modification and Fabrication

2. Explain active and passive attack with example.


Passive attack: Monitoring the message during transmission.
Eg: Interception Active attack:
It involves the modification of data stream or creation of false data stream. E.g.:
Fabrication, Modification, and Interruption

3. Define integrity and non repudiation.


Integrity: Service that ensures that only authorized person able to modify the
message. Non repudiation: This service helps to prove that the person who denies the
transaction is true or false.

4. Define cryptanalysis?
It is a process of attempting to discover the key or plaintext or both.

5. Compare stream cipher with block cipher with example.


Stream cipher: Processes the input stream continuously and producing one element at
a time. Example: caeser cipher.
Block cipher: Processes the input one block of elements at a time producing an output
block for each input block. Example: DES.

6. Define security mechanism


It is process that is designed to detect prevent, recover from a security attack.
Example: Encryption algorithm, Digital signature, Authentication protocols.

7. Differentiate unconditionally secured and computationally secured.


An Encryption algorithm is unconditionally secured means, the condition is if the
cipher text Generated by the encryption scheme doesn’t contain enough information
to determine Corresponding plaintext. Encryption is computationally secured means,
1. The cost of breaking the cipher exceed the value of enough information.
2. Time required to break the cipher exceed the useful lifetime of information.

8. Define steganography
Hiding the message into some cover media. It conceals the existence of a message.

9. Why network need security?


When systems are connected through the network, attacks are possible during
transmission time.

8
9

ASSIGNMENT QUESTIONS

S.N QUESTIONS CO BT COMPL


O MAPPING LEVEL EXITY

Create an application based on DES


1 CO1 Create High
symmetric cipher.

Develop an application based on AES


2 CO1 Create High
symmetric cipher.
Implement Playfair cipher matrix
with the keyword “Cryptography”,
3 CO1 Create High
and perform both encryption and
decryption.
Create a program to implement Hill
cipher technique which executes both
4 CO1 Create High
encryption and decryption using a
2*2 key matrix.

9
10

EX. NO: 2a. IMPLEMENTATION OF RAIL FENCE – ROW TRANSFORMATION


TECHNIQUE

AIM:
To write a C program to implement the rail fence- row transposition technique.

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

ALGORITHM:
STEP-1: Read the Plain text.
STEP-2: Arrange the plain text in row columnar matrix format.
STEP-3: Now read the keyword depending on the number of rows of the plain text.
STEP-4: Arrange the characters of the keyword in sorted order and the corresponding
Rows of the plain text.
STEP-5: Read the characters row wise in the former order to get the cipher text.

PROGRAM: (Rail Fence)


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int i,j,k,l;
char a[20],c[20],d[20];
clrscr();
printf("\n\t\t RAIL FENCE TECHNIQUE");
printf("\n\nEnter the input string : ");
gets(a);
l=strlen(a);
/*Ciphering*/
for(i=0,j=0;i<l;i++)
{
if(i%2==0)
c[j++]=a[i];
}
for(i=0;i<l;i++)
{
if(i%2==1)
c[j++]=a[i];
}
c[j]='\0';
printf("\nCipher text after applying rail fence :");
printf("\n%s",c);
10
11

/*Deciphering*/
if(l%2==0)
k=l/2;
else
k=(l/2)+1;
for(i=0,j=0;i<k;i++)
{
d[j]=c[i];
j=j+2;
}
for(i=k,j=1;i<l;i++)
{
d[j]=c[i];
j=j+2;
}
d[l]='\0';
printf("\nText after decryption : ");
printf("%s",d);
getch();
}

OUTPUT:
RAIL FENCE TECHNIQUE
Enter the input string: computer science
Cipher text after applying rail fence:
cmue cecoptrsine
Text after decryption: computer science

RESULT:
Thus the rail fence algorithm had been executed successfully.

11
12

EX. NO: 2b. IMPLEMENTATION OF RAIL FENCE-COLUMN TRANSFORMATION


TECHNIQUE
AIM:
To write a C program to implement the rail fence - column transposition technique.

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

ALGORITHM:
STEP-1: Read the Plain text.
STEP-2: Arrange the plain text in row columnar matrix format.
STEP-3: Read the keyword depending on the number of columns of the plain text.
STEP-4: Arrange the characters of the keyword in sorted order and the corresponding
Columns of the plain text.
STEP-5: Read the character of column wise in the former order to get the cipher text.

PROGRAM: (Rail Fence)


#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
int i,j,k,l;
char a[20],c[20],d[20];
clrscr();
printf("\n\t\t RAIL FENCE TECHNIQUE");
printf("\n\nEnter the input string : ");
gets(a);
l=strlen(a);
/*Ciphering*/
for(i=0,j=0;i<l;i++)
{
if(i%2==0)
c[j++]=a[i];
}
for(i=0;i<l;i++)
{
if(i%2==1)
c[j++]=a[i];
}
c[j]='\0';
printf("\nCipher text after applying rail fence :");
printf("\n%s",c);
/*Deciphering*/
12
13

if(l%2==0)
k=l/2;
else
k=(l/2)+1;
for(i=0,j=0;i<k;i++)
{
d[j]=c[i];
j=j+2;
}
for(i=k,j=1;i<l;i++)
{
d[j]=c[i];
j=j+2;
}
d[l]='\0';
printf("\nText after decryption : ");
printf("%s",d);
getch();
}

OUTPUT:
RAIL FENCE TECHNIQUE
Enter the input string: computer science
Cipher text after applying rail fence:
cmue cecoptrsine
Text after decryption: computer science

RESULT:
Thus the rail fence algorithm had been executed successfully.

VIVA QUESTIONS

1. What is the Rail Fence Transposition technique?


The Rail Fence Transposition technique is a simple form of transposition cipher
where the plaintext is written in a zigzag pattern across several "rails" (rows), and then
read off as the cipher text.
2. Explain the row-major transformation of the Rail Fence technique.
In the row-major transformation, the characters of the plaintext are written
sequentially across the rows of a matrix (the "rails"), and then the cipher text is formed by
reading off the characters row by row.
3. How does the column-major transformation differ from the row-major
transformation in Rail Fence encryption?
In the column-major transformation, the characters of the plaintext are written
sequentially down the columns of a matrix, and then the cipher text is formed by reading
off the characters column by column.
4. How do you encrypt a plaintext using the Rail Fence technique with row-major
transformation?
13
14

To encrypt using row-major transformation:


Write the plaintext characters in a zigzag pattern across the rows of a matrix.
Read off the characters row by row to form the cipher text.
5. How do you decrypt a cipher text encrypted using the Rail Fence technique with row-
major transformation?
To decrypt using row-major transformation:
Reconstruct the matrix with the cipher text characters filled in row by row.
Read off the characters diagonally to recover the original plaintext.
6. Can you describe how the row-major encryption and decryption functions are
implemented in the provided code?
The encryption function constructs a matrix representing the rail fence pattern with
plaintext characters filled in row by row. The decryption function reconstructs the matrix
with cipher text characters filled in row by row and then reads off the characters diagonally
to recover the plaintext.
7. What is the purpose of the Rail Fence technique in cryptography?
The Rail Fence technique is used for simple transposition encryption. It is primarily
used for educational purposes or in situations where security requirements are not
stringent.
8. Discuss the security implications of using Rail Fence encryption for sensitive data.
Rail Fence encryption is not secure against modern cryptanalysis techniques. It is
susceptible to frequency analysis and other attacks due to its simple and predictable
encryption scheme.
9. What modifications could be made to improve the security of Rail Fence encryption?
Increasing the number of rails or using different variations of the Rail Fence
technique, such as using irregular spacing between rails, can enhance security to some
extent. However, for sensitive data, it's recommended to use more advanced encryption
techniques.
10. How does the complexity of the Rail Fence encryption and decryption algorithms
compare to other encryption techniques?
Rail Fence encryption and decryption algorithms have a linear time complexity in
terms of the length of the plaintext or cipher text. They are simpler compared to many
modern encryption techniques, which often have polynomial or exponential time
complexity. However, simplicity often comes at the cost of security.

Assignment Question.

S.N QUESTIONS CO BT COMPL


O MAPPING LEVEL EXITY
Implement the Rail Fence Cipher
1 encryption and decryption algorithms CO1 Create High
in Python.

14
15

EX. NO: 3 IMPLEMENTATION OF DATA ENCRYPTION STANDARD (DES)

AIM:
To write a C program to implement Data Encryption Standard (DES).

DESCRIPTION:
DES is a symmetric encryption system that uses 64-bit blocks, 8 bits of which are used
for parity checks. The key therefore has a "useful" length of 56 bits, which means that
only 56 bits are actually used in the algorithm. The algorithm involves carrying out
combinations, substitutions and permutations between the text to be encrypted and the
key, while making sure the operations can be performed in both directions. The key is
ciphered on 64 bits and made of 16 blocks of 4 bits, generally denoted k1 to k16. Given
that "only" 56 bits are actually used for encrypting, there can be 256 different keys.

The main parts of the algorithm are as follows:


Fractioning of the text into 64-bit blocks
Initial permutation of blocks
Breakdown of the blocks into two parts: left and right, named L and R
Permutation and substitution steps repeated 16 times
Re-joining of the left and right parts then inverse initial permutation

ALGORITHM:
STEP-1: Read the 64-bit plain text.
STEP-2: Split it into two 32-bit blocks and store it in two different arrays.
STEP-3: Perform XOR operation between these two arrays.
STEP-4: The output obtained is stored as the second 32-bit sequence and the original
second 32-bit sequence forms the first part.
STEP-5: Thus the encrypted 64-bit cipher text is obtained in this way. Repeat the same
Process for the remaining plain text characters.

PROGRAM:
DES.java
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
15
16

{
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
{
16
17

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:

Encrypted: c2df68c7c9f8a1da8b67c1dc5cbe9e1b
Decrypted: Hello World!!

RESULT:
Thus the data encryption standard algorithm had been implemented successfully.

VIVA QUESTIONS

1. What is DES and what is its purpose in cryptography?

DES (Data Encryption Standard) is a symmetric-key block cipher that encrypts data in fixed-size blocks using a
shared secret key. Its purpose in cryptography is to provide confidentiality by scrambling plaintext into cipher
text, making it unreadable to unauthorized parties.

2. Explain the key size and block size used in DES.

DES uses a 56-bit key and operates on 64-bit blocks of data.

3. Describe the overall structure of the DES algorithm.

DES consists of multiple rounds of permutation and substitution operations, including key generation, initial
permutation, 16 rounds of Feistel network, and a final permutation.

4. What are the key generation steps in DES?

The 56-bit key is expanded to 64 bits and then divided into two 28-bit halves. Each half is rotated left or right,
and then combined to generate 16 round subkeys of 48 bits each.

17
18

5. How does the DES algorithm achieve confusion and diffusion?

DES achieves confusion through its use of S-boxes (substitution boxes) to substitute bits in the data, and
diffusion through its permutation operations, which spread the influence of each plaintext bit across multiple
cipher text bits.

Assignment Question

S.N QUESTIONS CO BT COMPL


O MAPPING LEVEL EXITY
Implement a Python script to perform
1 DES encryption and decryption using CO1 Create High
the pycryptodome library.
Generate a random 56-bit key for use
2 in the encryption and decryption CO3 Create High
process.
Decrypt the resulting ciphertext back
3 CO3 Create High
to plaintext using the same key.
Display the original plaintext, the
4 generated key, the ciphertext, and the CO3 Create High
decrypted plaintext.

18
19

EX.NO. 4 IMPLEMENT ADVANCED ENCRYPTION STANDARD (AES)


ALGORITHM

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

ALGORITHM:
Step 1. AES is based on a design principle known as a substitution–permutation.
Step 2. AES does not use a Feistel network like DES, it uses variant of Rijndael.
Step 3. It has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.
Step 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)
19
20

{
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}
public static String decrypt(String strToDecrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
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);
String decryptedString = 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.

VIVA QUESTIONS
1. What is AES, and what is its significance in cryptography?
AES (Advanced Encryption Standard) is a symmetric-key block cipher used for
encryption and decryption of electronic data. It is significant in cryptography as it is
20
21

widely used to secure sensitive information in various applications, including banking,


government, and military.

2. Explain the key features of the AES algorithm.


AES operates on fixed-size blocks of data (128 bits), using keys of varying lengths
(128, 192, or 256 bits). It uses a substitution-permutation network consisting of
multiple rounds of substitution, permutation, and key mixing operations.

3. How does AES differ from DES in terms of security and performance?
AES offers improved security compared to DES due to its larger key size options (up
to 256 bits) and more complex encryption algorithm. Additionally, AES is generally
faster in terms of performance compared to DES, especially on modern hardware.

4. Describe the key expansion process in AES.


The key expansion process in AES involves transforming the original key into a set of
round keys used in each round of encryption. This process includes key schedule
operations such as key expansion, key mixing, and round key generation.

5. Explain the difference between AES encryption modes such as ECB, CBC, and CTR.
ECB (Electronic Codebook) mode encrypts each block of plaintext separately, CBC
(Cipher Block Chaining) mode XORs each plaintext block with the previous
ciphertext block before encryption, and CTR (Counter) mode encrypts plaintext by
XORing it with the output of a counter function.

ASSIGNMENT QUESTIONS

S.NO QUESTIONS CO BT COMPLE


MAPPING LEVEL XITY

Prompt the user to enter a plaintext


1 CO1 Create High
message.
Encrypt the plaintext message using
2 AES with the generated key and CO3 Create High
display the resulting cipher text.
Decrypt the cipher text back to
3 plaintext using the same key and CO3 Create High
display the original plaintext message.

21
22

EX. NO. 5 TO IMPLEMENT RSA ENCRYPTION ALGORITHM


AIM:
To implement RSA (Rivest–Shamir–Adleman) algorithm by using HTML and
Javascript.

ALGORITHM:

Step 1. Choose two prime number p and q


Step 2. Compute the value of n and p
Step 3. Find the value of e(publickey)
Step 4. Compute the value of d(private key) using gcd()
Step 5. Do the encryption and decryption
Step 6. Encryption is given as,
e
c=t mod n
Step 7. Decryption is given as,
d
t=c modn

PROGRAM:
<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>
22
23

<tr>
<td>Exponent:</td>
<td>
<p id="exponent"></p>
</td>
</tr>
<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;
23
24

}
</script>
</html>

OUTPUT:

RESULT:

Thus the RSA algorithm was implemented using HTML and Javascript and executed
successfully

VIVA QUESTIONS:

1. What are the principle elements of a public key cryptosystem?


The principle elements of a cryptosystem are:

2. What are roles of public and private key?


The two keys used for public-key encryption are referred to as the public key and the
private key. Invariably, the private key is kept secret and the public key is known
publicly. Usually the public key is used for encryption purpose and the private key is
used in the decryption side.

3. Specify the applications of the public key cryptosystem?

The applications of the public-key cryptosystem can classified as follows


1. Encryption/Decryption: The sender encrypts a message with the recipient’s public key.

2. Digital signature: The sender “signs” a message with its private key. Signing is achieved
24
25

by a cryptographic algorithm applied to a message or to a small block of data that is a


function of the message.

3. Key Exchange: Two sides cooperate to exchange a session key. Several different
approaches are possible, involving the private key(s) of one or both parties.

ASSIGNMENT QUESTIONS

CO BT COMPLE
S.NO QUESTIONS MAPPING LEVEL XITY
Choose an application of your
choice for RSA and show how CO4 Create High
1
encryption and decryption is
carried out.

25
26

EX. NO. 6 DIFFIE-HELLMAN KEY EXCHANGE ALGORITHM

AIM:
To implement the Diffie-Hellman Key Exchange algorithm for a given problem.

ALGORITHM:

Step1. Sender and receiver publicly agree to use a modulus p and base g which is a
primitive root modulo p.
Step 2. Sender chooses a secret integer x then sends Bob R1 = gx mod p
Step 3. Receiver chooses a secret integer y, then sends Alice R2 = gy mod p
Step 4. Sender computes k1 = Bx mod p
Step 5. Receiver computes k2 = Ay mod p
Step 6. Sender and Receiver now share a secret key.

PROGRAM:
class DiffieHellman
{
public static void main(String args[])
{
int p = 23; /* publicly known (prime number)
*/ int g = 5; /* publicly known (primitive root)
*/ int x = 4; /* only Alice knows this secret */ int y = 3;
/* only Bob knows this secret */ double
aliceSends = (Math.pow(g, x)) % p;
double bobComputes = (Math.pow(aliceSends, y)) % p;
double bobSends = (Math.pow(g, y)) % p;
double aliceComputes = (Math.pow(bobSends, x)) % p;
double sharedSecret = (Math.pow(g, (x * y))) % p;
System.out.println("simulation of Diffie-Hellman key exchange algorithm\n-----------");
System.out.println("Alice Sends : " + aliceSends);
System.out.println("Bob Computes : " + bobComputes);
System.out.println("Bob Sends : " + bobSends);
System.out.println("Alice Computes : " + aliceComputes);
System.out.println("Shared Secret : " + sharedSecret);
/* shared secrets should match and equality is transitive */
if ((aliceComputes == sharedSecret) && (aliceComputes == bobComputes))
System.out.println("Success: Shared Secrets Matches! " + sharedSecret);
else
System.out.println("Error: Shared Secrets does not Match");
}
}

OUTPUT:
C:\Users\abacussys1\Desktop>javac DiffieHellman.java
C:\Users\abacussys1\Desktop>java DiffieHellman
simulation of Diffie-Hellman key exchange algorithm
26
27

Alice Sends : 4.0


Bob Computes : 18.0
Bob Sends : 10.0
Alice Computes : 18.0
Shared Secret : 18.0
Success: Shared Secrets Matches! 18.0

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

VIVA QUESTIONS:
1. For long messages, RSA will be applied in blocks. If the block is very small say it
contains only one letter in each block, will the encryption be secure?
No, If the block contains only one letter, then each letter will be mapped to a fixed
Replacement. Thus it will become a substitution cipher and the cipher can be broken
using frequently analysis.
2. Mention any one technique of attacking RSA.
1. Brute force 2. Mathematical attacks 3 . Timing attacks 4. Chosen ciphertext attacks

ASSIGNMENT QUESTIONS
S.NO QUESTIONS CO BT COMPLE
MAPPING LEVEL XITY
Create a C++ program to
1 implement Diffie-Hellman CO1 Create High
Key Exchange.
Develop a program to
implement Diffie-Hellman CO1 Create High
2
Key exchange and generate
the shared secret key.
Create a program that can do
key exchange between two
parties and generate secret CO1 Create High
3
key. You can make use of
Diffie-Hellman Key Exchange
algorithm.

27
28

EX. NO: 7 MESSAGE DIGEST OF A TEXT USING THE SHA-1 ALGORITHM

AIM:
Calculate the message digest of a text using theSHA-1 algorithm in JAVA.

PROGRAM:
import java.security.*;
publicclassSHA1
{
publicstaticvoidmain(String[]a)
{
try
{
MessageDigestmd=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());
String input ="";md.update(input.getBytes());
byte[]output=md.digest();System.out.println();
System.out.println("SHA1(\""+input+"\")="+bytesToHex(output));
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)
{
System.out.println("Exception:"+e);
}
}
publicstaticStringbytesToHex(byte[]b){
charhexDigit[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
StringBufferbuf=newStringBuffer();
for (intj=0; j<b.length; j++)
{
buf.append(hexDigit[(b[j]>>4)&0x0f]);
buf.append(hexDigit[b[j] & 0x0f]);
}
returnbuf.toString();}
}
28
29

OUTPUT:
Message digestobject info:Algorithm=SHA1
Provider=SUNversion1.6
ToString = SHA1 Message Digest from SUN, <initialized> SHA1("")
=DA39A3EE5E6B4B0D3255BFEF95601890AFD80709SHA1("abc")
=A9993E364706816ABA3E25717850C26C9CD0D89D
SHA1("abcdefghijklmnopqrstuvwxyz")=32D10C7B8CF96570CA04CE37F2A19D84240D
3A89

RESULT:
Thus the SHA1 algorithm was used to implement and calculate the message digest of
text was executed and the output was verified successfully.

VIVA QUESTIONS

1. What is SHA-1, and how does it work?


SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function that takes an
input and produces a 160-bit (20-byte) hash value, typically represented as a 40-digit
hexadecimal number. It works by repeatedly applying a compression function to blocks of
data, transforming them into a fixed-size hash value.

2. Why is SHA-1 considered insecure?


SHA-1 is considered insecure due to vulnerabilities discovered over time, primarily
collision attacks. In 2017, researchers demonstrated the practicality of collision attacks
against SHA-1, making it unsuitable for cryptographic purposes where collision resistance
is required.

3. What are some alternatives to SHA-1?


Some alternatives to SHA-1 include SHA-256, SHA-384, and SHA-512, which are
part of the SHA-2 family. These algorithms offer stronger security properties and are
currently recommended for most cryptographic applications. Additionally, SHA-3, a
separate cryptographic hash function, provides another option for secure hashing.

4. How can SHA-1 be phased out in existing systems?


Phasing out SHA-1 involves migrating to newer hash functions, such as SHA-256 or
SHA-3, in all relevant systems and protocols. This may require updating software,
protocols, and cryptographic libraries to ensure compatibility with the new algorithms.
Additionally, it may involve retiring any systems or protocols that rely exclusively on
SHA-1 for security.

5. What are some real-world implications of SHA-1 vulnerabilities?


The real-world implications of SHA-1 vulnerabilities include the potential for forged
digital signatures, compromised certificate authorities, and insecure communication
channels. These vulnerabilities can be exploited by attackers to conduct various forms of
cyber-attacks, such as man-in-the-middle attacks and phishing scams.
29
30

ASSIGNMENT QUESTIONS

S. QUESTIONS CO BT COMPLE
N MAPPING LEVEL XITY
O
Explain the significance of the
1 collision vulnerability discovered CO4 Create High
in SHA-1.
Discuss its implications for
cryptographic security and the CO4 Create High
2
recommended actions for
organizations still using SHA-1.

30
31

EX. NO: 8 MESSAGE DIGEST OF A TEXT USING THE MD5 ALGORITHM

AIM:
Calculate the message digest of a text using the MD5 algorithm in JAVA.

PROGRAM:
importjava.security.*;
public classMD5
{
publicstaticvoidmain(String[]a)
{
//TO Do code application logic here
Try
{
MessageDigestmd=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());
String input ="";md.update(input.getBytes());
byte[]output=md.digest();System.out.println();
System.out.println("MD5(\""+input+"\")="+bytesToHex(output));
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(Exceptione)
{
System.out.println("Exception:"+e);
}}
publicstaticStringbytesToHex(byte[]b)
{
charhexDigit[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
StringBufferbuf=newStringBuffer();
for (intj=0; j<b.length; j++)
{
buf.append(hexDigit[(b[j]>>4)&0x0f]);
buf.append(hexDigit[b[j]&0x0f]);
}
returnbuf.toString();
}
}
31
32

OUTPUT:
Message digest object info:Algorithm=MD5
Provider=SUNversion1.6
ToString=MD5MessageDigestfromSUN, <initialized>MD5("")=D41D8CD98F00B204E98
00998ECF8427EMD5("abc")=
900150983CD24FB0D6963F7D28E17F72MD5 ("abcdefghijklmnopqrstuvwxyz")
=C3FCD3D76192E4007DFB496CCA67E13B

RESULT:

Thus the MD5 algorithm was used to implement and calculate the message digest of
text was executed and the output was verified successfully.

VIVA QUESTIONS

1. What is the MD5 algorithm, and how does it work?

The MD5 (Message Digest Algorithm 5) is a widely used cryptographic hash function
that produces a128-bit (16-byte) hash value, typically represented as a 32-digit
hexadecimal number. It works by taking an input message of arbitrary length and
processing it through a series of mathematical operations to produce a fixed-size output,
known as the message digest. MD5 operates by dividing the input message into blocks,
processing each block through a compression function, and combining the results to
generate the final hash value.

2. What are the key properties of the MD5 algorithm?

The key properties of the MD5 algorithm include: Collision Resistance: Ideally, it
should be computationally infeasible to find two different inputs that produce the same hash
value.Pre-image Resistance: Given a hash value, it should be computationally infeasible to
find an input message that produces that hash value. Second Pre-image Resistance: Given
an input message, it should be computationally infeasible to find another message that
produces the same hash value.High Speed: MD5 is designed to be relatively fast and
efficient in generating hash values.

3. What are some security concerns associated with the use of MD5?

While MD5 was widely used in the past, it is now considered cryptographically broken
and insecure for many applications due to several vulnerabilities. These vulnerabilities
include:Collision Attacks: Researchers have demonstrated practical collision attacks
against MD5, allowing for the creation of different inputs with the same hash value.Pre-
image Attacks: MD5 is susceptible to pre-image attacks, where an attacker can find an
input message that matches a given hash value.Length Extension Attacks: MD5 is
vulnerable to length extension attacks, where an attacker can append additional data to a
given hash value without knowing the original message. Security Weaknesses: MD5's
32
33

design features, such as its reliance on a simple iterative structure and lack of sufficient
mixing operations, contribute to its vulnerability to various attacks.

ASSIGNMENT QUESTION

S.N QUESTIONS CO BT COMPLE


O MAPPING LEVEL XITY

1 Alternatives to MD5 CO4 Create High

33
34

EX. NO. 9 IMPLEMENT DIGITAL SIGNATURE STANDARD

AIM:
To implement the signature scheme - Digital Signature Standard.

ALGORITHM:

Step 1. Declare the class and required variables.


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

PROGRAM:

import java.util.*;
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))
e:
{
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;
}
34
35

public static BigInteger getGen(BigInteger p, BigInteger q, Random r)


{
BigInteger h = new BigInteger(p.bitLength(), r); h = h.mod(p);
return h.modPow((p.subtract(one)).divide(q), p);
}
public static void main (String[] args) throws java.lang.Exception
{
Random randObj = new Random();
BigInteger p = getNextPrime("10600");
/* approximate prime */
BigInteger q = findQ(p.subtract(one));
BigInteger g = getGen(p,q,randObj);
System.out.println(" \n simulation of Digital Signature Algorithm \n");
System.out.println(" \n global public key components are:\n");
System.out.println("\np is: " + p);
System.out.println("\nq is: " + q); System.out.println("\ng is: " + g);
BigInteger x = new BigInteger(q.bitLength(), randObj); x = x.mod(q);
BigInteger y = g.modPow(x,p);
BigInteger k = new BigInteger(q.bitLength(), randObj); k = k.mod(q);
BigInteger r = (g.modPow(k,p)).mod(q);
BigInteger hashVal = new BigInteger(p.bitLength(), randObj);
BigInteger kInv = k.modInverse(q);
BigInteger s = kInv.multiply(hashVal.add(x.multiply(r)));
s = s.mod(q);
System.out.println("\nsecret information are:\n");
System.out.println("x (private) is:" + x);
System.out.println("k (secret) is: " + k);
System.out.println("y (public) is: " + y);
System.out.println("h (rndhash) is: " + hashVal);
System.out.println("\n generating digital signature:\n");
System.out.println("r is : " + r);
System.out.println("s is : " + s);
BigInteger w = s.modInverse(q);
BigInteger u1 = (hashVal.multiply(w)).mod(q);
BigInteger u2 = (r.multiply(w)).mod(q);
BigInteger v = (g.modPow(u1,p)).multiply(y.modPow(u2,p));
v = (v.mod(p)).mod(q);
System.out.println("\nverifying digital signature (checkpoints)\n:");
System.out.println("w is : " + w);
System.out.println("u1 is : " + u1);
System.out.println("u2 is : " + u2);
System.out.println("v is : " + v);
if (v.equals(r))
{
System.out.println("\nsuccess: digital signature is verified!\n " + r);
}
else
{
35
36

System.out.println("\n error: incorrect digital signature\n ");


}
}
}

OUTPUT:

C:\Security Lab New\programs>javac dsaAlg.java C:\Security Lab New\programs>javadsa


Alg simulation of Digital Signature Algorithm
global public key components are:
p is: 10601
q is: 53
g is: 6089
secret information are:
x (private) is:6k (secret) is: 3
y (public) is: 1356
h (rndhash) is: 12619 generating digital signature:
r is : 2 s is : 41
verifying digital signature (checkpoints):
w is : 22 u1 is : 4 u2 is : 44 v is : 2
success: digital signature is verified! 2

RESULT:
Thus the Digital Signature Standard Signature Scheme has been implemented and
executed successfully.

VIVA QUESTIONS

1. What are the properties a digital signature should have?


It must verify the author and the data and time of signature.
It must authenticate the contents at the time of signature.
It must be verifiable by third parties to resolve disputes.

2. What requirements should a digital signature scheme should satisfy?


The signature must be bit pattern that depends on the message being signed.
The signature must use some information unique to the sender, to prevent both
forgery and denial.
It must be relatively easy to produce the digital signature.
It must be relatively easy to recognize and verify the digital signature.
It must be computationally infeasible to forge a digital signature, either by
constructing a new message for an existing digital signature or by constructing a
fraudulent digital signature for a given message.
It must be practical to retain a copy of the digital signature in storage.

3. What are the security services provided by Digital Signature?


Security services provided by digital signature are message authentication,
message integrity and Non-repudiation.

36
37

4. Why do we need digital signature?

A digital signature provides proof of the message origin and a method to verify the
integrity of the message. A digital certificate owner combines the data to be signed with
their private key, and then transforms the data with an algorithm. digital signatures are a
fundamental tool for establishing trust, security, and authenticity in digital
communications, transactions, and document management. They play a critical role in
modern digital ecosystems, helping to protect sensitive information, reduce fraud, and
facilitate efficient, secure interactions.

5. What is key distribution centre?

A key distribution centre is responsible for distributing keys to pairs of users such as
hosts, processes, applications. Each user must share a unique key with the key
distribution centre for purposes of key distribution.

ASSIGNMENT QUESTIONS

S.N CO BT COMPL
O QUESTIONS MAPPING LEVEL EXITY
1 Create a program to CO2 Create High
implement the signature
scheme using DSA.
2 Develop a signature scheme CO2 Create High
using Digital Signature
Standard (DSS)

37
38

CONTENT BEYOND
SYLLABUS

38
39

EX. NO. 1. INSTALLATION OF WIRE SHARK, TCP DUMP


AIM:
To Install Wire shark, TCP dump and observe data transferred in client-server
communication using UDP/TCP and identify the UDP/TCP datagram.

PROCEDURE:
Wireshark is a free open- source network protocol analyzer. It is used for
network troubleshooting and communication protocol analysis. Wireshark captures
network packets in real time and display them in human-readable format. It provides
many advanced features including live capture and offline analysis, three-pane packet
browser, coloring rules for analysis. This document uses Wireshark for the
experiments, and it covers Wireshark installation, packet capturing, and protocol
analysis.

After you select the interface, you can click start to capture the packets as shown in the
figureTest Run

39
40

Do the following steps:

1. Start up the Wireshark program (select an interface and press start to capture packets).
2. Start up your favorite browser (ceweasel in Kali Linux).
3. In your browser, go to Wayne State homepage by typing www.wayne.edu.
4. After your browser has displayed the http://www.wayne.edu page, stop Wireshark
packet capture by selecting stop in the Wireshark capture window. This will cause the
Wireshark capture window to disappear and the main Wireshark window to display
all packets captured since you began packet capture see image below:

Color Coding: You’ll probably see packets highlighted in green, blue, and
black. Wireshark uses colors to help you identify the types of traffic at a glance. By
default, green is TCP traffic, dark blue is DNS traffic, light blue is UDP traffic, and
black identifies TCP packets with problems — for example, they could have been
delivered out-of-order. You now have live packet data that contains all protocol
messages exchanged between your computer and other network entities! However, as
you will notice the HTTP messages are not clearly shown because there are many
other packets included in the packet capture. Even though the only action you took
was to open your browser, there are many other programs in your computer that
communicate via the network in the background. To filter the connections to the ones
we want to focus on, we have to use the filtering functionality of Wireshark by typing
“http” in the filtering field as shown below:
Notice that we now view only the packets that are of protocol HTTP. However, we also still
do not have the exact communication we want to focus on because using HTTP as a
filter is not descriptive enough to allow us to find our connection to
http://www.wayne.edu. We need to be more precise if we want to capture the correct set
of packets. screenshot below

40
41

http.host www.wayne.edu, we are restricting the view to packets that have as an http
host the www.wayne.edu website. Notice that we need two equal signs to perform the
match not just one. See the Now, we can try another protocol. Let’s use Domain Name
System (DNS) protocol as an example here.

Let us try now to find the conversations (also called network flows), select one
of the packets and press the right mouse button (if you are on a Mac use the command

button and click), you should see something similar to the screen below:

Click on Follow UDP Stream, and then you will see following screen.

41
42

If we close this window and change the filter back to “http.hos ww.wayne.edu” and then
follow a packetfrom the list of packets that match that filter, we should get the
something similar to the following screens. Note that we click on Follow TCP Stream
this time.

RESULT:
Installation of Wire shark, tcp dump and observe data transferred in client-server
communication using UDP/TCP and identify the UDP/TCP datagram.

VIVA QUESTIONS:

1. What is Wireshark?
Wireshark is a network protocol analyzer, or an application that captures packets from a
network connection, such as from your computer to your home office or the internet.
Packet is the name given to a discrete unit of data in a typical Ethernet network. Wireshark
is the most often-used packet sniffer in the world.

2. What is difference between Wireshark and tcpdump?


Both Wireshark and tcpdump can be used to capture packets from a live network.
However, tcpdump is a terminal-based application while Wireshark has a graphical user
interface. Since we have terminal-based SSH sessions on our remote hosts, we will use
tcpdump to capture network packets on the remote network links.

3. What attacks Can Wireshark detect?


Wireshark to detect such attacks as DoS attack, DNS attacks, ARP poisoning and the
countermeasures specified to prevent the attacks. The final result showed that Wireshark is
a powerful tool used to keep track of network activity.

4. Explain the error control mechanism in TCP.

42
43

Error control in TCP is mainly done through the use of three simple techniques:
Checksum – Every segment contains a checksum field which is used to find corrupted
segments. If the segment is corrupted, then that segment is discarded by the destination
TCP and is considered lost.

5. What is TCP and UDP and how it works?


TCP vs UDP: Differences between the protocols. The main difference between TCP
(transmission control protocol) and UDP (user datagram protocol) is that TCP is a
connection-based protocol and UDP is connectionless. While TCP is more reliable, it
transfers data more slowly. UDP is less reliable but works more quickly.

ASSIGNMENT QUESTIONS
S.NO QUSETIONS CO BT COMPL
MAP LEVEL EXITY
PING
1 Install Wireshark and start a sample capture
using your wireless interface. Save your
Create High
capture file on the desktop with the CO3
name first.pcap, and close Wireshark.
2 Download and install wireshark and capture
icmp, tcp, and
http packets in promiscuous mode.
Download and install wireshark and capture
CO3 Create High
icmp, tcp, and
http packets in promiscuous mode.
Explore how the packets can be traced on
different filters.
3 Which layer in the TCP/IP model handles
Layer 2 addresses? Open
CO3 Create High
your first.pcap capture file in Wireshark and
check how many packets you captured in total.
4 How can Wireshark help in network
troubleshooting and analysis? What is the CO3 Create High
purpose of wireshark?
5 Working with Sniffers for monitoring network
communication using a) Ethereal b) Wire CO3 Create High
shark c) Snort d) tcp dump.

43
44

EX. NO. 2 CHECK MESSAGE INTEGRITY AND CONFIDENTIALITY USING SSL

Aim:
To check message integrity and confidentiality using SSL.

PROCEDURE:

Handshaking - Ciphersuit Negotiation


Client sends a plaintext Client_Hello message and suggests some cryptographic
parameters (collectively called ciphersuit) to be used for their communication session. The
Client_Hello message also contains a 32-byte random number denoted as client_random.
For example,

Client_Hello:
Protocol Version: TLSv1 if you can, else SSLv3. Key Exchange: RSA if you can, else
Diffe-Hellman.
Secret Key Cipher Method: 3DES if you can, else DES. Message Digest: SHA-1 if you
can, else MD5.
Data Compression Method: PKZip if you can, else gzip. Client Random Number: 32 bytes.

The stronger method (in terms of security) shall precede the weaker one, e.g. RSA (1024-
bit) precedes DH, 3DES precedes DES, SHA-1 (160-bit) precedes MD5 (128-bit).
Server responds with a plaintext Server_Helllo to state the ciphersuit of choice (server
decides on the ciphersuit). The message also contains a 32-byte random number denoted
as server_random. For example,

Server_Hello:
Protocol Version: TLSv1.
Key Exchange: RSA.
Secret Key Cipher Method: DES. Message Digest: SHA-1.
Data Compression Method: PKZip. Server Random Number: 32 bytes.
Handshaking - Key Exchange
The server sends its digital certificate to the client, which is supposedly signed by a root
CA. The client uses the root CA's public key to verify the server's certificate (trusted root-
CAs' public key are pre-installed inside the browser). It then retrieves the server's public
key from the server's certificate. (If the server's certificate is signed by a sub-CA, the client
has to build a digital certificate chain, leading to a trusted root CA, to verify the server's
certificate.)

44
45

The server can optionally request for the client's certificate to authenticate the client. In
practice, server usually does not authenticate the client. This is because:
A SSL Session Trace
We could use OpenSSL's s_client (with debug option) to produce a SSL session trace.
openssl s_client ?
(Display the available options)
The following command turns on the debug option and forces the protocol to be TLSv1:
openssl s_client -connect localhost:443 -CAfile ca.crt -debug -tls1

Loading 'screen' into random state - done CONNECTED(00000760)


write to 00988EB0 [009952C8] (102 bytes => 102 (0x66))
0000 - 16 03 01 00 61 01 00 00-5d 03 01 40 44 35 27 5c ....a...]..@D5'\
0010 - 5a e8 74 26 e9 49 37 e2-06 3b 1c 6d 77 37 d1 ae Z.t&.I7..;.mw7..
0020 - 44 07 86 47 98 fa 84 1a-8d f4 72 00 00 36 00 39 D..G .... r..6.9
0030 - 00 38 00 35 00 16 00 13-00 0a 00 33 00 32 00 2f .8.5.......3.2./
0040 - 00 07 00 66 00 05 00 04-00 63 00 62 00 61 00 15 ...f.....c.b.a..
0050 - 00 12 00 09 00 65 00 64-00 60 00 14 00 11 00 08 .....e.d.`......
0060 - 00 06 00 03 01 .....
0066 - <SPACES/NULS>
read from 00988EB0 [00990AB8] (5 bytes => 5 (0x5)) 0000 - 16 03 01 00 2a *
read from 00988EB0 [00990ABD] (42 bytes => 42 (0x2A))
0000 - 02 00 00 26 03 01 40 44-35 27 cc ef 2b 51 e1 b0 ...&..@D5'..+Q..
0010 - 44 1f ef c4 83 72 df 37-4f 9b 2b dd 11 50 13 87 D....r.7O.+..P..
0020 - 91 0a a2 d2 28 b9 00 00-16 ....(....
002a - <SPACES/NULS>
read from 00988EB0 [00990AB8] (5 bytes => 5 (0x5)) 0000 - 16 03 01 02 05 .....
read from 00988EB0 [00990ABD] (517 bytes => 517 (0x205)) 0000 - 0b 00 02 01 00 01
fe 00-01 fb 30 82 01 f7 30 82 ..........0 ........................................... 0.
0010 - 01 60 02 01 01 30 0d 06-09 2a 86 48 86 f7 0d 01 .`...0...*.H....
Server certificate
-----BEGIN CERTIFICATE-----
MIIB9zCCAWACAQEwDQYJKoZIhvcNAQEEBQAwTTELMAkGA1UEBhMCVVMx
EDAOBgNV
BAsTB3Rlc3QxMDExDDAKBgNVBAMTA2NoYzEeMBwGCSqGSIb3DQEJARYPY2
hjQHRl
c3QxMDEuY29tMB4XDTA0MDIyNjA2NTY1NFoXDTA1MDIyNTA2NTY1NFowOzE
LMAkG
A1UEBhMCVVMxDDAKBgNVBAMTA2NoYzEeMBwGCSqGSIb3DQEJARYPY2hj
QHRlc3Qx
MDEuY29tMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDN5J58ttI0TtNTR
45
46

iXH
U4glYOZG22Q6c2GSrCOSzSyUqY/Gf0dzwNmNNLcs3cmGvYJvzqzY4roP5fU6ZyyJ
GhsD6yGFKOMpmITtRnWC+g8wo6mlcUZM1g0XxBn9RPviGEamnauR3muhf/4wBih
d
2NMpAMMdTBMAYY/zhVH1aNhpJQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBA
Cn9v1rt
cI9TpOkUTF66hMZUG/LAPMQwD38SgE4Bt/05UPFBDdiqd9mHJRoe4peIT1N1yHAi
agFhD1E+ExmcZPJ2FOiFJSOiEcSM+CMs0cPTcTrmcVQQB9xy/+7oPs+Od3Ppn/Wa
kGBNoKoDMh8Rby6aXzx3BSIMgb8plq3LOxiu
-----END CERTIFICATE-----
subject=/C=US/CN=chc/[email protected]
issuer=/C=US/OU=test101/CN=chc/[email protected]
Byt Le Valu Description
es n e
00 1 16 Record Content Type - Handshake
Message
01- 2 03 01 SSL version - TLSv1
02
03- 2 00 2a Record Length
04
05 1 02 Handshake Type - Server_Hello
06- 3 00 00 Message Length
08 26
09- 2 03 01 Protocol Version Chosen - TLSv1
0A
Certificate

The certificate message consists of a chain of X.509 certificates in the correct order. The
first certificate belongs to the server, and the next certificate contains the key that certifies
the first certificate (i.e., the server's certificate), and so on. The client uses the server's
public key (contained inside the server's certificate) to either encrypt the pre_master_secret
or verify the server_key_exchange, depending on which ciphersuit is used.
No client certificate CA names sent
---
SSL handshake has read 1031 bytes and written 292 bytes
---
New, TLSv1/SSLv3, Cipher is EDH-RSA-DES-CBC3-SHA
Server public key is 1024 bit SSL-Session:
Protocol : TLSv1

46
47

Cipher : EDH-RSA-DES-CBC3-SHA
Session-ID:
Session-ID-ctx:
Master-Key: 57FDDAF85C7D287F9F9A070E8784A29C75E788DA2757699B
20F3CA50E7EE01A66182A71753B78DA218916136D50861AE
Key-Arg : None
Start Time: 1078211879 Timeout : 7200 (sec) Verify return code: 0 (ok)
---

Bytes Val Description


Len ue
00 1 14 Record Content Type -
Change_Cipher_Spec
01-02 2 03 SSL version - TLSv1
01
03-04 2 00 Record Length
01
05 1 01 ??

Certificate_Verify
Change_Cipher_Spec
Unknown Handshaking Message (D4) - to check
Application_Data Client-to-Server - the HTTP request message:
GET /test.html HTTP/1.0
Server-to-Client - the HTTP response message
Alert

RESULT:

Thus the confidentiality and Integrity using SSL was verified.

VIVA QUESTION:

1. What is the difference between an SSL connection and SSL session?


Connection is a transport that provides a suitable type of service. For SSL, such
connections are peer-topeer relationships. The connections are transient. Every connection
is associated with one session. Session: An SSL session is an association between a client
and a server. Sessions are created by the Handshake Protocol. Sessions define a set of
47
48

cryptographic security parameters, which can be shared among multiple connections.


Sessions are used to avoid the expensive negotiation of new security parameters for each
connection.
2. What is SSL integrity?
SSL, or Secure Sockets Layer, is an encryption based internet security protocol. It was
first developed by Netscape in 1995 for the purpose of ensuring privacy, authentication,
and data integrity in Internet communications. SSL is the predecessor to the modern TLS
encryption used today.
3. What is confidentiality in SSL?
Confidentiality—SSL uses a symmetric encryption algorithm to encrypt data and uses the
asymmetric key algorithm of RSA to encrypt the key to be used by the symmetric
encryption algorithm. Authentication—SSL supports certificate-based identity
authentication of the server and client by using the digital signatures.
4. What network layer is SSL?
One of the most popular encryption schemes usually associated with the presentation
layer is the Secure Socket Layer (SSL) protocol." HTTPS is the application layer protocol
using ssl at layer 6 for encryption purposes. SSL works on OSI layer 6.
5. How do you check integrity of messages?
The sender will calculate a hash on the message, and include the digest with the message.
On the other side, the receiver will independently calculate the hash on just the message,
and compare the resulting digest with the digest which was sent with the message.

ASSIGNMENT QUESTIONS
S.NO QUESTIONS CO BT COMPLEXITY
MAPPING LEVEL
1 Define SSL protocol stack and
SSL record protocol? Is SSL CO3 Create High
enough for cloud security
2 Develop a program to
implement SHA-1 to generate
CO3 Create High
message digest for any given
text.
3 Give a reliable solution for
securing online transactions CO3 Create High
using SSL
4 Using open SSL for web server
CO3 Create High
- browser communication.

48
49

INNOVATIVE PROJECT

49
50

PROJECT: EXPERIMENT EAVESDROPPING, DICTIONARY ATTACKS, MITM


ATTACKS

AIM:
To experiment eavesdropping, Dictionary attacks, MIMT attacks.
PROCEDURE
Password cracking is a term used to describe the penetration of a network, system, or
resource with or without the use of tools to unlock a resource that has been secured with a
password. Password cracking tools may seem like powerful decryptors, but in reality are
little more than fast, sophisticated guessing machines.

Types of password breaking


Dictionary attack
A simple dictionary attack is usually the fastest way to break into a machine. A
dictionary file (a text file full of dictionary words) is loaded into a cracking application,
which is run against user accounts located by the application.
Brute force attack
A brute force attack is a very powerful form of attack, though it may often take a long time
to work depending on the complexity of the password. The program will begin trying any
and every combination of numbers and letters and running them against the hashed
passwords.

Passwords that are composed of random letters numbers and characters are most
vulnerableto this type of attack.
Hybrid attack
Another well-known form of attack is the hybrid attack. A hybrid attack will add numbers
or symbols to the search words to successfully crack a password. Many people change their
passwords by simply adding a number to the end of their current password. Therefore, this
type of attack is the most versatile, while it takes longer then a standard dictionary attack it
does not take as long as a brute force attack.
Cracking Process
Since a brute force attack is the most time consuming and is not likely to break any
passwords that are not composed of random characters, the best plan is to use techniques
that are computationally efficient compared to untargeted and unspecific techniques. By
applying what is known about how users select passwords, an intruder can tremendously
increase the odds in their favor of finding passwords. With the right techniques, some poor
passwords can be cracked in under a second. The real power of dictionary attacks come
from understanding the ways in which most people vary names and dictionary words when
50
51

attempting to create a password. By applying all the common transformations to every word
in the electronic list and encrypting each result the number tested passwords multiplies
rapidly. Cracking tools can often detect “clever” ways of manipulating words to hide their
origin. For example, such cracking programs often subject each word to a list of rules. A
rule could be anything, any manner in which a word might appear. Typical rules might
include Alternate upper- and lowercase lettering. Spell the word forward and then
backward, and then fuse the two results (for example: cannac). Add the number 1 to the
beginning and/or end of each word. Naturally, the more rules one applies to the words, the
longer the cracking process takes. However, more rules also guarantee a higher likelihood of
success.

Man in the Middle (MITM) against Diffie-Hellman:


A malicious Malory, that has a MitM (man in the middle) position, can manipulate the
communications between Alice and Bob, and break the security of the key exchange.
Step by Step explanation of this process:
Step 1: Selected public numbers p and g, p is a prime number, called the “modulus” and g
is called the base.
Step 2: Selecting private numbers.
let Alice pick a private random number a and let Bob pick a private random number b,
Malory picks 2 random numbers c and d.

Step 3: Intercepting public values,


Malory intercepts Alice’s public value (g a(mod p)), block it from reaching Bob, and
instead sends Bob her own public value (g c(modp)) and Malory intercepts Bob’s public
value (gb(mod p)), block it from reaching Alice, and instead sends Alice her own public
value (gd (modp))

Step 4: Computing secret key


Alice will compute a key S 1=gda(mod p), and Bob will compute a different key,
S2=gcb(mod p)

51
52

Step 5: If Alice uses S1 as a key to encrypt a later message to Bob, Malory can decrypt it,
re-encrypt it using S2, and send it to Bob. Bob and Alice won’t notice any problem and
may assume their communication is encrypted, but in reality, Malory can decrypt, read,
modify, and then re-encrypt all their conversations.
Task 1 – Microsoft Office Password Recovery
Many applications require you to establish an ID and password that may be saved and
automatically substituted for future authentication. The password will usually appear on
the screen as a series of asterisks. This is fine as long as your system remembers the
password for you but what if it "forgets" or you need it for use on another system.
Fortunately, many utilities have been written to recover such passwords. In this task, you
will use OfficeKey to recover the password for a MS word document.
You will find OfficeKey and a MS document in the folder.
Step 1: Find the folder “Lab1” on your desktop, and open it.

Step 2: Open the Office Key – Password Recovery tool


Step 3: Press the “Recover” button in the upper left corner, or select File Recover
Step 4: Choose the password protected MS Office File you have saved to the Desktop.
Step 5: After running the first password auditing session, check to see if Office key has
cracked the password. If the password has not been cracked press the Settings button on
the upper tool bar.

52
53

Step 6: Once in the Settings menu you will be able to modify the search parameters and
customize a more targeted search

Step 7: Repeat steps 3 and 4 until the password has been cracked and opens the MS
Office File.
Step 8: Write down the contents of the MS word document and the password into your
lab report and submit it to your TA.

Task 2 – Password Auditing (Windows platform):


The purpose of this task is to familiarize you with act of password cracking/recovery.
Password cracking software uses a variety of approaches, including intelligent guessing,
dictionary attacks and automation that tries every possible combination of characters.
Given enough time the automated method can crack any password, but more effective
passwords will last months before breaking.
When a password is entered and saved on a computer it is encrypted, the encrypted
password becomes a string of characters called a “hash” and is saved to a password file.
53
54

A password cannot be reverse-decrypted. So a cracking program encrypts words and


characters given to it (wordlist or randomly generated strings of characters) and compares
the results with hashed passwords. If the hashes match then the password has successfully
been guessed or “cracked”. This process is usually performed offline against a captured
password file so that being locked out of the account is not an issue, and guessing can go
on continuously. Thus, revealing the passwords is simply a mater of CPU time and
dictionary size
1. You obtain a dictionary file, which is no more than a flat file (plain text) list of words
(commonly referred to as wordlists).
2. These words are fed through any number of programs that encrypt each word. Such
encryption conforms to the DES standard.
3. Each resulting encrypted word is compared with the target password. If a match
occurs, there is better than a 90 percent chance that the password was cracked.

Step 1: Go to Lab1 folder, and open LC4 to audit the passwords on your Windows
system.
Select File New Session
Select Import Import from PWDUMP File (in the same folder) Select the
“Passwords” file that has been provided to you.

Objectives
This password file has been retrieved from a system that we must gain access to. To do
this you must crack as many passwords as possible as quickly as possible. We have
captured the user names and encrypted passwords for ten users. The user names follow a
standard pattern of first initial and last name, but the passwords have no set standards. We
do know that users of this system are encouraged to add numbers and other characters to
the words they chose for passwords.
To aid you in cracking these passwords we have managed to collect some basic
information about the users. This personal information may help you target your searches
as to what the user’s password may be.
54
55

Kmiller Ken Miller is an avid fly fisher and his record number
of catches is just under 30
Smacman Steven MacMan has a fiancé who’s name is 4 letters
long and starts with a “K”
Gkoch Gina Koch grew up with her German grandmother,
who used to call her ‘Little Precious’ *
Mjones Matt Jones was born in 1979. He compares
himself to a Shakespearean character who was born
via C section
Tgriffin Tim Griffin loves funky ‘70’s and ‘80s music. And
songs about ‘Love’
Rklatt Ryan Klatt is a big Star Trek fan and has most
likely chosen an obscure reference for his password *

Step 2: Select Session Session Options

Use this menu to customize your password search. Here you can add different word list
for Dictionary attacks, change Hybrid attack features. Keep in mind you are working
with a short dead line and more in depth searches will take longer then you have. You
must use the information given to you to target your search most specifically at more
likely passwords.

55
56

Step 3: Select Session Begin “Audit” or Press the blue play button on the upper toolbar
to start the password search.
Step 4: After the first search has run check your progress. Have some of the passwords
been cracked all the way though or have some only been partially cracked. Use what
you’ve learned from this first search to target your next few searches. You will need to
search the internet and use the information you have been given about each user to find
words they may have used as their password.
Note: The question marks in the partially cracked passwords do not necessarily represent
the number of remaining undiscovered characters.
Step 5: Add words to your wordlist Session Session Options
Press the ‘Dictionary List’ button in the Dictionary crack section. Here you can edit your
current word list and add words by selecting the ‘EDIT’ button and entering each

wordon a new line. You can also add multiple dictionaries and wordlist.

Step 6:You may chose to conduct dictionary attacks with other wordlists.
You can find additional wordlist to use here: ftp://ftp.cerias.purdue.edu/pub/dict

Step 7: Continue searching for possible passwords during the remainder of the lab.
Repeating steps 3 and 4 each time you modify your search.

Step 8: Once you have cracked all the passwords in the file, write them down in your lab
report or once the lab time has ended, submit the passwords you were able to crack.

Dictionary attacks,
import java.security.*;
import java.io.*;
import java.util.*;
import java.lang.StringBuilder;
import javax.xml.bind.DatatypeConverter;
56
57

public class DictionaryAttack {


//Extracted from http://www.jmdoudoux.fr/java/dej/chap-jca.htm
public static String bytesToHex(byte[] b) {
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
StringBufferbuf = 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();
}
//This method takes a string, computes its SHA-1 hash,
//and converts it into HEX using the bytesToHex method
public static String stringToSha1(String input) throws Exception {
//Setup a MessageDigest for SHA1
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
//Setup the MessageDigest with our input string
md.update(input.getBytes("UTF-8"));
//Convert the string's digest to HEX
String sha1 = bytesToHex(md.digest());
return sha1;
}
//This method takes a byte array holding a salt and a string input
//and returns the concatenated salt || input in byte array format
public static byte[] concatenate_salt_with_string(byte[] salt, String input) throws Exception
{
//Convert input string to bytes
byte[] input_byte = input.getBytes("UTF-8");
//Create byte array sufficiently large
byte[] concatenated = new byte[salt.length + input_byte.length];
//Insert the salt first
System.arraycopy(salt, 0, concatenated, 0, salt.length);
//Insert the input string converted to bytes
System.arraycopy(input_byte, 0, concatenated, salt.length, input_byte.length);
//Return the concatenated salt and string in a byte array
return concatenated;
}

57
58

//This method takes a string, a salt, computes its salted SHA-1 hash,
//and converts it into HEX using the bytesToHex method
public static String stringToSha1_salted(byte[] salt, String input) throws Exception {
//Setup a MessageDigest for SHA1
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
//Use the concatenate_salt_with_string method to concatenate the salt with the input byte[]
concatenated = concatenate_salt_with_string(salt, input);
//Setup the MessageDigest with our input string
md.update(concatenated);
//Convert the string's digest to HEX
String sha1 = bytesToHex(md.digest());
return sha1;
}
public static void main(String[] args) throws Exception {
//Notify the user the program is starting.
System.out.println("Let's get things started.");
//Load the provided password file into stream and buffer
Filepasswords_file=new
File("/Users/nicolas/Documents/eclipseworkspace/dictionaryattack/src/password.txt");
FileInputStreampassword_stream = new FileInputStream(passwords_file);
BufferedReaderpassword_buffer=newBufferedReader(new
nputStreamReader(password_stream));
//Initialize 3 hashmaps, one for non-salted passwords, one for salted passwords,
//and one for the salts of salted passwords.
Map<String, String>non_salted_passwords = new HashMap<String, String>();
Map<String, String>salted_passwords = new HashMap<String, String>();
Map<String, String>salted_passwords_salts = new HashMap<String, String>();
//We parse the buffer to extract user account names and passwords
String password_file_line = null;
while ((password_file_line = password_buffer.readLine()) != null)
{
String[] splited = password_file_line.split("\\s+");
//First case: password hashed with no salt
if(splited.length == 3){
non_salted_passwords.put(splited[0], splited[2]);
}
//Second case: password hashed with a salt
Else{
salted_passwords.put(splited[0], splited[3]);
58
59

salted_passwords_salts.put(splited[0], splited[2]);
}
}
//We are done reading the password file, we can close its buffer
password_buffer.close();
//Load the provided Dictionary into stream and buffer
File fin = new
File("/Users/nicolas/Documents/eclipseworkspace/dictionaryattack/src/english.0");
FileInputStreamfis = new FileInputStream(fin);
//Construct BufferedReader from InputStreamReader
BufferedReaderbr = new BufferedReader(new InputStreamReader(fis));
//We parse the buffer to test matches for hashed password,
//reversed passwords, non vowel passwords, and salted versions of password (if required).
String line = null;
while ((line = br.readLine()) != null) {
//We first iterate through the non salted passwords
Iterator non_salted_passwords_it = non_salted_passwords.entrySet().iterator();
while (non_salted_passwords_it.hasNext()) {
//We extract the key,value pair from the HashTable entry
Map.Entry pair = (Map.Entry)non_salted_passwords_it.next();
String account_name = pair.getKey().toString();
String account_password_hash = pair.getValue().toString();
//We test if the password matches an unmodified dictionary entry
if(account_password_hash.equals(stringToSha1(line))){
System.out.println(account_name + "'s password is '" + line + "'"); }

//We test if the password matches a reversed dictionary entry


String reversed_line = new StringBuilder(line).reverse().toString();
if(account_password_hash.equals(stringToSha1(reversed_line))){
System.out.println(account_name + "'s password is '" + reversed_line + "'");
}
//We test if the password matches a dictionary entry without its vowels
String line_without_vowels = line.replaceAll("[AEIOUaeiou]", "");
if(account_password_hash.equals(stringToSha1(line_without_vowels))){
System.out.println(account_name + "'s password is '" + line_without_vowels + "'");
}
}
//We then iterate through the salted passwords
Iterator salted_passwords_it = salted_passwords.entrySet().iterator();
while (salted_passwords_it.hasNext()) {
59
60

//We extract the key,value pair from the HashTable entry


Map.Entrysalted_pair = (Map.Entry)salted_passwords_it.next();
String account_name = salted_pair.getKey().toString();
String account_password_hash = salted_pair.getValue().toString();
//We extract the corresponding salt from the HashTable of salts
byte[] account_password_hash_salt =
DatatypeConverter.parseHexBinary(salted_passwords_salts.get(account_name));
//We test if the password matches an unmodified dictionary entry
if(account_password_hash.equals(stringToSha1_salted(account_password_hash_salt,line)))
{
System.out.println(account_name + "'s password is '" + line + "'");
}
//We test if the password matches a reversed dictionary entry
String reversed_line = new StringBuilder(line).reverse().toString();
if(account_password_hash.equals(stringToSha1_salted(account_password_hash_salt,revers
ed_line))){
System.out.println(account_name + "'s password is '" + reversed_line + "'");
}
//We test if the password matches a dictionary entry without its vowels
String line_without_vowels = line.replaceAll("[AEIOUaeiou]", "");
if(account_password_hash.equals(stringToSha1_salted(account_password_hash_salt,line_
without_vowels))){
System.out.println(account_name + "'s password is '" + line_without_vowels + "'");
}
}
}
//We are done using the dictionary file, we can close its buffer
br.close();
//Notify the user our program is done running.
System.out.println("The program terminated.");
}
}
Password.txt
andrew 0 7207aa5e5e68188241a72b3fd9b12391585cad21
joe 0 65640c6577c9c72497525e656127b5bd1deb6f85
eve 0 61424ee758ec5e0d0ffe6a2ce151bf9d927c3ad7
bob 0 843b961da8707a9314aa3b7bb950a7003e49a94c
guy 0 eb6dc8cf797e6aeec2f2695883c0cf93cc765537
alice 0 eb756abf97413f28b2e36f1de57e17b31129aa46
mary 0 932eeb1076c85e522f02e15441fa371e3fd000ac
60
61

adam 0 7d27662bb31cb629178e929287993c01bf7c42ac
nick 1 a9edd3db 93bbd7dab6e365a5a840584d9849cbd55fbbf469
john 1 2afd4f21 511c896b5bcf313140d513100966a5ccec90c714

Here are the files you can find in this repository:


 password.txt contains a list of passwords that we recover using the attack
 DictionaryAttack.java is the source code for the attack
 english.0 is the dictionary used during the attack to recover passwords
Description of the password.txt file format
The list of passwords that we recover using the attack is a text file in which each line
contains a user account name followed by a password. There are two possible line
formats: the first one contains an unsalted password while the second contains a
salted password along with the salt.
username 0 unsaltedpassword
username 1 salt saltedpassword
The passwords are hashed using SHA-1 (see attack source code for implementation in
the Java Cryptography Extension). When a salt is used, it is simply concatenated
together with the passwords as follows: salt || password.
Description of the attack
The attack simply reads the dictionary line by line and computes 6 different possible
hashed passwords for the word contained in each line. These 6 possible hashes
are compared to each of the passwords contained in the password.txt file for a
match. If there is a match, we recovered a password. If not, we simply keep
reading the dictionary line by line.
The 6 possible hashes computed for each word from the dictionary are:
 SHA1(word)
 SHA1(drow) (reversed word)
 SHA1(wrd) (word without vowels)
 SHA1(salt||word) (salted word)
 SHA1(salt||drow) (salted reversed word)
 SHA1(salt||wrd) (salted word without vowels)
Note that the salts used in salted hashes are the ones includes in the password.txt file.
How to run the attack
To run the attack, simply compile and run the DictionaryAttack.java file. All paths are
hardcoded in the file so you will need to update them before you compile the
source code.
The output should be the following:
Let's get things started.
joe's password is 'December'
alice's password is 'tfosorciM'
61
62

mary's password is 'Monday'


john's password is 'brosba'
bob's password is 'yllacitebahpla'
guy's password is 'ntrstwrthnss'
nick's password is 'uplifting'
adam's password is 'vsblts'
eve's password is 'wrrsm'
andrew's password is 'kcitsdray'
The program terminated.
Note on complexity
Note that this attack is a simple example and could be made far more efficient using
various strategies. One of them would be to precompute the possible hashes before
checking the password list for matches. Since our password list and dictionary are fairly
small in this example, I did not implement this feature.

62

You might also like