0% found this document useful (0 votes)
231 views65 pages

Security Lab Manual Overview

The document describes a lab manual for a security laboratory course. It contains 12 experiments covering topics like encryption/decryption algorithms (Caesar cipher, Playfair cipher, Hill cipher, Vigenere cipher, DES, AES), RSA, Diffie-Hellman key exchange, SHA-1, digital signatures, intrusion detection using Snort, attack tools like N-Stalker, malware, and cryptography topics beyond the syllabus like program obfuscation and cryptocurrency. It provides code samples and procedures for experiments on Caesar cipher and Playfair cipher encryption. The experiments are designed to help students learn and implement classic and modern cryptographic algorithms and analyze security applications in practice.

Uploaded by

PonGopal P
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)
231 views65 pages

Security Lab Manual Overview

The document describes a lab manual for a security laboratory course. It contains 12 experiments covering topics like encryption/decryption algorithms (Caesar cipher, Playfair cipher, Hill cipher, Vigenere cipher, DES, AES), RSA, Diffie-Hellman key exchange, SHA-1, digital signatures, intrusion detection using Snort, attack tools like N-Stalker, malware, and cryptography topics beyond the syllabus like program obfuscation and cryptocurrency. It provides code samples and procedures for experiments on Caesar cipher and Playfair cipher encryption. The experiments are designed to help students learn and implement classic and modern cryptographic algorithms and analyze security applications in practice.

Uploaded by

PonGopal P
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/ 65

SRM VALLIAMMAI ENGINEERING COLLEGE

SRM NAGAR, KATTANKULATHUR -603203

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LAB MANUAL

IT8761 SECURITY LABORATORY


2017 REGULATION
(IV YEAR CSE/ SEVENTH SEMESTER)

PREPARED BY

Mr. N. LEO BRIGHT TENNISSON,


Assistant Professor [Sr. G.]
Ms.A.VIDHYA
Assistant Professor [Sr. G.]
Department of Computer Science and Engineering,
SRM Valliammai Engineering College.
INDEX
S.No TOPICS PAGE NO
1 Perform encryption, decryption using the following
substitution techniques
(i) Ceaser cipher
(ii) playfair cipher
(iii) Hill Cipher
(iv) Vigenere cipher
2 Perform encryption and decryption using following
transposition techniques
i) Rail fence
ii) row & Column Transformation
3 Apply DES algorithm for practical applications.
4 Apply AES algorithm for practical applications.
5 Implement RSA Algorithm using HTML and
JavaScript
6 Implement the Diffie-Hellman Key Exchange
algorithm for a given problem
7 Calculate the message digest of a text using the
SHA-1 algorithm.
8 Implement the SIGNATURE SCHEME - Digital
Signature Standard.
9 Demonstrate intrusion detection system (ids) using
any tool eg. Snort or any other s/w.
10 Automated Attack and Penetration Tools
 Exploring N-Stalker, a Vulnerability
Assessment Tool
11 Defeating Malware
i) Building Trojans
ii) Rootkit Hunter
12 VIVA QUESTIONS
TOPIC BEYOND SYLLABUS

1. Program Obfuscation
2. Computing over encrypted data (Fully
Homomorhpic Encryption (FHE), Functional
Encryption (FE))
3. Failures of Cryptography (Cryptanalysis and
Attacks)
4. Crypto Currency (Bitcoin) and Smart Contracts
(Ethereum)
5. Memory Hard Functions (e.g., Script, Argon )
Ex. No. 1.A) CAESAR CIPHER
Date:

Aim: To write a program to perform encryption and decryption using Caesar Cipher
Procedure:
1. Traverse the given text one character at a time .
2. For each character, transform the given character as per the rule, depending
on whether we’re encrypting or decrypting the text.
3. Return the new string generated.

Examples :

Text : ABCDEFGHIJKLMNOPQRSTUVWXYZ
Shift: 23
Cipher: XYZABCDEFGHIJKLMNOPQRSTUVW

Text : ATTACKATONCE
Shift: 4
Cipher: EXXEGOEXSRGI

Program

public class Program


{
static String caesar(String value, int shift)
{
// Convert to char array.
char[] buffer = value.toCharArray();
// Loop over characters.
for (int i = 0; i < buffer.length; i++)
{
// Shift letter, moving back or forward 26 places if needed.
char letter = buffer[i];
letter = (char) (letter + shift); if (letter > 'z')
{
letter = (char) (letter - 26);
} else if (letter < 'a')
{
letter = (char) (letter + 26);
}
buffer[i] = letter;
}
// Return final string.
return new String(buffer);
}
public static void main(String[] args)
{
// Test the cipher method.
String a = "test";
System.out.println(a);
System.out.println();
String b = caesar(a, 18);
String c = caesar(b, -18);
System.out.println(b);
System.out.println(c);
System.out.println();
String d = caesar(a, 1);
String e = caesar(d, -1);
System.out.println(d);
System.out.println(e);
System.out.println();
String f = "exxegoexsrgi";
String g = caesar(f, -4);
System.out.println(f);
System.out.println(g);
}
}

OUTPUT
test
lwkl
test
uftu
test
exxegoexsrgi
attackatonce
Ex. No. 1.B)
JAVA PROGRAM TO ENCODE A MESSAGE USING PLAYFAIR CIPHER
Date:

Aim: To write a program to perform encryption using Playfair Cipher

Vertion 1[small coding –PLAYFAIR CIPHER- ENCRYPTION & DECRYPTION


COMBINED]

import java.awt.Point;
import java.util.Scanner;

public class PlayfairCipher {


private static char[][] charTable;
private static Point[] positions;

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

String key = prompt("Enter an encryption key (min length 6): ", sc,
6);
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n: ", sc, 1);

boolean changeJtoI = jti.equalsIgnoreCase("y");

createTable(key, changeJtoI);

String enc = encode(prepareText(txt, changeJtoI));

System.out.printf("%nEncoded message: %n%s%n", enc);


System.out.printf("%nDecoded message: %n%s%n", decode(enc));
}

private static String prompt(String promptText, Scanner sc, int minLen)


{
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trim();
} while (s.length() < minLen);
return s;
}

private static String prepareText(String s, boolean changeJtoI) {


s = s.toUpperCase().replaceAll("[^A-Z]", "");
return changeJtoI ? s.replace("J", "I") : s.replace("Q", "");
}

private static void createTable(String key, boolean changeJtoI) {


charTable = new char[5][5];
positions = new Point[26];

String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ",


changeJtoI);

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

private static String codec(StringBuilder text, int direction) {


int len = text.length();
for (int i = 0; i < len; i += 2) {
char a = text.charAt(i);
char b = text.charAt(i + 1);

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 + direction) % 5;
col2 = (col2 + direction) % 5;

} else if (col1 == col2) {


row1 = (row1 + direction) % 5;
row2 = (row2 + direction) % 5;

} else {
int tmp = col1;
col1 = col2;
col2 = tmp;
}
text.setCharAt(i, charTable[row1][col1]);
text.setCharAt(i + 1, charTable[row2][col2]);
}
return text.toString();
}
}

Procedure:
The Algorithm consists of 2 steps:
1. Generate the key Square(5×5):
 The key square is a 5×5 grid of alphabets that acts as the key for
encrypting the plaintext. Each of the 25 alphabets must be unique and one
letter of the alphabet (usually J) is omitted from the table (as the table can
hold only 25 alphabets). If the plaintext contains J, then it is replaced by I.
 The initial alphabets in the key square are the unique alphabets of the
key in the order in which they appear followed by the remaining letters of
the alphabet in order.
For example:

The key is "monarchy"


Thus the initial entires are
'm', 'o', 'n', 'a', 'r', 'c', 'h', 'y'
followed by remaining characters of
a-z(except 'j') in that order.

2. Algorithm to encrypt the plain text: The plaintext is split into pairs of two letters
(digraphs). If there is an odd number of letters, a Z is added to the last letter.
For example:
PlainText: "instruments"
After Split: 'in' 'st' 'ru' 'me' 'nt' 'sz'

Rules for Encryption:

 If both the letters are in the same column: Take the letter below each one (going
back to the top if at the bottom).
 If both the letters are in the same row: Take the letter to the right of each one
(going back to the leftmost if at the rightmost position).
 If neither of the above rules is true: Form a rectangle with the two letters and take
the letters on the horizontal opposite corner of the rectangle.

