cys_lab_manual
cys_lab_manual
LAB MANUAL
REGULATION 2021 R
YEAR/SEM II / IV
Prepared by Approved by
Dr. S. SUDHAKAR, AsP/CSE Dr. K. RAJESH Professor
HOD/CSE (CYBER SECURITY)
SSM INSTITUTE OF ENGINEERING AND TECHNOLOGY
(AN AUTONOMOUS INSTITUTION)
(Approved by AICTE, New Delhi / Affiliated to Anna University/Accredited by NAAC)
Dindigul – Palani Highway, Dindigul – 624 002.
VISION
To develop skilled cyber security professionals equipped to secure digital landscapes, address emerging
cyber challenges, and contribute to society with strong technical expertise, entrepreneurial skills, and
ethical values.
MISSION
Foster self-discipline and critical thinking in students through robust teaching and learning.
Empower students to become proficient cyber security professionals and responsible citizens.
Strengthen industry partnerships by establishing specialized centres for advanced skill
development and practical exposure.
Deliver knowledge for secure and innovative solutions, contributing to sustainable and ethical
technology advancement.
PEO1 Graduates can apply their technical competence in computer science to solve real world
problems, with technical and people leadership.
Graduates Conduct cutting edge research and develop solutions on problems of social
PEO2 relevance.
Graduates will Work in a business environment, exhibiting team skills, work ethics,
PEO3 adaptability and lifelong learning.
PROGRAM OUTCOMES (POs)
Graduate Attribute
2 Problem analysis: Identify, formulate, review research literature, and analyse complex
engineering problems reaching substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
3 Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modelling to complex engineering activities with
an understanding of the limitations.
6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms
of the engineering practice.
9 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
10 Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as, being able to comprehend and write
effective reports and design documentation, make effective presentations, and give and receive clear
instructions.
12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
COURSE OBJECTIVES:
Learn different cipher techniques.
Implement the algorithms DES, AES, RSA and Diffie-Hellman.
Implement hashing techniques such as SHA-1, MD-5.
Develop a digital signature scheme.
PRACTICAL EXERCISES:
1. Write a program to implement the following cipher techniques to perform encryption and
decryption
i. Caesar Cipher
ii. Playfair Cipher
iii. Hill Cipher
2. Write a program to implement the following transposition techniques
(i) Rail fence technique –Row major transformation
(ii) Rail fence technique - Column major transformation
3. Write a program to implement DES algorithm
4. Write a program to implement AES algorithm
5. Write a program to implement RSA Encryption algorithm
6. Write a program to implement the Diffie-Hellman Key Exchange mechanism. Consider one of
the parties as Alice and the other party as bob.
7. Write a program to calculate the message digest of a text using the SHA-1 algorithm.
8. Write a program to calculate the message digest of a text using the MD-5 algorithm.
9. Write a program to implement digital signature standard.
TOTAL: 30 PERIODS
COURSE OUTCOMES:
CO1: Develop a code for classical encryption techniques.
CO2: Build a symmetric and asymmetric algorithms.
CO3: Construct a code for various Authentication schemes.
CO4: Apply the principles of digital signature.
LIST OF EQUIPMENT FOR A BATCH OF 30 STUDENTS:
SOFTWARE: C / C++ / Java or equivalent compiler
HARDWARE: Standalone desktops – 30 Nos. (or) Server supporting 30 terminals or more.
CO PO1 PO2 PO3 PO4 PO5 PO6 PO7 PO8 PO9 PO10 PO11 PO12 PSO1 PSO2
CB3411.1 3 3 3 3 3 - - - 3 - - 1 3 3
(CO1)
CB3411.2 3 3 3 3 3 - - - 3 - - 1 3 3
(CO2)
CB3411.3 3 3 3 3 3 - - - 3 - - 1 3 3
(CO3)
CB3411.4 3 3 3 3 3 - - - 3 - - 1 3 3
(CO4)
Avg. 3 3 3 3 3 - - - 3 - - 1 3 3
AIM:
To implement a Caesar cipher substitution technique in Java.
ALGORITHM:
1. Assign the 26 letters in alphabet to the variable named ALPHABET.
2. Convert the plaintext letters into lowercase.
3. To encrypt a plaintext letter, the first set of plaintext letters and slides it to LEFT by the
number of positions of the secret shift.
4. The plaintext letter is then encrypted to the ciphertext letter on the sliding ruler underneath.
5. On receiving the ciphertext, the receiver who also knows the secret shift, positions his
sliding ruler underneath the ciphertext alphabet and slides it to RIGHT by the agreed shift
number, 3 in this case.
6. Then replaces the ciphertext letter by the plaintext letter on the sliding ruler underneath.
PROGRAM:
import java.util.Scanner;
public class ceasercipher
{
public static final String ALPHABET="abcdefghijklmnopqrstuvwxyz";
public static String encrypt(String plainText,int shiftKey)
{
plainText=plainText.toLowerCase();
String cipherText="";
for (int i=0; i<plainText.length();i++)
{
int charPosition=ALPHABET.indexOf(plainText.charAt(i));
int keyVal=(shiftKey+charPosition)%26;
char replaceVal=ALPHABET.charAt(keyVal);
cipherText+=replaceVal;
}
return cipherText;
}
public static String decrypt(String cipherText,int shiftKey)
{
cipherText = cipherText.toLowerCase();
String plainText = "";
for(int i=0;i<cipherText.length();i++)
{
int charPosition= ALPHABET. indexOf(cipherText. charAt(i));
int keyVal=(charPosition-shiftKey)%26;
if (keyVal< 0)
{
keyVal=ALPHABET.length()+keyVal;
}
char replaceVal=ALPHABET.charAt(keyVal);
plainText+=replaceVal;
}
return plainText;
}
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the Plain text for Encryption: ");
String message=new String();
message=sc.next();
System.out.println("Encrypted message:Cipher Text="+encrypt(message,3));
System.out.println("Decrypted message:Plain Text="+decrypt (encrypt(
message,3),3));
sc.close();
}
}
OUTPUT:
F:\bin>javac ceasercipher.java
F:\bin>java ceasercipher
Enter the Plain text for Encryption:
covid
Encrypted message:Cipher Text=frylg
Decrypted message:Plain Text=covid
RESULT:
Thus the Caesar cipher substitution technique was implemented and executed
successfully.
Ex.No. : 1b PLAYFAIR CIPHER
Date :
AIM:
To implement a Playfair cipher substitution technique in Java.
ALGORITHM:
1. Read the keyword.
2. Then create the key table of 5x5 grid of alphabets.
3. Read the word to encrypt.
4. Ifthe input word should be even and then process it.
5. Then the plaintext message is split into pairs of two letters (digraphs).
6. Ifboth the letters are in the same column, take the letter below each one.
7. Ifboth letters are in the same row, take the letter to the right of each one.
8. If neither of the preceding two rules are true, form a rectangle with the two letters and
take the letters on the horizontal opposite corner of the rectangle.
PROGRAM:
import java.util.Scanner;
public class Playfair1
{
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
System.out.print("Enter keyword: ");
String key=in.nextLine();
System.out.print("Enter message to encrypt: ");
String msg=in.nextLine();
PFEncryption pfEncryption=new PFEncryption();
pfEncryption.makeArray(key);
msg=pfEncryption.manageMessage(msg);
pfEncryption.doPlayFair(msg, "Encrypt");
String en=pfEncryption.getEncrypted();
System.out.println("Encrypting. .. \n\nThe encrypted text is: " + en);
System.out.println("=============================");
pfEncryption.doPlayFair(en, "Decrypt");
System.out.print("\nDecrypting... \n\nThe encrypted text is: " +
pfEncryption.getDecrypted());
}
}
class PFEncryption
{
private char [][] alphabets= new char[5][5];
private char[] uniqueChar= new char[26];
private String ch="ABCDEFGHIKLMNOPQRSTUVWXYZ";
private String encrypted="";
private String decrypted="";
void makeArray(String keyword)
{
keyword=keyword.toUpperCase().replace("J","I");
boolean present, terminate=false;
int val=0;
int uniqueLen;
for (int i=0; i<keyword.length(); i++)
{
present=false;
uniqueLen=0;
if (keyword.charAt(i)!= ' ')
{
for (int k=0; k<uniqueChar.length; k++)
{
if (Character.toString(uniqueChar[k])==null)
{
break;
}
uniqueLen++;
}
for (int j=0; j<uniqueChar.length; j++)
{
if (keyword.charAt(i)==uniqueChar[j])
{
present=true;
}
}
if (!present)
{
uniqueChar[val]=keyword.charAt(i);
val++;
}
}
ch=ch.replaceAll(Character.toString(keyword.charAt(i)), "");
}
for (int i=0; i<ch.length(); i++)
{
uniqueChar[val]=ch.charAt(i);
val++;
}
val=0;
OUTPUT:
F:\bin>javac Playfair1.java
F:\bin>java Playfair1
Enter keyword: INFOSEC
Enter message to encrypt: cryptography
I N F O S
E C A B D
G H K L M
P Q R T U
V W X Y Z
Encrypting....
Decrypting....
RESULT:
Thus the Playfair cipher substitution technique was implemented and executed
successfully.
Ex.No. : 1c HILL CIPHER
Date :
AIM:
To implement a Hill cipher substitution technique in Java.
ALGORITHM:
1. Obtain a plaintext message to encode in standard English with no spaces.
2. Split the plaintext into group of length three. To fill this, add X at the end.
3. Convert each group of letters with length three into plaintext vectors.
4. Replace each letter by the number corresponding to its position in the alphabet i.e.
A=1, B=2, C=3…Z=0.
5. Create the keyword in a 3*3 matrix.
6. Multiply the two matrices to obtain the cipher text of length three.
7. For decryption, convert each entry in the ciphertext vector into its plaintext vector by
multiplying the cipher text vector and inverse of a matrix.
8. Thus plain text is obtained fromcorresponding plaintext vector by corresponding
position in the alphabet.
PROGRAM:
import java.util.Scanner;
import javax.swing.JOptionPane;
public class hillcipher
{
//the 3x3 key matrix for 3 characters at once
public static int[][] keymat = new int[][]
{
{ 1, 2, 1 },
{ 2, 3, 2 },
{ 2, 2, 1 },
};
public static int[][] invkeymat = new int[][]
{
{ -1, 0, 1 },
{ 2, -1, 0 },
{ -2, 2, -1},
};
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
text = text.toUpperCase();
text = text.replaceAll("\\s",""); //removing spaces
n = text.length() % 3;
if(n!=0)
{
for(int i = 1; i<= (3-n);i++)
{
text+= 'X';
}
}
System.out.println("Padded Text:" + text);
char[] ptextchars = text.toCharArray();
for(int i=0;i< text.length(); i+=3)
{
outtext += encrypt(ptextchars[i],ptextchars[i+1],ptextchars[i+2]);
}
System.out.println("Encypted Message: " + outtext);
OUTPUT:
F:\bin>javac hillcipher.java
F:\bin>java hillcipher
Enter the Plain text for Encryption:
mothertheresa
Padded Text:MO THERTHERESAXX
Encypted Message: AAHXIGPPLJEROLR
Decrypted Message: MOTHERTHERESAXX
F:\bin>java hillcipher
Enter the Plain text for Encryption:
hilcipher
Padded Text:HILCIPHER
Encypted Message: TIIWGHXIG
Decrypted Message: HILCIPHER
RESULT:
Thus the Hill cipher substitution technique was implemented and executed
successfully.
Ex.No. : 2a RAIL FENCE CIPHER
Date :
AIM:
To implement a rail fence transposition technique in Java.
ALGORITHM :
1. In the rail fence cipher, the plaintext is written downwards and diagonally on
successive "rails" of an imaginary fence, then moving up when we reach the bottom
rail.
2. When we reach the top rail, the message is written downwards again until the whole
plaintext is written out.
3. The message is then read off in rows.
PROGRAM:
class railfenceCipherHelper
{
int depth;
String encode(String msg, int depth) throws Exception
{
int r = depth;
int l = msg.length();
int c = l / depth;
int k = 0;
char mat[][] = new char[r][c];
String enc = "";
for (int i = 0; i< c; i++)
{
for (int j = 0; j < r; j++)
{
if (k != l)
{ mat[j][i] = msg.charAt(k++); }
else
{ mat[j][i] = 'X'; }
}}
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
enc += mat[i][j];
}}
return enc;
}
String decode(String encmsg, int depth) throws Exception
{
int r = depth;
int l = encmsg.length();
int c = l / depth;
int k = 0;
char mat[][] = new char[r][c];
String dec = "";
for (int i = 0; i < r; i++)
{
for (int j = 0; j < c; j++)
{
mat[i][j] = encmsg.charAt(k++);
}}
for (int i = 0; i< c; i++)
{
for (int j = 0; j < r; j++)
{
dec += mat[j][i];
}}
return dec;
}}
class railfencecipher
{
public static void main(String[] args) throws java.lang.Exception
{
railfenceCipherHelper rf = new railfenceCipherHelper();
String msg, enc, dec;
System.out.println("Enter the Plain text: ");
msg = System.console().readLine();
int depth = 2;
enc = rf.encode(msg, depth);
dec = rf.decode(enc, depth);
System.out.println("Plain Text:"+msg);
System.out.println("Encrypted Message-Cipher Text:"+enc);
System.out.printf("Decrypted Message-:"+dec);
}
}
OUTPUT:
F:\bin>javac railfencecipher.java
F:\bin>java railfencecipher
Enter the Plain text:
paulinefreeda
Plain Text:paulinefreeda
Encrypted Message-Cipher Text:puiereaalnfed
Decrypted Message-:paulinefreeda
RESULT:
Thus the Rail Fence Transposition Technique was implemented and executed
successfully.
Ex.No. : 2b ROW AND COLUMN TRANSFORMATION TECHNIQUE
Date :
AIM:
To implement a rail fence transposition technique in Java.
ALGORITHM:
1. Consider the plain text hello world, and let us apply the simple columnar transposition
technique as shown below
h e l l
o w o r
l d
2. The plain text characters are placed horizontally and the cipher text is created with
vertical format as: holewdlo lr.
3. Now, the receiver has to use the same table to decrypt the cipher text to plain text.
EXAMPLE:
PROGRAM:
import java.util.*;
class TransCipher {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the plain text");
String pl = sc.nextLine();
sc.close();
String s = "";
int start = 0;
for (int i= 0; i< pl.length(); i++) {
if (pl.charAt(i) == ' ') {
s = s + pl.substring(start, i);
start = i + 1;
}
}
s = s + pl.substring(start);
System.out.print(s);
System.out.println();
// end of space deletion
int k = s.length();
int l = 0;
int col = 4;
int row = s.length() / col;
char ch[][] = new char[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (l < k) {
ch[i][j] = s.charAt(l);
l++;
} else {
ch[i][j] = '#';
}
}
}
char trans[][] = new char[col][row];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
trans[j][i] = ch[i][j];
}}
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
System.out.print(trans[i][j]);
}}
System.out.println();
}
}
OUTPUT:
F:\bin>javac TransCipher.java
F:\bin>java TransCipher
Enter the plain text
altrozcarshervin
altrozcarshervin
aorrlzsvtchiraen
a l t r
o z c a
r s h e
r v I n
RESULT:
Thus the Row and Column Transposition Technique was implemented and executed
successfully.
Ex.No. : 3 DATA ENCRYPTION STANDARD (DES)
Date :
AIM:
To apply Data Encryption Standard (DES) Algorithm for a practical application like
User Message Encryption.
ALGORITHM:
1. Create a DES Key.
2. Create a Cipher instance from Cipher class, specify the following information
and separated by a slash (/).
Algorithm name
Mode (optional)
Padding scheme (optional)
3. Convert String into Byte[] array format.
4. Make Cipher in encrypt mode, and encrypt it with Cipher.doFinal() method.
5. Make Cipher in decrypt mode, and decrypt it with Cipher.doFinal() method.
PROGRAM:
import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random;
class DES
{
byte[] skey=new byte[1000];
String skeystring;
static byte[] raw;
String inputmessage,encryptedata,decryptedmessage;
public DES()
{
try
{
generatesymmetrickey();
inputmessage=JOptionPane.showInputDialog(null,"Enter message to
encrypt:");
byte[] ibyte =inputmessage.getBytes();
byte[] ebyte=encrypt(raw, ibyte);
String encrypteddata=new String(ebyte);
System.out.println("Encrypted message:"+encrypteddata);
JOptionPane.showMessageDialog(null,"Encrypted
Data"+"\n"+encrypteddata);
byte[] dbyte=decrypt(raw,ebyte);
String decryptedmessage=new String(dbyte);
System.out.println("Decrypted message:"+decryptedmessage);
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
SymmerticKey="+skeystring);
}
catch(Exception e)
{
System.out.println(e);
}
}
OUTPUT:
RESULT:
Thus the java program for applying Data Encryption Standard (DES) Algorithm for a
practical application of User Message Encryption is written and executed successfully.
Ex.No. : 4 AES ALGORITHM
Date :
AIM:
To apply Advanced Encryption Standard (AES) Algorithm for a practical application
like URL Encryption.
ALGORITHM:
1. AES is based on a design principle known as a substitution–permutation.
2. AES does not use a Feistel network like DES, it uses variant of Rijndael.
3. It has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.
4. AES operates on a 4 × 4 column- major order array of bytes, termed the state
PROGRAM:
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
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.
Ex.No. : 5 RSA ALGORITHM
Date :
AIM:
To implement a RSA algorithm using HTML and Javascript.
ALGORITHM:
1. Choose two prime number p and q.
2. Compute the value of n and t.
3. Find the value of public key e.
4. Compute the value of private key d.
5. Do the encryption and decryption
a. Encryption is given as,
c = te mod n
b. Decryption is given as,
t = cd mod n
PROGRAM:
rsa.html
<html>
<head>
<title>RSA Encryption</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<h1>RSA Algorithm</h1>
<h2>Implemented Using HTML & Javascript</h2>
<hr>
<table>
<tr>
<td>Enter First Prime Number:</td>
<td><input type="number" value="53" id="p"></td>
</tr>
<tr>
<td>Enter Second Prime Number:</td>
<td><input type="number" value="59" id="q"></p> </td>
</tr>
<tr>
<td>Enter the Message(cipher text):<br>[A=1, B=2,...]</td>
<td><input type="number" value="89" id="msg"></p> </td>
</tr>
<tr>
<td>Public Key:</td>
<td><p id="publickey"></p> </td>
</tr>
<tr>
<td>Exponent:</td>
<td><p id="exponent"></p> </td>
</tr>
<tr>
<td>Private Key:</td>
<td><p id="privatekey"></p></td>
</tr>
<tr>
<td>Cipher Text:</td>
<td><p id="ciphertext"></p> </td>
</tr>
<tr>
<td><button onclick="RSA();">Apply RSA</button></td>
</tr>
</table> </center>
</body>
<script type="text/javascript">
function RSA()
{
var gcd, p, q, no, n, t, e, i, x;
gcd = function (a, b) { return (!b) ? a : gcd(b, a % b); };
p = document.getElementById('p' ).value;
q = document.getElementById('q').value;
no = document.getElementById('msg').value;
n = p * q;
t = (p - 1) * (q - 1);
for (e = 2; e < t; e++)
{
if (gcd(e, t) == 1)
{
break;
}
}
for (i = 0; i < 10; i++)
{
x = 1 + i* t
if (x % e == 0)
{
d = x / e;
break;
}
}
ctt = Math.pow(no, e).toFixed(0);
ct = ctt % n;
dtt = Math.pow(ct, d).toFixed(0);
dt = dtt % n;
document.getElementById('publickey').innerHTML = n;
document.getElementById('exponent').innerHTML = e;
document.getElementById('privatekey').innerHTML = d;
document.getElementById('ciphertext').innerHTML = ct;
}
</script>
</html>
OUTPUT:
RESULT:
Thus the RSA algorithm was implemented using HTML and Javascript and executed
successfully.
Ex.No. : 6 DIFFIE-HELLMAN KEY EXCHANGE ALGORITHM
Date :
AIM:
To implement a Diffie-Hellman Key Exchange algorithm.
ALGORITHM:
1. Sender and receiver publicly agree to use a modulus p and base g which is a primitive
root modulo p.
2. Sender chooses a secret integer x then sends Bob R1 = gx mod p
3. Receiver chooses a secret integer y, then sends Alice R2 = gy mod p
4. Sender computes k1 = Bx mod p
5. Receiver computes k2 = Ay mod p
6. Sender and Receiver now share a secret key.
PROGRAM:
import java.io.*;
import java.math.BigInteger;
class dh
{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter prime number:");
BigInteger p=new BigInteger(br.readLine());
BigInteger k1=R2.modPow(x,p);
System.out.println("Key calculated at Sender's side:"+k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Receiver's side:"+k2);
System.out.println("Diffie-Hellman secret key was calculated.");
}
}
OUTPUT
C:\Security Lab New\programs>javac dh.java
RESULT:
Thus the Diffie-Hellman key exchange algorithm was implemented and executed
successfully.
Ex.No. : 7 SHA-1 ALGORITHM
Date :
AIM:
To calculate the message digest of a text using the SHA-1 algorithm in Java.
ALGORITHM:
1. Append Padding bits.
2. Append Length - 64 bits are appended to the end.
3. Prepare Processing Functions.
4. Prepare Processing Constants.
5. Initialize Buffers.
6. Processing Message in 512-bit blocks (L blocks in total message).
PROGRAM:
import java.util.Scanner;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class sha1
{
public static void main(String[] args)throws NoSuchAlgorithmException
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String message = new String();
message = sc.next();
System.out.println("Mesage Digest is=");
System.out.println(sha1(message));
}
static String sha1(String input)throws NoSuchAlgorithmException
{
MessageDigest mDigest = MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb = new StringBuffer();
for(int i = 0;i<result.length;i++)
{
sb.append(Integer.toString((result[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
OUTPUT:
C:\Security Lab New\programs>java sha1
Enter the String:
CORONA VIRUS DISEASE
Mesage Digest is=
7690b7ccb987f4b3f32d2b9e7e8a69db2d0ded02
RESULT:
Thus the Secure Hash Algorithm (SHA-1) has been implemented and executed
successfully.
Ex.No. : 8 MD-5 ALGORITHM
Date :
AIM:
Calculate the message digest of a text using the MD-5 algorithm in JAVA.
ALGORITHM:
OUTPUT:
RESULT:
Thus the Message Digest Algorithm (MD-5) has been implemented and executed
successfully.
Ex.No. : 9 DIGITAL SIGNATURE SCHEME
Date :
AIM:
To implement the signature scheme - Digital Signature Standard.
ALGORITHM:
1. Declare the class and required variables.
2. Create the object for the class in the main program.
3. Access the member functions using the objects.
4. Implement the SIGNATURE SCHEME - Digital Signature Standard.
5. It uses a hash function.
6. The hash code is provided as input to a signature function along with a random
number K generated for the particular signature.
7. The signature function also depends on the sender„s private key.
8. The signature consists of two components.
9. The hash code of the incoming message is generated.
10. The hash code and signature are given as input to a verification function.
PROGRAM:
import java.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;
}
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
{
System.out.println("\n error: incorrect digital signature\n ");
}
}
}
OUTPUT:
RESULT:
Thus the Digital Signature Standard Signature Scheme has been implemented and
executed successfully.
CONTENT BEYOND
THE SYLLABUS
Ex. No. : 10 INTRUSION DETECTION SYSTEM (IDS)
Date:
AIM:
To demonstrate Intrusion Detection System (IDS) using Snort software tool.
You can tell which interface to use by looking at the Index number and finding Microsoft.
As you can see in the above example, the other interfaces are for VMWare. My interface is
3.
9. To run snort in IDS mode, you will need to configure the file “snort.conf” according to
your network environment.
10. To specify the network address that you want to protect in snort.conf file, look for the
following line.
var HOME_NET 192.168.1.0/24 (You will normally see any here)
11. You may also want to set the addresses of DNS_SERVERS, if you have some on your
network.
Example:
example snort
12. Change the RULE_PATH variable to the path of rules folder.
var RULE_PATH c:\snort\rules
path to rules
13. Change the path of all library files with the name and path on your system. and you must
change the path of snort_dynamicpreprocessorvariable.
C:\Snort\lib\snort_dynamiccpreprocessor
You need to do this to all library files in the “C:\Snort\lib” folder. The old path might be:
“/usr/local/lib/…”. you will need to replace that path with your system path. Using
C:\Snort\lib
14. Change the path ofthe “dynamicengine” variable value in the “snort.conf” file..
Example:
dynamicengine C:\Snort\lib\snort_dynamicengine\sf_engine.dll
15 Add the paths for “include classification.config” and “include reference.config” files.
include c:\snort\etc\classification.config
include c:\snort\etc\reference.config
16. Remove the comment (#) on the line to allow ICMP rules, if it is commented with a #.
include $RULE_PATH/icmp.rules
17. You can also remove the comment of ICMP-info rules comment, if it is commented.
include $RULE_PATH/icmp- info.rules
18. To add log files to store alerts generated by snort, search for the “output log” test in
snort.conf and add the following line:
output alert_fast: snort-alerts.ids
19. Comment (add a #) the whitelist $WHITE_LIST_PATH/white_list.rules and the
blacklist
Ifa log is created, select the appropriate program to open it. You can use WordPard or
NotePad++ to read the file.
To generate Log files in ASCII mode, you can use following command while running snort in
IDS mode:
snort -A console - i3 -c c:\Snort\etc\snort.conf -l c:\Snort\log -K ascii
23. Scan the computer that is running snort from another computer by using PING or NMap
(ZenMap).
After scanning or during the scan you can check the snort-alerts.ids file in the log folder to
insure it is logging properly. You will see IP address folders appear.
Date
Aim:
Write a JAVA program to implement the BlowFish algorithm logic
Theory:
Blowfish is a symmetric-key block cipher that uses a variable-length key. It operates on 64-bit
blocks of data and can use keys between 32 bits and 448 bits in length.
Program:
import java.nio.ByteBuffer;
static {
// Initialize P-array and S-array with predefined values (for simplification, initialize with
example values)
// These should be filled with proper values as per the Blowfish specification
// For example, P-array and S-array should be filled with specific values from Blowfish's
standard
// This can be done manually or read from predefined data in a production
implementation.
}
left ^= pArray[0];
for (int i = 1; i < P_ARRAY_SIZE; i += 2) {
right ^= f(left) ^ pArray[i];
left ^= f(right) ^ pArray[i + 1];
}
encryptBlock(block);
encryptedData[i * BLOCK_SIZE] = (byte) (block[0] >> 24);
encryptedData[i * BLOCK_SIZE + 1] = (byte) (block[0] >> 16);
encryptedData[i * BLOCK_SIZE + 2] = (byte) (block[0] >> 8);
encryptedData[i * BLOCK_SIZE + 3] = (byte) (block[0]);
encryptedData[i * BLOCK_SIZE + 4] = (byte) (block[1] >> 24);
encryptedData[i * BLOCK_SIZE + 5] = (byte) (block[1] >> 16);
encryptedData[i * BLOCK_SIZE + 6] = (byte) (block[1] >> 8);
encryptedData[i * BLOCK_SIZE + 7] = (byte) (block[1]);
}
return encryptedData;
}
decryptBlock(block);
decryptedData[i * BLOCK_SIZE] = (byte) (block[0] >> 24);
decryptedData[i * BLOCK_SIZE + 1] = (byte) (block[0] >> 16);
decryptedData[i * BLOCK_SIZE + 2] = (byte) (block[0] >> 8);
decryptedData[i * BLOCK_SIZE + 3] = (byte) (block[0]);
decryptedData[i * BLOCK_SIZE + 4] = (byte) (block[1] >> 24);
decryptedData[i * BLOCK_SIZE + 5] = (byte) (block[1] >> 16);
decryptedData[i * BLOCK_SIZE + 6] = (byte) (block[1] >> 8);
decryptedData[i * BLOCK_SIZE + 7] = (byte) (block[1]);
}
return decryptedData;
}
// Encrypting data
byte[] encrypted = blowfish.encrypt(data);
System.out.println("Encrypted Data (Base64 encoded): " + bytesToHex(encrypted));
// Decrypting data
byte[] decrypted = blowfish.decrypt(encrypted);
System.out.println("Decrypted Data: " + new String(decrypted));
}
// Helper method to convert byte array to hex string for easy visualization
private static String bytesToHex(byte[] bytes) {
StringBuilder hex = new StringBuilder();
for (byte b : bytes) {
hex.append(String.format("%02X ", b));
}
return hex.toString().trim();
}
}
OUTPUT:
RESULT:
Thus the BlowFish algorithm logic has been implemented and executed successful.