Security Lab Manual Overview
Security Lab Manual Overview
LAB MANUAL
PREPARED BY
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
OUTPUT
test
lwkl
test
uftu
test
exxegoexsrgi
attackatonce
Ex. No. 1.B)
JAVA PROGRAM TO ENCODE A MESSAGE USING PLAYFAIR CIPHER
Date:
import java.awt.Point;
import java.util.Scanner;
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);
createTable(key, changeJtoI);
if (i == sb.length() - 1)
sb.append(sb.length() % 2 == 1 ? 'X' : "");
if (row1 == row2) {
col1 = (col1 + direction) % 5;
col2 = (col2 + 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:
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'
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.
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;
}
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
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;
}
}
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
Aim: To write a program to perform encryption and decryption using VIGENERE Cipher
Procedure:
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
Program
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
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>
DECRYPTION
Ex. No. 3 DES ALGORITHM
Date:
Aim: To write a program to perform encryption and decryption using DES ALGORITHM
Procedure:
Program
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;
Let’s test if we are able to get the decrypted string back from encrypted string.
System.out.println(originalString);
System.out.println(encryptedString);
System.out.println(decryptedString);
}
Output:
howtodoinjava.com
Tg2Nn7wUZOQ6Xc+1lenkZTQ9ZDf9a2/RBRiqJBCIX6o=
howtodoinjava.com
Aim: To write a HTML and JAVA SCRIPT program to perform encryption and decryption
using RSA ALGORITHM
Procedure:
Download
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.
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">
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
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
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):
8
// convert hash bytes to string (usually in hexadecimal form)
6 byte[] hashedBytes =
digest.digest(message.getBytes("UTF-8"));
7
return convertByteArrayToHexString(hashedBytes);
8
} catch (NoSuchAlgorithmException |
9 UnsupportedEncodingException ex) {
10 throw new HashGenerationException(
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 }
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 */
11 try {
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
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");
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.
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.
This is a configuration file applies rule to each packet to decide it an action based
upon the rule type in the file.
12. Go to command prompt and get into Snortbin 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.
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.
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
(i)Building Trojans
The file that is then downloaded follows the same naming scheme as Java updates
and the interface looks very similar.
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.
DESCRIPTION:
STEPS:
Download Rootkit Tool from GMER website. www.gmer.net
Double click on the GMER rootkit application. Now the rootkit 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
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.
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.
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?‘)
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.
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.
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
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
this means that you can separately tune these parameters and tailor the security bound to your
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
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