Plain Text: "instrumentsz"


Encrypted Text: gatlmzclrqtx
Encryption:
i -> g
n -> a
s -> t
t -> l
r -> m
u -> z
m -> c
e -> l
n -> r
t -> q
s -> t
z -> x

Program

package com.sanfoundry.setandstring;
import java.util.Scanner;
public class PlayfairCipherEncryption
{
private String KeyWord = new String();
private String Key = new String();
private char matrix_arr[][] = new char[5][5];
public void setKey(String k)
{
String K_adjust = new String();
3oolean flag = false;
K_adjust = K_adjust + k.charAt(0);
for (int i = 1; i < k.length(); i++)
{
for (int j = 0; j < K_adjust.length(); j++)
{
if (k.charAt(i) == K_adjust.charAt(j))
{
flag = true;
}
}
if (flag == false)
K_adjust = K_adjust + k.charAt(i);
flag = false;
}
KeyWord = K_adjust;
}
public void KeyGen()
{
Boolean flag = true;
char current;
Key = KeyWord;
for (int i = 0; i < 26; i++)
{
current = (char) (i + 97);
if (current == ‘j’)
continue;
for (int j = 0; j < KeyWord.length(); j++)
{
if (current == KeyWord.charAt(j))
{
flag = false;
break;
}
}
if (flag)
Key = Key + current;
flag = true;
}
System.out.println(Key);
matrix();
}
private void matrix()
{
int counter = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
matrix_arr[i][j] = Key.charAt(counter);
System.out.print(matrix_arr[i][j] + “ “);
counter++;
}
System.out.println();
}
}
private String format(String old_text)
{
int i = 0;
int len = 0;
String text = new String();
len = old_text.length();
for (int tmp = 0; tmp < len; tmp++)
{
if (old_text.charAt(tmp) == ‘j’)
{
text = text + ‘i’;
}
else
text = text + old_text.charAt(tmp);
}
len = text.length();
for (i = 0; i < len; i = i + 2)
{
if (text.charAt(i + 1) == text.charAt(i))
{
text = text.substring(0, i + 1) + ‘x’ + text.substring(i + 1);
}
}
return text;
}
private String[] Divid2Pairs(String new_string)
{
String Original = format(new_string);
int size = Original.length();
if (size % 2 != 0)
{
size++;
Original = Original + ‘x’;
}
String x[] = new String[size / 2];
int counter = 0;
for (int i = 0; i < size / 2; i++)
{
x[i] = Original.substring(counter, counter + 2);
counter = counter + 2;
}
return x;
}
public int[] GetDiminsions(char letter)
{
int[] key = new int[2];
if (letter == ‘j’)
letter = ‘i’;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (matrix_arr[i][j] == letter)
{
key[0] = i;
key[1] = j;
break;
}
}
}
return key;
}

public String encryptMessage(String Source)


{
String src_arr[] = Divid2Pairs(Source);
String Code = new String();
char one;
char two;
int part1[] = new int[2];
int part2[] = new int[2];
for (int i = 0; i < src_arr.length; i++)
{
one = src_arr[i].charAt(0);
two = src_arr[i].charAt(1);
part1 = GetDiminsions(one);
part2 = GetDiminsions(two);
if (part1[0] == part2[0])
{
if (part1[1] < 4)
part1[1]++;
else
part1[1] = 0;
if (part2[1] < 4)
part2[1]++;
else
part2[1] = 0;
}
else if (part1[1] == part2[1])
{
if (part1[0] < 4)
part1[0]++;
else
part1[0] = 0;
if (part2[0] < 4)
part2[0]++;
else
part2[0] = 0;
}
else
{
int temp = part1[1];
part1[1] = part2[1];
part2[1] = temp;
}
Code = Code + matrix_arr[part1[0]][part1[1]]
+ matrix_arr[part2[0]][part2[1]];
}
return Code;
}

public static void main(String[] args)


{
PlayfairCipherEncryption x = new PlayfairCipherEncryption();
Scanner sc = new Scanner(System.in);
System.out.println(“Enter a keyword:”);
String keyword = sc.next();
x.setKey(keyword);
x.KeyGen();
System.out .println(“Enter word to encrypt: (Make sure length of message is even)”);
String key_input = sc.next();
if (key_input.length() % 2 == 0)
{
System.out.println(“Encryption: “ + x.encryptMessage(key_input));
}
else
{
System.out.println(“Message length should be even”);
}
sc.close();
}
}

OUTPUT
$ javac PlayfairCipherEncryption.java
$ java PlayfairCipherEncryption
Enter a keyword:
Sanfoundry
Sanfoudrybceghiklmpqstvwxz
Sanfo
udryb
ceghi
klmpq
stvwx
Enter word to encrypt: (Make sure length of message is even)
Learningcenter
Encryption: acndogrmegavgd
Ex. No. 1. B ii) JAVA PROGRAM TO DECODE A MESSAGE ENCODED USING PLAYFAIR CIPHER

Aim: To write a program to perform decryption using Playfair Cipher

Procedure:
The Playfair Cipher Decryption Algorithm:
The Algorithm consistes of 2 steps:
1. Generate the key Square(5×5) at the receiver’s end:
The key square is a 5×5 grid of alphabets that acts as the key for encrypting the plaintext.
Each of the 25 alphabets must be unique and one letter of the alphabet (usually J) is omitted
from the table (as the table can hold only 25 alphabets). If the plaintext contains J, then it is
replaced by I.
 The initial alphabets in the key square are the unique alphabets of the key in the order
in which they appear followed by the remaining letters of the alphabet in order.

For example:
The key is "monarchy"
Thus the initial entires are
'm', 'o', 'n', 'a', 'r', 'c', 'h', 'y'
followed by remaining characters of
a-z(except 'j') in that order.

2. Algorithm to decrypt the ciphertext: The ciphertext is split into pairs of two letters
(digraphs).
For example:
CipherText: "gatlmzclrqtx"
After Split: 'ga' 'tl' 'mz' 'cl' 'rq' 'tx'
Rules for Decryption:
 If both the letters are in the same column: Take the letter above each one
(going back to the bottom if at the top).
For example:
Diagraph: "cl"
Decrypted Text: me
Decryption:
c -> m
l -> e
 If both the letters are in the same row: Take the letter to the left of each one (going
back to the rightmost if at the leftmost position).
 If neither of the above rules is true: Form a rectangle with the two letters and take
the letters on the horizontal opposite corner of the rectangle.

Program

package com.sanfoundry.setandstring;
import java.util.Scanner;
public class PlayfairCipherDecryption
{
private String KeyWord = new String();
private String Key = new String();
private char matrix_arr[][] = new char[5][5];
public void setKey(String k)
{
String K_adjust = new String();
boolean flag = false;
K_adjust = K_adjust + k.charAt(0);
for (int i = 1; i < k.length(); i++)
{
for (int j = 0; j < K_adjust.length(); j++)
{
if (k.charAt(i) == K_adjust.charAt(j))
{
flag = true;
}
}
if (flag == false)
K_adjust = K_adjust + k.charAt(i);
flag = false;
}
KeyWord = K_adjust;
}

public void KeyGen()


{
boolean flag = true;
char current;
Key = KeyWord;
for (int i = 0; i < 26; i++)
{
current = (char) (i + 97);
if (current == 'j')
continue;
for (int j = 0; j < KeyWord.length(); j++)
{
if (current == KeyWord.charAt(j))
{
flag = false;
break;
}
}
if (flag)
Key = Key + current;
flag = true;
}
System.out.println(Key);
matrix();
}
private void matrix()
{
int counter = 0;
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
matrix_arr[i][j] = Key.charAt(counter);
System.out.print(matrix_arr[i][j] + " ");
counter++;
}
System.out.println();
}

private String format(String old_text)


{
int i = 0;
int len = 0;
String text = new String();
len = old_text.length();
for (int tmp = 0; tmp < len; tmp++)
{
if (old_text.charAt(tmp) == 'j')
{
text = text + 'i';
}
else
text = text + old_text.charAt(tmp);
}
len = text.length();
for (i = 0; i < len; i = i + 2)
{
if (text.charAt(i + 1) == text.charAt(i))
{
text = text.substring(0, i + 1) + 'x' + text.substring(i + 1);
}
}
return text;
}

private String[] Divid2Pairs(String new_string)


