Cryptography and Cyber Security Manual
Cryptography and Cyber Security Manual
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);
}
RESULT:
Thus the Caesar cipher substitution technique was implemented and executed
successfully.
2
3
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
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
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
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
4. Define cryptanalysis?
It is a process of attempting to discover the key or plaintext or both.
8. Define steganography
Hiding the message into some cover media. It conceals the existence of a message.
8
9
ASSIGNMENT QUESTIONS
9
10
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.
/*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
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.
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
Assignment Question.
14
15
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.
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
Encrypted: c2df68c7c9f8a1da8b67c1dc5cbe9e1b
Decrypted: Hello World!!
RESULT:
Thus the data encryption standard algorithm had been implemented successfully.
VIVA QUESTIONS
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.
DES consists of multiple rounds of permutation and substitution operations, including key generation, initial
permutation, 16 rounds of Feistel network, and a final permutation.
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
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
18
19
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
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.
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
21
22
ALGORITHM:
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:
2. Digital signature: The sender “signs” a message with its private key. Signing is achieved
24
25
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
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
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
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
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
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
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.
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
33
34
AIM:
To implement the signature scheme - Digital Signature Standard.
ALGORITHM:
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
OUTPUT:
RESULT:
Thus the Digital Signature Standard Signature Scheme has been implemented and
executed successfully.
VIVA QUESTIONS
36
37
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.
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
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
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.
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.
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
Aim:
To check message integrity and confidentiality using SSL.
PROCEDURE:
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
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)
---
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:
VIVA QUESTION:
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
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.
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.
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.
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.
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 *
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
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 + "'"); }
adam 0 7d27662bb31cb629178e929287993c01bf7c42ac
nick 1 a9edd3db 93bbd7dab6e365a5a840584d9849cbd55fbbf469
john 1 2afd4f21 511c896b5bcf313140d513100966a5ccec90c714
62