{
String Original = format(new_string);
int size = Original.length();
if (size % 2 != 0)
{
size++;
Original = Original + 'x';
}
String x[] = new String[size / 2];
int counter = 0;
for (int i = 0; i < size / 2; i++)
{
x[i] = Original.substring(counter, counter + 2);
counter = counter + 2;
}
return x;
}

public int[] GetDiminsions(char letter)


{
int[] key = new int[2];
if (letter == 'j')
letter = 'i';
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 5; j++)
{
if (matrix_arr[i][j] == letter)
{
key[0] = i;
key[1] = j;
break;
}
}
}
return key;
}

public String encryptMessage(String Source)


{
String src_arr[] = Divid2Pairs(Source);
String Code = new String();
char one;
char two;
int part1[] = new int[2];
int part2[] = new int[2];
for (int i = 0; i < src_arr.length; i++)
{
one = src_arr[i].charAt(0);
two = src_arr[i].charAt(1);
part1 = GetDiminsions(one);
part2 = GetDiminsions(two);
if (part1[0] == part2[0])
{
if (part1[1] < 4)
part1[1]++;
else
part1[1] = 0;
if (part2[1] < 4)
part2[1]++;
else
part2[1] = 0;
}
else if (part1[1] == part2[1])
{
if (part1[0] < 4)
part1[0]++;
else
part1[0] = 0;
if (part2[0] < 4)
part2[0]++;
else
part2[0] = 0;
}
else
{
int temp = part1[1];
part1[1] = part2[1];
part2[1] = temp;
}
Code = Code + matrix_arr[part1[0]][part1[1]]
+ matrix_arr[part2[0]][part2[1]];
}
return Code;
}
public String decryptMessage(String Code)
{
String Original = new String();
String src_arr[] = Divid2Pairs(Code);
char one;
char two;
int part1[] = new int[2];
int part2[] = new int[2];
for (int i = 0; i < src_arr.length; i++)
{
one = src_arr[i].charAt(0);
two = src_arr[i].charAt(1);
part1 = GetDiminsions(one);
part2 = GetDiminsions(two);
if (part1[0] == part2[0])
{
if (part1[1] > 0)
part1[1]--;
else
part1[1] = 4;
if (part2[1] > 0)
part2[1]--;
else
part2[1] = 4;
}
else if (part1[1] == part2[1])
{
if (part1[0] > 0)
part1[0]--;
else
part1[0] = 4;
if (part2[0] > 0)
part2[0]--;
else
part2[0] = 4;

}
else
{
int temp = part1[1];
part1[1] = part2[1];
part2[1] = temp;
}
Original = Original + matrix_arr[part1[0]][part1[1]] + matrix_arr[part2[0]][part2[1]];
}
return Original;
}
public static void main(String[] args)
{
PlayfairCipherDecryption x = new PlayfairCipherDecryption();
Scanner sc = new Scanner(System.in);
System.out.println("Enter a keyword:");
String keyword = sc.next();
x.setKey(keyword);
x.KeyGen();
System.out.println("Enter word to encrypt: (Make sure length of message is even)");
String key_input = sc.next();
if (key_input.length() % 2 == 0)
{
System.out.println("Encryption: " + x.encryptMessage(key_input));
System.out.println("Decryption: "+ x.decryptMessage(x.encryptMessage(key_input)));
}
else
{
System.out.println("Message length should be even");
}
sc.close();
}
}
OUTPUT
$ javac PlayfairCipherDecryption.java
$ java PlayfairCipherDecryption
Enter a keyword:
sanfoundry
sanfoudrybceghiklmpqtvwxz
sanfo
udryb
ceghi
klmpq
tvwxz
Enter word to encrypt: (Make sure length of message is even)
learning
Encryption: vlndogrm
Decryption: learning
Ex. No. 1.C) Hill CIPHER
Date:

Aim: To write a program to perform encryption and decryption using Hill Cipher
Procedure:

Hill Cipher
 The Hill cipher is a poly-graphic substitution cipher (plaintext letters are substituted in
larger groups, instead of substituting letters individually i.e. Works on multiple letters at
same time).
 In this Hill cipher technique, the KEY and PLAINTEXT must be in the form of
square matrix.
 The KEY must be chosen randomly according to PLAINTEXT.

ENCRYPTION:
1. To encrypt the message, we will use the formula C=K.P mod 26 where C is
Ciphertext, K is the Key, P is Plaintext.
2. Each letter is represented by a number modulo 26. Often following simple scheme is
used.

3. By using above value table we have to write the corresponding numbers of alphabets
present in KEY and PLAINTEXT.
4. For example:
PLAINTEXT message: ATTACK, KEY:CDDG
1) Find inverse of random chosen key matrix
2) Multiply Inverse matrix with ciphertext against mod 26
Original Plaintext = [(Inverse of key matrix) x (Ciphertext)] mod 26
Program

import java.io.*;
import java.util.*;
import java.io.*;
public class HillCipher {
static float[][]decrypt=new float[3][1];
static float[][] a=new float[3][3];
static float[][] b=newfloat[3][3]; static float[][] mes=newfloat[3][1];
staticfloat[][ ]res=new float[3][1];
static BufferedReaderbr=new BufferedReader(newInputStreamReader(System.in));
static
Scannersc=new Scanner(System.in);
public static void main(String[]args) throws IOException {
//TODO code application logic here get keymes();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++){
res[i][j]=res[i][j]+a[i][k]*mes[k][j];
}
System.out.print("\nEncryptedstringis:");
for(int i=0;i<3;i++) {
System.out.print((char)(res[i][0]%26+97));
res[i][0]=res[i][0];
}
inverse();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++) {
decrypt[i][j]=decrypt[i][j]+b[i][k]*res[k][j];
}
System.out.print("\nDecryptedstringis:");
for(int i=0;i<3;i++) {
System.out.print((char)(decrypt[i][0]%26+97));
}
System.out.print("\n");
}
Public static void getkeymes( )throwsIOException {
System.out.println("Enter3x3matrixforkey(Itshouldbeinversible):");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j]=sc.nextFloat();
System.out.print("\nEntera3letterstring:");
Stringmsg=br.readLine();
for(int i=0;i<3;i++)
mes[i][0]=msg.charAt(i)-97;
}
Public static void inverse() {
float p,q;
float[][] c=a;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++){
//a[i][j]=sc.nextFloat();
if(i==j)
b[i][j]=1;
else
b[i][j]=0;
}
for(int k=0;k<3;k++) {
for(int i=0;i<3;i++ ){
p=c[i][k];
q=c[k][k];
for(intj=0;j<3;j++) { if(i!=k) {
c[i][j]=c[i][j]*q-p*c[k][j];
b[i][j]=b[i][j]*q-p*b[k][j];

}}}}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) { b[i][j]=b[i][j]/c[i][i];
}
System.out.println("");
System.out.println("\nInverseMatrixis:");
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++)
System.out.print(b[i][j]+" ");
System.out.print("\n");}
}}
OUTPUT:
Enter a 3 letter string: hai
Encrypted string is: fdx
Inverse Matrix is:
0.083333336 0.41666666 -0.33333334
-0.41666666 -0.083333336 0.6666667
0.5833333 -0.083333336 -0.33333334

Decrypted string is: hai


Ex. No. 1. D) VIGENERE CIPHER
Date:

Aim: To write a program to perform encryption and decryption using VIGENERE Cipher
Procedure:

1.d) VIGENERE CYPHER

Program

package com.sanfoundry.setandstring;
public class VigenereCipher
{
public static String encrypt(String text, final String key)
{
String res = "";
text = text.toUpperCase();
for (int i = 0, j = 0; i < text.length(); i++)
{
char c = text.charAt(i);
if (c < 'A' || c > 'Z')
continue;
res += (char) ((c + key.charAt(j) - 2 * 'A') % 26 + 'A');
j = ++j % key.length();
}
return res;
}
public static String decrypt(String text, final String key)
{
String res = "";
text = text.toUpperCase();
for (int i = 0, j = 0; i < text.length(); i++)
{
char c = text.charAt(i);
if (c < 'A' || c > 'Z')
continue;
res += (char) ((c - key.charAt(j) + 26) % 26 + 'A');
j = ++j % key.length();
}
return res;
}
public static void main(String[] args)
{
String key = "VIGENERECIPHER";
String message = "Beware the Jabberwock, my son! The jaws that bite, the claws that catch!";
String encryptedMsg = encrypt(message, key);
System.out.println("String: " + message);
System.out.println("Encrypted message: " + encryptedMsg);
System.out.println("Decrypted message: " + decrypt(encryptedMsg, key));
}
}

OUTPUT
$ javac VigenereCipher.java
$ java VigenereCipher
String: Beware the Jabberwock, my son! The jaws that bite, the claws that catch!
Encrypted message:
WMCEEIKLGRPIFVMEUGXQPWQVIOIAVEYXUEKFKBTALVXTGAFXYEVKPAGY
Decrypted message: BEWARETHEJABBERWOCKMYSONTHEJAWSTHATBITETHECLAWSTHATCATCH

Ex. No. 2.A) RAIL FENCE CIPHER


Date:
Aim: To write a program to perform encryption and decryption using RAIL FENCE Cipher
Procedure:

Program

// File Name: RailFence.java


import java.util.*;
class RailFenceBasic{
int depth;
String Encryption(String plainText,int depth)throws Exception
{
int r=depth,len=plainText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String cipherText="";
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
if(k!=len)
mat[j][i]=plainText.charAt(k++);
else
mat[j][i]='X';
}
}
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
cipherText+=mat[i][j];
}
}
return cipherText;
}
String Decryption(String cipherText,int depth)throws Exception
{
int r=depth,len=cipherText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String plainText="";
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
mat[i][j]=cipherText.charAt(k++);
}
}
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
plainText+=mat[j][i];
}
}
return plainText;
}
}
class RailFence{
public static void main(String args[])throws Exception
{
RailFenceBasic rf=new RailFenceBasic();
Scanner scn=new Scanner(System.in);
int depth;
String plainText,cipherText,decryptedText;
System.out.println("Enter plain text:");
plainText=scn.nextLine();
System.out.println("Enter depth for Encryption:");
depth=scn.nextInt();
cipherText=rf.Encryption(plainText,depth);
System.out.println("Encrypted text is:\n"+cipherText);
decryptedText=rf.Decryption(cipherText, depth);
System.out.println("Decrypted text is:\n"+decryptedText);
}
}
OUTPUT
Enter plain text: railfencecipher
Enter depth for Encryption: 3
Encrypted text is: rlnchafcieieepr
Decrypted text is: railfenceciphe
Ex. No. 2.A) TRANSPOSITION CIPHER
Date:
Aim: To write a program to perform encryption and decryption using Transposition Cipher
Procedure:
The columnar transposition cipher is a fairly simple, easy to implement cipher. It is a
transposition cipher that follows a simple rule for mixing up the characters in the plaintext to
form the ciphertext.

Example
The key for the columnar transposition cipher is a keyword e.g. GERMAN. The
row length that is used is the same as the length of the keyword. To encrypt
a piece of text, e.g.
defend the east wall of the castle

we write it out in a special way in a number of rows (the keyword here


is GERMAN):
GERMAN
d e f e n d
t h e e a s
t w a l l o
f t h e c a
s t l e x x
In the above example, the plaintext has been padded so that it neatly fits in
a rectangle. This is known as a regular columnar transposition. An irregular
columnar transposition leaves these characters blank, though this makes
decryption slightly more difficult. The columns are now reordered such that
the letters in the key word are ordered alphabetically.

AEGMNR
n e d e d f
a h t e s e
l w t l o a
c t f e a h
x t s e x l
The ciphertext is read off along the columns:

nalcxehwttdttfseeleedsoaxfeahl

Program
<!doctype html>
<html>
<head>
<title>Practical Cryptography</title>
</head>

<body id="ciphers">
<h1>Columnar Transposition Cipher</h1>
<script type="text/javascript">
function Encrypt() {
plaintext = document.getElementById("p").value.toLowerCase().replace(/[^a-z]/g, "");
if(plaintext.length < 1){ alert("please enter some plaintext"); return; }
var key = document.getElementById("key").value.toLowerCase().replace(/[^a-z]/g, "");
var pc = document.getElementById("pc").value.toLowerCase().replace(/[^a-z]/g, "");
if(pc=="") pc = "x";
while(plaintext.length % key.length != 0) plaintext += pc.charAt(0);
var colLength = plaintext.length / key.length;
var chars = "abcdefghijklmnopqrstuvwxyz";
ciphertext = ""; k=0;
for(i=0; i < key.length; i++){
while(k<26){
t = key.indexOf(chars.charAt(k));
arrkw = key.split(""); arrkw[t] = "_"; key = arrkw.join("");
if(t >= 0) break;
else k++;
}
for(j=0; j < colLength; j++) ciphertext += plaintext.charAt(j*key.length + t);
}
document.getElementById("c").value = ciphertext;
}
function Decrypt(f) {
ciphertext = document.getElementById("c").value.toLowerCase().replace(/[^a-z]/g, "");
if(ciphertext.length < 1){ alert("please enter some ciphertext (letters only)"); return; }
keyword = document.getElementById("key").value.toLowerCase().replace(/[^a-z]/g, "");
klen = keyword.length;
if(klen <= 1){ alert("keyword should be at least 2 characters long"); return; }
if(ciphertext.length % klen != 0){ alert("ciphertext has not been padded, the result may be
incorrect (incorrect keyword?)."); }
// first we put the text into columns based on keyword length
var cols = new Array(klen);
var colLength = ciphertext.length / klen;
for(i=0; i < klen; i++) cols[i] = ciphertext.substr(i*colLength,colLength);
// now we rearrange the columns so that they are in their unscrambled state
var newcols = new Array(klen);
chars="abcdefghijklmnopqrstuvwxyz"; j=0;i=0;
while(j<klen){
t=keyword.indexOf(chars.charAt(i));
if(t >= 0){
newcols[t] = cols[j++];
arrkw = keyword.split(""); arrkw[t] = "_"; keyword = arrkw.join("");
}else i++;
}
// now read off the columns row-wise
plaintext = "";
for(i=0; i < colLength; i++){
for(j=0; j < klen; j++) plaintext += newcols[j].charAt(i);
}
document.getElementById("p").value = plaintext;
}
</script>

<p>This is a JavaScript implementation of the Columnar Transposition Cipher. This


implementation pads the
plaintext so that its length is a multiple of the key length.</p>
Plaintext<br>
<textarea id="p" name="p" rows="4" cols="50">attack at dawn</textarea>
<p> keyword = <input id="key" name="key" size="10" value="zebra" type="text"> pad
character = <input id="pc" name="pc" size="1" value="x" type="text"></p>
<p><input name="btnEn" value="v Encrypt v" onclick="Encrypt()" type="button">
<input name="btnDe" value="^ Decrypt ^" onclick="Decrypt()" type="button"></p>
<p>Ciphertext<br><textarea id="c" name="c" rows="4" cols="50"></textarea> </p>
</script>
</body>
</html>
ENCRYPTION

DECRYPTION
Ex. No. 3 DES ALGORITHM
Date:

Aim: To write a program to perform encryption and decryption using DES ALGORITHM
Procedure:
Program

DATA ENCRYPTION DECRYPTION USING DES ALGORITHM

package com.anuj.security.encryption;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class DESEncryptionDecryption {
private static Cipher encryptCipher;
private static Cipher decryptCipher;
public static void main(String[] args) {
try {
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey secretKey = keygenerator.generateKey();
encryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
encryptCipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedData = encryptData("Classified Information!");
decryptCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
decryptCipher.init(Cipher.DECRYPT_MODE, secretKey);
decryptData(encryptedData);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
}
}
/**
* Encrypt Data
* @param data
* @return
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
private static byte[] encryptData(String data)
throws IllegalBlockSizeException, BadPaddingException {
System.out.println("Data Before Encryption :" + data);
byte[] dataToEncrypt = data.getBytes();
byte[] encryptedData = encryptCipher.doFinal(dataToEncrypt);
System.out.println("Encryted Data: " + encryptedData);
return encryptedData;
}
/**
* Decrypt Data
* @param data
* @throws IllegalBlockSizeException
* @throws BadPaddingException
*/
private static void decryptData(byte[] data)
throws IllegalBlockSizeException, BadPaddingException {
byte[] textDecrypted = decryptCipher.doFinal(data);
System.out.println("Decryted Data: " + new String(textDecrypted));
}
}
Here,
DES = Data Encryption Standard.
ECB = Electronic Codebook mode.
PKCS5Padding = PKCS #5-style padding
While initializing Cipher, we can pass Key,Certificate and AlgorithParameters as well.

OUTPUT
Data Before Encryption :Classified Information!
Encryted Data: [B@bc6007
Decryted Data: Classified Information!
Ex. No. 4 AES ALGORITHM
Date:

Aim: To write a program to perform encryption and decryption using AES ALGORITHM
Procedure:
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.getB
ytes("UTF-8")));
}
catch (Exception e)
{
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;
}
}

2. Encryption and decryption example

Let’s test if we are able to get the decrypted string back from encrypted string.

public static void main(String[] args)


{
final String secretKey = "ssshhhhhhhhhhh!!!!";

String originalString = "howtodoinjava.com";


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

System.out.println(originalString);
System.out.println(encryptedString);
System.out.println(decryptedString);
}

Output:
howtodoinjava.com
Tg2Nn7wUZOQ6Xc+1lenkZTQ9ZDf9a2/RBRiqJBCIX6o=
howtodoinjava.com

Ex. No. 5 RSA ALGORITHM


Date:

Aim: To write a HTML and JAVA SCRIPT program to perform encryption and decryption
using RSA ALGORITHM
Procedure:

Download

Go to https://github.com/travist/jsencrypt to download this library.


Website & Demo

http://travistidwell.com/jsencrypt
How to use this library.

This library should work hand-in-hand with openssl. With that said, here is how to
use this library.

 Within your terminal (Unix based OS) type the following.

openssl genrsa -out rsa_1024_priv.pem 1024


 This generates a private key, which you can see by doing the following…

cat rsa_1024_priv.pem
 You can then copy and paste this in the Private Key section of within index.html.
 Next, you can then get the public key by executing the following command.
openssl rsa -pubout -in rsa_1024_priv.pem -out
rsa_1024_pub.pem
 You can see the public key by typing…
cat rsa_1024_pub.pem

 Now copy and paste this in the Public key within the index.html.
 Now you can then convert to and from encrypted text by doing the following in code.
Program

!doctype html>
<html>
<head>
<title>JavaScript RSA Encryption</title>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="bin/jsencrypt.min.js"></script>
<script type="text/javascript">

// Call this code when the page is done loading.


$(function() {

// Run a quick encryption/decryption when they click.


$('#testme').click(function() {

// Encrypt with the public key...


var encrypt = new JSEncrypt();
encrypt.setPublicKey($('#pubkey').val());
var encrypted = encrypt.encrypt($('#input').val());

// Decrypt with the private key...


var decrypt = new JSEncrypt();
decrypt.setPrivateKey($('#privkey').val());
var uncrypted = decrypt.decrypt(encrypted);

// Now a simple check to see if the round-trip worked.


if (uncrypted == $('#input').val()) {
alert('It works!!!');
}
else {
alert('Something went wrong....');
}
});
});
</script>
</head>
<body>
<label for="privkey">Private Key</label><br/>
<textarea id="privkey" rows="15" cols="65">-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDlOJu6TyygqxfWT7eLtGDwajtNFOb9I5XRb6khyfD1Yt3YiCgQ
WMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76xFxdU6jE0NQ+Z+zEdhUTooNR
aY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4gwQco1KRMDSmXSMkDwIDAQAB
AoGAfY9LpnuWK5Bs50UVep5c93SJdUi82u7yMx4iHFMc/Z2hfenfYEzu+57fI4fv
xTQ//5DbzRR/XKb8ulNv6+CHyPF31xk7YOBfkGI8qjLoq06V+FyBfDSwL8KbLyeH
m7KUZnLNQbk8yGLzB3iYKkRHlmUanQGaNMIJziWOkN+N9dECQQD0ONYRNZeuM8zd
8XJTSdcIX4a3gy3GGCJxOzv16XHxD03GW6UNLmfPwenKu+cdrQeaqEixrCejXdAF
z/7+BSMpAkEA8EaSOeP5Xr3ZrbiKzi6TGMwHMvC7HdJxaBJbVRfApFrE0/mPwmP5
rN7QwjrMY+0+AbXcm8mRQyQ1+IGEembsdwJBAN6az8Rv7QnD/YBvi52POIlRSSIM
V7SwWvSK4WSMnGb1ZBbhgdg57DXaspcwHsFV7hByQ5BvMtIduHcT14ECfcECQATe
aTgjFnqE/lQ22Rk0eGaYO80cc643BXVGafNfd9fcvwBMnk0iGX0XRsOozVt5Azil
psLBYuApa66NcVHJpCECQQDTjI2AQhFc1yRnCU/YgDnSpJVm1nASoRUnU8Jfm3Oz
uku7JUXcVpt08DFSceCEX9unCuMcT72rAQlLpdZir876
-----END RSA PRIVATE KEY-----</textarea><br/>
<label for="pubkey">Public Key</label><br/>
<textarea id="pubkey" rows="15" cols="65">-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDlOJu6TyygqxfWT7eLtGDwajtN
FOb9I5XRb6khyfD1Yt3YiCgQWMNW649887VGJiGr/L5i2osbl8C9+WJTeucF+S76
xFxdU6jE0NQ+Z+zEdhUTooNRaY5nZiu5PgDB0ED/ZKBUSLKL7eibMxZtMlUDHjm4
gwQco1KRMDSmXSMkDwIDAQAB
-----END PUBLIC KEY-----</textarea><br/>
<label for="input">Text to encrypt:</label><br/>
<textarea id="input" name="input" type="text" rows=4 cols=70>This is a
test!</textarea><br/>
<input id="testme" type="button" value="Test Me!!!" /><br/>
</body>
</html>

OUTPUT
Program and demo available in the following link
http://travistidwell.com/blog/2013/02/15/a-better-library-for-javascript-
asymmetrical-rsa-encryption/
DECRYPTION

Ex. No. 6 DIFFIE-HELLMAN KEY EXCHANGE ALGORITHM


Date:

Aim: To write a program to perform encryption and decryption using Diffie-Hellman Key
Exchange algorithm
Procedure:
Program

package diffie;
import java.io.*;
import java.math.BigInteger;
class Diffie
{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter prime number:");
BigInteger p=new BigInteger(br.readLine());
System.out.print("Enter primitive root of "+p+":");
BigInteger g=new BigInteger(br.readLine());
System.out.println("Enter value for x less than "+p+":");
BigInteger x=new BigInteger(br.readLine());
BigInteger R1=g.modPow(x,p);
System.out.println("R1="+R1);
System.out.print("Enter value for y less than "+p+":");
BigInteger y=new BigInteger(br.readLine());
BigInteger R2=g.modPow(y,p);
System.out.println("R2="+R2);
BigInteger k1=R2.modPow(x,p);
System.out.println("Key calculated at Alice's side:"+k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Bob's side:"+k2);
System.out.println("deffie hellman secret key Encryption has Taken");
}
}
OUTPUT
Enter prime number:
11
Enter primitive root of 11:7
Enter value for x less than 11:
3
R1=2
Enter value for y less than 11:6
R2=4
Key calculated at Alice's side:9
Key calculated at Bob's side:9
deffie hellman secret key Encryption has Taken

Ex. No. 7 SHA-1 ALGORITHM


Date:

Aim: To Calculate the message digest of a text using the SHA-1 algorithm.
Procedure:
&
Program

Here are general steps to generate a hash value from an input (message):

 First approach (suitable for small-sized message):

1 // algorithm can be "MD5", "SHA-1", "SHA-256"


2 MessageDigest digest = MessageDigest.getInstance(algorithm);
3 byte[] inputBytes = // get bytes array from message

4 byte[] hashBytes = digest.digest(inputBytes);

8
// convert hash bytes to string (usually in hexadecimal form)

 Second approach (suitable for large-size message, i.e. large file):

1 MessageDigest digest = MessageDigest.getInstance(algorithm);


2
byte[] inputBytes = // get bytes array from message
3
digest.update(inputBytes);
4
byte[] hashedBytes = digest.digest();
5
// convert hash bytes to string (usually in hexadecimal form)

Now, let’s see some examples in details.

1. Generating Hash from String


The following method takes a message and algorithm name as inputs and returns
hexadecimal form of the calculated hash value:

1 private static String hashString(String message, String


algorithm)
2
throws HashGenerationException {
3
try {
4
MessageDigest digest =
5 MessageDigest.getInstance(algorithm);

6 byte[] hashedBytes =
digest.digest(message.getBytes("UTF-8"));
7
return convertByteArrayToHexString(hashedBytes);
8
} catch (NoSuchAlgorithmException |
9 UnsupportedEncodingException ex) {
10 throw new HashGenerationException(

11 "Could not generate hash from String",


ex);
}
}

The HashGenerationException is a custom exception (you can find this class in


the attachment). The convertByteArrayToHexString() method is implemented
as follows:
private static String convertByteArrayToHexString(byte[]
1 arrayBytes) {
2 StringBuffer stringBuffer = new StringBuffer();
3 for (int i = 0; i < arrayBytes.length; i++) {
4 stringBuffer.append(Integer.toString((arrayBytes[i]
& 0xff) + 0x100, 16)
5
.substring(1));
6
}
7
return stringBuffer.toString();
8
}
The hashString() is a general method. Here are four public utility methods that
are specific to each algorithm (MD5, SHA-1 and SHA-256):
1 public static String generateMD5(String message) throws
2 HashGenerationException {
return hashString(message, "MD5");
3
}
4
public static String generateSHA1(String message) throws
5
HashGenerationException {
6
return hashString(message, "SHA-1");
7 }
8 public static String generateSHA256(String message) throws
9 HashGenerationException {

10 return hashString(message, "SHA-256");


}

Hence we have the following utility class:


1 package net.codejava.security;

2 import java.io.UnsupportedEncodingException;

3 import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
4
5
/**
6
* Hash functions utility class.
7
* @author www.codejava.net
8
*
9
*/
10
public class HashGeneratorUtils {
11
private HashGeneratorUtils() {
12
13
}
14
public static String generateMD5(String message) throws
15 HashGenerationException {
16 return hashString(message, "MD5");

17 }

18 public static String generateSHA1(String message) throws


HashGenerationException {
19
return hashString(message, "SHA-1");
20
}
21
public static String generateSHA256(String message) throws
22 HashGenerationException {
23 return hashString(message, "SHA-256");
24 }

25
26 private static String hashString(String message, String
algorithm)
27
throws HashGenerationException {
28
try {
29
MessageDigest digest =
30 MessageDigest.getInstance(algorithm);
31 byte[] hashedBytes =
digest.digest(message.getBytes("UTF-8"));
32
return convertByteArrayToHexString(hashedBytes);
33
} catch (NoSuchAlgorithmException |
34 UnsupportedEncodingException ex) {
35 throw new HashGenerationException(
36 "Could not generate hash from String", ex);
37 }

38 }

39
40 private static String convertByteArrayToHexString(byte[]
arrayBytes) {
41
StringBuffer stringBuffer = new StringBuffer();
42
for (int i = 0; i < arrayBytes.length; i++) {
43
stringBuffer.append(Integer.toString((arrayBytes[i]
44 & 0xff) + 0x100, 16)

45 .substring(1));
}
return stringBuffer.toString();
}
}
Here’s a test program:
1 package net.codejava.security;
2
3 /**
4 * Test generating hash values from String.
5 * @author www.codejava.net

6 *

7 */

8 public class StringHashGeneratorExample {


9
10 public static void main(String[] args) {

11 try {

12 String inputString = args[0];

13 System.out.println("Input String: " +


inputString);
14
15
String md5Hash =
16 HashGeneratorUtils.generateMD5(inputString);
17 System.out.println("MD5 Hash: " + md5Hash);

18
19 String sha1Hash =
HashGeneratorUtils.generateSHA1(inputString);
20
System.out.println("SHA-1 Hash: " + sha1Hash);
21
22
String sha256Hash =
23 HashGeneratorUtils.generateSHA256(inputString);
24 System.out.println("SHA-256 Hash: " +
sha256Hash);
25
} catch (HashGenerationException ex) {
26
ex.printStackTrace();
27
}
28
}

OUTPUT
If the input message is “admin” the test program produces the following output:
1 Input String: admin
2 MD5 Hash: 21232f297a57a5a743894a0e4a801fc3
3 SHA-1 Hash: d033e22ae348aeb5660fc2140aec35850c4da997
4 SHA-256 Hash:
8c6976e5b5410415bde908bd4dee15dfb167a9c873fc4bb8a81f6f2ab448a918

Ex. No. 8 DIGITAL SIGNATURE STANDARD


Date:

Aim: To write a JAVA program to implement the Digital Signature Standard scheme.

Procedure:

Signing:

Verifying:
Correctness of the Algorithm
Program

import java.util.*;
import java.math.BigInteger;

class DSS
{
final static BigInteger one = new
BigInteger("1"); final static
BigInteger zero = new
BigInteger("0");

/* incrementally tries for next prime */


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

/* finds largest prime factor of n */


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

/* finds a generator mod p */


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();
/* establish the global public
key components */ BigInteger p
= getNextPrime("10600");
/* approximate prime */
BigInteger q =
findQ(p.subtract(one))
; BigInteger g =
getGen(p,q,randObj);

/* public key components */


System.out.println("Simulation of Digital
Signature Algorithm");
System.out.println("Global public key
components are:"); System.out.println("p is: " +
p);
System.out.println("q is: " + q);
System.out.println("g is: " + g);
/* find the private key */
BigInteger x = new
BigInteger(q.bitLength(), randObj); x =
x.mod(q);
/*
corresponding
public key */
BigInteger y =
g.modPow(x,p)
;
/* random value message */
BigInteger k = new
BigInteger(q.bitLength(), randObj); k =
k.mod(q);
/* randomly generated hash value and
digital signature */ 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);
/* secret information */
System.out.println("Secret
information are:");
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("Generating
Digital signature:");
System.out.println("r is : " + r);
System.out.println("s is : " + s);
/* verify the
digital signature
*/ 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("verifying digital signature
(checkpoints):"); 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("Success: Digital signature is verified! " + r);
}
else
{
System.out.println("Error: Incorrect Digital signature");
}
}
}

OUTPUT:
C:\javaprg>javac DSS.java C:\javaprg>java DSS
Simulation of Digital Signature Algorithm Global public key components are:
p is: 10601
q is: 53
g is: 4763
Secret information are:
x (private) is: 33 k (secret) is: 30
y (public) is: 6965
h (rndhash) is: 13010 Generating Digital signature: r is : 48
s is : 13
verifying digital signature (checkpoints): w is : 49
u1 is : 6 u2 is : 20 v is : 48
Success: Digital signature is verified! 48
RESULT:
Thus the program to implement the DSS Algorithm was executed successfully and the
output was verified.

Ex. No. 9 DEMONSTRATE INTRUSION DETECTION SYSTEM


Date: (IDs) USING ANY TOOL (SNORT OR ANY OTHER S/W)

Aim:
To demonstrate intrusion detection system (ids) using SNORT tool.

DESCRIPTION:
Snort is an open source network intrusion detection system (NIDS) has the
ability to perform real-time traffic analysis and packet logging on internet protocol
(IP) networks. Snort performs protocol analysis, content searching and matching.
Snort can be configured in three main modes: sniffer, packet logger, and network
intrusion detection.

SNORT can be configured to run in three modes:


1. Sniffer mode
2. Packet Logger mode
3. Network Intrusion Detection System mode
Sniffer mode:
snort –v Print out the TCP/IP packets header on the screen.

Packet Logger mode:


snort –dev –l c:\log [create this directory in the C drive] and snort will
automatically know to go into packet logger mode, it collects every packet it sees and
places it in log directory.

Network Intrusion Detection System mode:


snort –d c:\log –h ipaddress/24 –c nort.conf

This is a configuration file applies rule to each packet to decide it an action based
upon the rule type in the file.

WORKING WITH SNORT:


1. Go to the web site www.snort.org/start/download
2. Click on download option and support path to save the setup file.
3. Double click on Snort Installation icon to run setup.
4. Accept License agreement and Specify path for installation, then Click on Next.
5. Install snort with or without database support.
6. Skip the WinPcap driver installation
7. Select all the components and Click Next.
8. Install and Close.
9. Add the path variable in windows environment variable by selecting new classpath.
10. Create a path variable and point it at snort.exe variable name: path and variable value
as
c:\Snort\bin.
11. Click OK button and then close all dialog boxes.

12. Go to command prompt and get into Snortbin directory (C:\Snort\bin) and run
Snort.exe file.
13. Now, type the command Snort.exe –W to see how many interfaces are present in your
PC.

14. If you are having any interface(Wireless, LAN, Bluetooth etc) you can examine that by
using the command: C:\Snort\bin> snort.exe -i 1 –v

15. An editor window displays the complete details of packets flowing across the
system, the IP Address of packet generator, date &Time, length of Packet, Time to
live(TTL), etc at real time.
16. By analyzing these details Intruders can be traced at real time. These details can
be documents by using a print screen option.
17. To stop snort press CTRL+C.

RESULT:
Thus the SNORT tool was installed and demonstrated the intrusion
detection system (ids) using SNORT tool.
Automated Attack and Penetration Tools Exploring N-Stalker, a
Ex. No. 10
Vulnerability Assessment Tool
Date:

Procedure:
The release of N-Stalker Web Application Security Scanner X is an important step towards the next
generation Web Application Security Assessment software, providing not only a tool to scan web
resources, but a solution that will follow your web application development's life-cycle.

• Component-oriented Web Application Security Analysis

The patent-pending technology of Component-oriented Web Application Security Analysis will provide
the most effective approach to your custom application, enabling a Service-oriented Architecture
(SOA) analysis with a security perspective.

N-Stalker Web Application Security Scanner will not only crawl resources as a browser would do it – it
will also create a class of objects being used by your custom application to allow for a more effective
assessment.

The concept of Development and QA, Infrastructure and Deploy and Penetration test analysis will
give customers the ability to verify relevant security issues based in their web application life-cycle,
from OWASP Top10 security recommendations to Bugtraq 0-day vulnerabilities being exploited by
malicious users in the wild.

• Web Application Secure Development Life-cycle

N-Stalker Web Application Security Suite is built to provide complete control over your Web
Application Development Life-cycle. With a range of different security checks, customers will be able
to create specific security scan policies to cover:

Development & QA Profile: a deep approach in the Web Application structure and output code
(HTML), enabling N-Stalker to sweep out transaction brokers and common application areas to
identify development security flaws. A QA approach can be used to certify internal or third-party
development code and give the level of trust needed to promote web applications to production
• level.
Infrastructure & Deploy Profile: According to recent studies (Gartner Group), most of the
vulnerabilities are introduced in the web application deployment phase, when even previously
certified applications can become vulnerable due to third-parties vulnerable softwares. N-Stalker is
the only vendor to provide more than 35,000 attack signatures to assess your Web server
• infrastructure and guarantee a safe hosting environment.
Pen-test and Security Audit Profile: A complete analysis of your web application, including
development, infrastructure and production aspects that can be used to assess the current level of
• security of Web Applications currently in use.

• Special Features

These are the special features that make N-Stalker Web Application Security Scanner the most
complete solution to assess Web Applications:

• HTTP Fingerprinting
• Parallel Web Crawling
• Server-side technology discoverer
• Automatic False Positive Prevention Engine
• Component-oriented Web Crawler
• Component-oriented Scanning Engine
• IDS Evasion Fuzzing Tests
• Custom Web Navigation Macro Recorder
• Web form autocomplete mechanism
• Special Attack console to explore vulnerabilities
• Effective Multithreading Scan for best performance
• Compliance-oriented security analysis

Ex. No. 11 Defeating Malware i) Building Trojans ii) Rootkit Hunter


Date:

(i)Building Trojans

How the Trojan Infects A Computer

When a user visits http://woofles.github.io/placeholder/infector/ to play a seemingly


harmless game, they are informed their Java version is out of date and prompted to
download and install a Java update. When the user opens the fake Java update file it
will be prompted by User Account Control to allow the program to run. Since the
installer was written in Java, the UAC popup will tell the user the file is signed by
Oracle Corporation, so it will have a valid digital signature.
Figure 2: The installer has been "signed" by Oracle Corporation.

The file that is then downloaded follows the same naming scheme as Java updates
and the interface looks very similar.

Figure 3: The actual Java installer


Figure 4: Our imitation of the Java installer (before installation)

Figure 5: Our imitation of the Java installer (during installation)


Figure 6: Our imitation of the Java installer (after installation)

Regardless of what the user does at this point the Trojan will be installed. If they
click the "x" to close the window, hit cancel or hit install, the installer will
download the Trojan. The installer will then run the executable file that was
downloaded with administrator privileges and schedule it as a process to run with
those privileges at startup. The executable file that was downloaded and run is
named "svchost.exe", which is a very common program to have running on a
Windows computer, helping us hide it from the user.

iii) Rootkit Hunter

DESCRIPTION:

Rootkit is a stealth type of malicious software designed to hide the existence of


certain process from normal methods of detection and enables continued privileged
access to a computer. The term rootkit is a concatenation of "root" (the traditional
name of the privileged account on Unix operating systems) and the word "kit" (which
refers to the software components that implement the tool). The term "rootkit" has
negative connotations through its association with malware.
A rootkit is a collection of tools (programs) that enable administrator-level access to a
computer or computer network. Typically, a cracker installs a rootkit on a computer
after first obtaining user-level access, either by exploiting a known vulnerability or
cracking a password. Once the rootkit is installed, it allows the attacker to mask
intrusion and gain root or privileged access to the computer and, possibly, other
machines on the network.
A rootkit may consist of spyware and other programs that: monitor traffic and
keystrokes; create a "backdoor" into the system for the hacker's use; alter log files;
attack other machines on the network; and alter existing system tools to escape
detection.

STEPS:
 Download Rootkit Tool from GMER website. www.gmer.net

 Double click on the GMER rootkit application. Now the rootkit screen will be
displayed.

 This displays the Processes, Modules, Services, Files, Registry,


RootKit/Malwares, Autostart, CMD of local host.
 Select Processes menu and kill any unwanted process if any. Modules
menu displays the various system files like .sys, .dll

 Services menu displays the complete services running with Autostart,


Enable, Disable, System, Boot.
 Files menu displays full files on Hard-Disk volumes.
 Select anyone of the drive which is shown at right side of the screen. After
selecting the drive click on scan button.
 Click on the option processes the screen will be displayed

RESULT:
Thus the study about Trojan and Rootkit was done.
VIVA QUESTIONS

1. What is cryptography?
2. What exactly are encryption and decryption?
3. What is plaintext or cleartext?
4. What is ciphertext?
5. How does the encryption process actually take place?
6. What are the origins of cryptography?
7. What is the Caesar cipher?
8. What is the goal of cryptography?
9. Are there any other ciphers that are available, other than the Caesar cipher?
10. Just how important is the field of cryptography?
11. What is the difference between a private key and a public key?
12. What are symmetric and asymmetric key systems?
13. What kinds of threats exist for a cryptographic system?
14. What is polyalphabetic encryption?
15. What is a block cipher?
16. What is cipher block chaining?
17. What are the disadvantages of symmetric key cryptography?
18. How is a Key Distribution Center (KDC) used?
19. What are the mathematical algorithms used in symmetric cryptography?
20. What is the hashing function?
21. What is asymmetric key cryptography?
22. What are the key differences between asymmetric and symmetric cryptography?
23. What are the disadvantages of asymmetric cryptography?
24. What are the mathematical algorithms used in asymmetric cryptography?
25. What is the Public Key Infrastructure (PKI)?
26. What are the specific components of the Public Key Infrastructure (PKI)?
27. What are the technical specifications of the Certificate Authority?
28. How does the Public Key Infrastructure (PKI) work?
29. What is the LDAP protocol and how is it used in a Public Key Infrastructure (PKI)?
30. What are the security vulnerabilities of hashing functions?
TOPIC BEYOND SYLLABUS
1. Program Obfuscation

Program obfuscation is about modifying source or machine code into


functionally equivalent code that is hard to understand to a human or some
other program. Early obfuscation techniques included heuristic non-
cryptographic code transformations, many of which however, have been
found to be ineffective against sufficiently motivated adversaries. The recent
area of cryptographic program obfuscation targets the design and
implementation of program obfuscators that are provably secure under a
widely accepted intractability assumption, following the standard of modern
cryptography solutions.

2. Computing over encrypted data (Fully Homomorhpic Encryption


(FHE), Functional Encryption (FE))

Homomorphic encryption is a form of encryption that allows computation on


ciphertexts, generating an encrypted result which, when decrypted, matches
the result of the operations as if they had been performed on the plaintext.

Homomorphic encryption can be used for privacy-preserving outsourced


storage and computation. This allows data to be encrypted and out-sourced
to commercial cloud environments for processing, all while encrypted. In
highly regulated industries, such as health care, homomorphic encryption
can be used to enable new services by removing privacy barriers inhibiting
data sharing. For example, predictive analytics in health care can be hard to
apply due to medical data privacy concerns, but if the predictive analytics
service provider can operate on encrypted data instead, these privacy
concerns are diminished.

3. Failures of Cryptography (Cryptanalysis and Attacks)

There are lots of other ways cryptographic software can fail


It fails due to users. How? Think about social engineering attacks. RSA
SecureID breach is said to originate from phishing emails exploiting users
and a zero day vulnerability.
It fails due to unrealistic threat models (Breaking web applications built on
top of encrypted data).
It fails due to hardware (Breaking hardware enforced technologies such as
TPM with hypervisors).
It fails due to side channels (Timing attacks on RSA, DH and DSS
algorithms).
As you can see, cryptographic software can fail due to many reasons. Are we
really doomed to never get cryptographic software right? Or can we at least
can reduce the number of such failures? Why can’t we learn from the past
and avoid the same mistakes happening again and again? What tools will
help us spot most of these issues?
Our situation actually isn’t all that bleak. There are ways to prevent most of
the failures discussed above.

4. Crypto Currency (Bitcoin) and Smart Contracts (Ethereum)

Bitcoin, cryptocurrency, blockchain... So what does it all mean?

Let's start with some quick definitions. Blockchain is the technology that enables the
existence of cryptocurrency (among other things). Bitcoin is the name of the best-known
cryptocurrency, the one for which blockchain technology was invented. A cryptocurrency is a
medium of exchange, such as the US dollar, but is digital and uses encryption techniques to
control the creation of monetary units and to verify the transfer of funds.

What is blockchain technology?

A blockchain is a decentralized ledger of all transactions across a peer-to-peer network.


Using this technology, participants can confirm transactions without a need for a central
clearing authority. Potential applications can include fund transfers, settling trades, voting,
and many other issues.

Like many ideas in the blockchain industry, a general confusion shrouds so called ‘smart
contracts’.

A new technology made possible by public blockchains, smart contracts are difficult to
understand because the term partly confuses the core interaction described.

While a standard contract outlines the terms of a relationship (usually one enforceable by
law), a smart contract enforces a relationship with cryptographic code.

Put differently, smart contracts are programs that execute exactly as they are set up to by their
creators.
First conceived in 1993, the idea was originally described by computer scientist and
cryptographer Nick Szabo as a kind of digital vending machine. In his famous example, he
described how users could input data or value, and receive a finite item from a machine, in
this case a real-world snack or a soft drink.

In a simple example, ethereum users can send 10 ether to a friend on a certain date using a
smart contract (See our guide “What is Ether?“).
In this case, the user would create a contract, and push the data to that contract so that it could
execute the desired command.

Ethereum is a platform that’s built specifically for creating smart contracts.

Strength in numbers

Extrapolating that last point, smart contracts are likely to need assistance from other smart
contracts.

When someone places a simple bet on the temperature on a hot summer day, it might trigger
a sequence of contracts under the hood.

One contract would use outside data to determine the weather, and another contract could
settle the bet based on the information it received from the first contract when the conditions
are met.

Running each contract requires ether transaction fees, which depend on the amount of
computational power required.

As explained in our guide “How Ethereum Works“, ethereum runs smart contract code when
a user or another contract sends it a message with enough transaction fees.
The Ethereum Virtual Machine then executes smart contracts in ‘bytecode’, or a series of
ones and zeroes that can be read and interpreted by the network.

But these new tools aren’t intended to be used in isolation. It is believed that they can also
form the building blocks for ‘decentralized applications’ (See: “What is a Dapp?“) and even
whole decentralized autonomous companies (See: “What is a DAO?‘)

How smart contracts work

It’s worth noting that bitcoin was the first to support basic smart contracts in the sense that
the network can transfer value from one person to another. The network of nodes will only
validate transactions if certain conditions are met.

But, bitcoin is limited to the currency use case.


By contrast, ethereum replaces bitcoin’s more restrictive language (a scripting language of a
hundred or so scripts) and replaces it with a language that allows developers to write their
own programs.

Ethereum allows developers to program their own smart contracts, or ‘autonomous agents’,
as the ethereum white paper calls them. The language is ‘Turing-complete’, meaning it
supports a broader set of computational instructions.
Smart contracts can:

 Function as ‘multi-signature’ accounts, so that funds are spent only when a required
percentage of people agree
 Manage agreements between users, say, if one buys insurance from the other
 Provide utility to other contracts (similar to how a software library works)
 Store information about an application, such as domain registration information or
membership records.

5. Memory Hard Functions (e.g., Script, Argon 2)

In cryptography, a memory hard function (MHF) is a function that costs significant amount
of memory to evaluate. It is different from memory bound functions, the latter incurs cost by
slowing down computation through memory latency. MHFs find their use as a form of proof-
of-work.

Passwords, despite all their drawbacks, remain the primary form of authentication on various
web-services. Passwords are usually stored in a hashed form in a server’s database. These
databases are quite often captured by the adversaries, who then apply dictionary attacks since
passwords tend to have low entropy. Protocol designers use a number of tricks to mitigate
these issues. Starting from the late 70’s, a password is hashed together with a random salt
value to prevent detection of identical passwords across different users and services. The hash
function computations, which became faster and faster due to Moore’s law have been called
multiple times to increase the cost of password trial for the attacker. In the meanwhile, the
password crackers migrated to new architectures, such as FPGAs, multiple-core GPUs and
dedicated ASIC modules, where the amortized cost of a multiple-iterated hash function is
much lower. It was quickly noted that these new environments are great when the
computation is almost memoryless, but they experience difficulties when operating on a large
amount of memory. The defenders responded by designing memory-hard functions, which
require a large amount of memory to be computed, and impose computational penalties if less
memory is used. The password hashing scheme scrypt [15] is an instance of such function.
Memory-hard schemes also have other applications. They can be used for key derivation
from low-entropy sources. Memory-hard schemes are also welcome in cryptocurrency
designs [13] if a creator wants to demotivate the use of GPUs and ASICs for mining and
promote the use of standard desktops.
An introduction

There are two main versions of Argon2: Argon2i which is the safest option against side-

channel attacks and Argon2d which is the safest option against GPU cracking attacks.

Source code is available on GitHub, written in C89-compliant C, licensed under CC0 and

compiles on most ARM, x86 and x64 architectures.

AES based

Argon2 is based on AES which modern x64 and ARM processors implement in their

instruction set extensions, thus greatly closing the performance gap between common systems

and the attackers’.

Parameters for fine-tuning

Both versions of the algorithm can be parameterised by:

 A time cost, which defines the execution time

 A memory cost, which defines the memory usage

 A parallelism degree, which defines the number of threads

this means that you can separately tune these parameters and tailor the security bound to your

use case, threat model and hardware specifications.

Tradeoff attacks

On top of this, Argon2 is particularly resistant to ranking tradeoff attacks making it much
more difficult to cheaply optimise on FPGAs: even though recent FPGAs have embedded
RAM blocks, memory bandwidth is still a constrain and in order to reduce the memory

bandwidth requirements, the attacker must use more computational resources with Argon2.

This and similar attacks are discussed in the specs (see chapter 5) as well as in a separate

paper by the same authors where they also compare it with scrypt.

Argon2id

The below is a quote/paraphrase from the Argon2 IETF Draft.

Argon2d uses data-depending memory access, which makes it suitable for cryptocurrencies

and PoW applications with no threats from side-channel timing attacks. Argon2i uses data-

independent memory access, which is preferred for password hashing. Argon2id works as

Argon2i for the first half of the first iteration over the memory and as Argon2d for the rest,

thus providing both side-channel attack protection and bruteforce cost savings due to time-

memory tradeoffs. Argon2i makes more passes over the memory to protect from tradeoff

attacks.

If you fear side-channel attacks (i.e. Meltdown/Spectre which allow reading private memory
of other processes running on the same hardware via cache-based side channels) you should
use Argon2i, otherwise Argon2d.
If you are unsure or if you’re comfortable with a hybrid approach you can use Argon2id

You might also like