0% found this document useful (0 votes)
25 views49 pages

CNS PDF

Project

Uploaded by

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

CNS PDF

Project

Uploaded by

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

1. Use sniffers for monitoring network communication (Ethereal).

Procedure:
Step 1: Open wireshark and you can see capture button on menu bar. Click on it.
In the drop down menu click on the refresh interfaces.

Step 2: Click on the Network connection that you are working on. Here we used
WiFi and click on the wifi channel.

Step 3:After clicking the WiFi channel we get our database regarding about the
background running websites and it shows the protocols and about it. Here we can
search for the sniffers .
Step 4: Here we see HTTP requests and there we get POST or GET methods used by
other persons we can find out them. Click on it. We get a drop down menu ,there
click on follow button and in that click on the TCP Stream. We can see the following
dialog box.

Step 5: Finally we can see the conversation between source, sniffers and the
destination.
2. understanding of cryptographic algorithms and implementation of same in C
or C++
AIM: To implement the simple substitution technique named Caesar cipher using
Java language.

DESCRIPTION:
To encrypt a message with a Caesar cipher, each letter in the message is
changed using a simple rule: shift by three. Each letter is replaced by the letter
three letters ahead in the alphabet. A becomes D, B becomes E, and so on.
For the last letters, we can think of the
alphabet as a circle and "wrap around". W becomes Z, X becomes A, Y bec mes
B, and Z
becomes C. To change a message back, each letter is replaced by the one three
before it.

ALGORITHM:

STEP-1: Read the plain text from the user.


STEP-2: Read the key value from the user.
STEP-3: If the key is positive then encrypt the text by adding the key with
each character in the plain text.
STEP-4: Else subtract the key from the plain text.
Program:

import java.io.BufferedReader;
import java.io.IOException; import
java.io.InputStreamReader; import
java.util.Scanner;
public class CeaserCipher {

static Scanner sc=new Scanner(System.in);


staticBufferedReaderbr=newBufferedReader(new
InputStreamReader(System.in));public static void main(String[] args) throws
IOException {
// TODO code application logic here

System.out.print("Enter any String: ");


String str = br.readLine();
System.out.print("\nEnter the Key: "); int key
= sc.nextInt();

String encrypted = encrypt(str, key);


System.out.println("\nEncrypted String is: " +encrypted);

Stringdecrypted=decrypt(encrypted,
key); System.out.println("\nDecrypted String
is: "
+decrypted); System.out.println("\n");
}

public static String encrypt(String str, int key)

{ String encrypted ="";


for(int i = 0; i < str.length(); i++) { int c
= str.charAt(i);
if (Character.isUpperCase(c)) {
c = c + (key % 26);
if (c > 'Z')

c = c - 26;
}

else if (Character.isLowerCase(c)) {
c = c + (key % 26);
if (c > 'z')
c = c - 26;
}

encrypted += (char) c;
}
return encrypted;
}

public static String decrypt(String str, int key)


{ String decrypted = ""; for(int i
= 0; i <str.length(); i++) { int c
= str.charAt(i);
if(Character.isUpperCase(c)) {
c = c - (key % 26);
if (c < 'A')

c = c + 26;
}

else if (Character.isLowerCase(c)) {
c = c - (key % 26);
if (c < 'a')

OUTPUT:
Enter any string: HelloWorld
Enter key: 5
Encrypted string is: MjqqtBtwqi
Decrypted string is: Hello World
RESULT: Thus the implementation of Caesar cipher had been executed successfully.

AIM: To write a Java program to implement the Playfair


Substitution technique.

DESCRIPTION:

The Playfair cipher starts with creating a key table. The key table is a
5×5 grid of letters that will act as the key for encrypting your plaintext.
Each of the 25 letters must be unique and one letter of the alphabet is
omitted from the table (as there are 25 spots and 26 letters in the
alphabet).

To encrypt a message, one would break the message into digrams


(groups of 2 letters) such that, for example, "HelloWorld" becomes "HE LL
OW OR LD", and map them out on the key table. The two letters of the
diagram are considered as the opposite corners of a rectangle in the key
table. Note the relative position of the corners of this rectangle. Then
apply the following 4 rules, in order, to each pair of letters in the plaintext:

1. If both letters are the same (or only one letter is left), add an "X" after
the first letter
2. If the letters appear on the same row of your table, replace them
with the letters to their immediate right respectively
3. If the letters appear on the same column of your table, replace them
with the letters immediately below respectively
4. If the letters are not on the same row or column, replace them with
the letters on the same row respectively but at the other pair of
corners of the rectangle defined by the original pair.

ALGORITHM:
STEP-1: Read the plain text from the user.
STEP-2: Read the keyword from the user.
STEP-3: Arrange the keyword without duplicates in a 5*5 matrix in the
row order and fill the remaining cells with missed out letters in
alphabetical order. Note that ‘i’ and ‘j’ takes the same cell.
STEP-4: Group the plain text in pairs and match the corresponding
corner letters by forming a rectangular grid.
STEP-5: Display the obtained cipher text.
Program
import java.awt.Point;
class playfairCipher {
private static char[][] charTable;
private static Point[] positions;
private static String prepareText(String s, boolean chgJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
return chgJtoI ? s.replace("J", "I") : s.replace("Q", "");
}
private static void createTbl(String key, boolean chgJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", chgJtoI);
int len = s.length();
for (int i = 0, k = 0; i < len; i++) {
char c = s.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String codec(StringBuilder txt, int dir) {
int len = txt.length();
for (int i = 0; i < len; i += 2) {
char a = txt.charAt(i);
char b = txt.charAt(i + 1);
int row1 = positions[a - 'A'].y;
int row2 = positions[b - 'A'].y;
int col1 = positions[a - 'A'].x;
int col2 = positions[b - 'A'].x;
if (row1 == row2) {
col1 = (col1 + dir) % 5;
col2 = (col2 + dir) % 5;
} else if (col1 == col2) {

row1 = (row1 + dir) % 5;


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

OUTPUT:
Simulating Playfair Cipher

Input Message : Security Lab


Encrypted Message : EABPUGYANSEZ
Decrypted Message : SECURITYLABX

RESULT:
Thus the program for playfair cipher encryption and decryption algorithm has
been implemented and the output verified successfully.

AIM: To write a Java program to implement the hill cipher substitution technique.
DESCRIPTION:
Each letter is represented by a number modulo 26. Often the simple scheme A = 0,
B
= 1... Z = 25, is used, but this is not an essential feature of the cipher. To encrypt a
message, each block of n letters is multiplied by an invertible n × n matrix,
against modulus 26. To
decrypt the message, each block is multiplied by the inverse of the ma trix
used for

encryption. The matrix usedfor encryption is the cipher keyanditshouldbechosen

ALGORITHM:

STEP-1: Read the plain text and key from the user.
STEP-2: Split the plain text into groups of length three.
STEP-3: Arrange the keyword in a 3*3 matrix.
STEP-4: Multiply the two matrices to obtain the cipher text of length three.
STEP-5: Combine all these groups to get the complete cipher text.
PROGRAM
import
java.io.*;
import
java.util.*;

public class SubstitutionCipher{


static Scanner sc = new Scanner(System.in);
staticBufferedReaderbr=newBufferedReader(new
InputStreamReader(System.in));public static void main(String[] args) throws
IOException {

// TODO code application logic here String a


= "abcdefghijklmnopqrstuvwxyz"; String b =
"zyxwvutsrqponmlkjihgfedcba";

System.out.print("Enter any string: ");


String str = br.readLine();
String decrypt =
""; char c;
for(int i=0;i<str.length();i++)
{
c=str.charAt(i);
int j = a.indexOf(c);
decrypt = decrypt+b.charAt(j);
}
System.out.println("The encrypted data is: " +decrypt);
}
}
Output:
Enter any string: aceho
The encrypted data is: zxvsl

RESULT:
Thus the program for hill cipher encryption and decryption algorithm has been
implemented and the output verified successfully.
AIM: To implement the Vigenere Cipher substitution technique using Java.
DESCRIPTION:
To encrypt, a table of alphabets can be used, termed a tabula recta, Vigenère square,
or Vigenère table. It different rows, each
consists of the alphabet
written out 26 times
alphabet shifted cyclically to the left compared to the previous alphabet,
corresponding to the 26 possible Caesar ciphers. At different points in the
encryption process, the cipher uses a different alphabet from one of the rows.
The alphabet used at each point repeating keyword.

Each row starts with a key letter. The remainder of the row holds the letters A to Z.
Although there are 26 key rows shown, you will only use as many keys as there are
unique letters in the key string, here just 5 keys, {L, E, M, O, N}. For successive letters
of the message, we are going to take successive letters of the key string, and
encipher each message
letter using its corresponding key row. Choose the next letter of the key, go al ng
that row to
find the column heading that atches the message character; the letter at the
intersection of
[key-row, msg-col] is the enciphered letter.

ALGORITHM:

STEP-1: Arrange the alphabets in row and column of a 26*26 matrix.


STEP-2: Circulate the alphabets in each row to position left such that the first letter is
attached to last.
STEP-3: Repeat this process for all 26 rows and construct the final key matrix.
STEP-4: The keyword and the plain text is read from the user.
STEP-5: The characters in the keyword are repeated sequentially so as to match
with that of the plain text.
STEP-6: Pick the first letter of the plain text and that of the keyword as the row
indices and column indices respectively.

STEP-7: The junction character where these two meet forms the cipher character.
STEP-8: Repeat the above steps to generate the entire cipher text.
public class vigenereCipher {
static String encode(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;
}
static String decode(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) throws java.lang.Exception {


String key = "VIGENERECIPHER";
String msg = "SecurityLaboratory";
System.out.println("Simulating Vigenere Cipher\n------------------------");
System.out.println("Input Message : " + msg);
String enc = encode(msg, key);
System.out.println("Encrypted Message : " + enc);
System.out.println("Decrypted Message : " + decode(enc, key));
}
}
OUTPUT:
Simulating Vigenere Cipher

Input Message : SecurityLaboratory


Encrypted Message : NMIYEMKCNIQVVROWXC
Decrypted Message : SECURITYLABORATORY

RESULT:
Thus the program for vigenere cipher encryption and decryption algorithm has
been implemented and the output verified successfully.
AIM: To write a Java program to implement the rail fence transposition technique.
DESCRIPTION:
In the rail fence cipher, the plain text is written downwards and diagonally on
successive "rails" of an imaginary fence, then moving up when we reach the bottom
rail. When we reach the top rail, the message is written downwards again until the
whole plaintext is written out. The message is then read off in rows.
ALGORITHM:

STEP-1: Read the Plain text.


STEP-2: Arrange the plain text in row columnar matrix format.
STEP-3: Now read the keyword depending on the number of columns of the plain text.
STEP-4: Arrange the characters of the keyword in sorted order and the corresponding
columns of the plain text.
STEP-5: Read the characters row wise or column wise in the former order to get the
cipher text.
class railfenceCipherHelper {
int depth;

String encode(String msg, int depth) throws Exception {


int r = depth;
int l = msg.length();
int c = l / depth;
int k = 0;
char mat[][] = new char[r][c];
String enc = "";
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) {
if (k != l) {
mat[j][i] = msg.charAt(k++);
} else {
mat[j][i] = 'X';
}
}
}
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
enc += mat[i][j];
}
}
return enc;
}

String decode(String encmsg, int depth) throws Exception {


int r = depth;
int l = encmsg.length();
int c = l / depth;
int k = 0;
char mat[][] = new char[r][c];
String dec = "";
for (int i = 0; i < r; i++) {
for (int j = 0; j < c; j++) {
mat[i][j] = encmsg.charAt(k++);
}
}
for (int i = 0; i < c; i++) {
for (int j = 0; j < r; j++) {
dec += mat[j][i];
}
}
return dec;
}
}

class railFenceCipher {
public static void main(String[] args) throws java.lang.Exception {
railfenceCipherHelper rf = new railfenceCipherHelper();
String msg, enc, dec;
msg = "Anna University, Chennai";
int depth = 2;
enc = rf.encode(msg, depth);
dec = rf.decode(enc, depth);
System.out.println("Simulating Railfence Cipher\n-------------------------");
System.out.println("Input Message : " + msg);
System.out.println("Encrypted Message : " + enc);
System.out.printf("Decrypted Message : " + dec);
}
}

OUTPUT:
Simulating Railfence Cipher

Input Message : Anna University, Chennai


Encrypted Message : An nvriy hnanaUiest,Ceni
Decrypted Message : Anna University, Chennai

RESULT:
Thus the java program for Rail Fence Transposition Technique has been
implemented and the output verified successfully.

AIM:
To implement a program for encryption and decryption by using row and column
transformation technique.

ALGORITHM:
1. Consider the plain text hello world, and let us apply the simple columnar
transposition technique as shown below

h e l l
o w o r
l d

2. The plain text characters are placed horizontally and the cipher text is created
with vertical format as: holewdlo lr.
3. Now, the receiver has to use the same table to decrypt the cipher text to plain
text.

PROGRAM:

TransCipher.java

import java.util.*;
class TransCipher {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the plain text");
String pl = sc.nextLine();
sc.close();
String s = "";
int start = 0;
for (int i = 0; i < pl.length(); i++) {
if (pl.charAt(i) == ' ') {
s = s + pl.substring(start, i);
start = i + 1;
}
}
s = s + pl.substring(start);
System.out.print(s);
System.out.println();
// end of space deletion

int k = s.length();
int l = 0;
int col = 4;
int row = s.length() / col;
char ch[][] = new char[row][col];
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (l < k) {
ch[i][j] = s.charAt(l);
l++;
} else {
ch[i][j] = '#';
}
}
}
// arranged in matrix

char trans[][] = new char[col][row];


for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
trans[j][i] = ch[i][j];
}
}
for (int i = 0; i < col; i++) {
for (int j = 0; j < row; j++) {
System.out.print(trans[i][j]);
}
}
// display
System.out.println();
}
}

OUTPUT:
Enter the plain text
Security Lab
SecurityLab
Sreictuy

RESULT:
Thus the java program for Row and Column Transposition Technique has been
implemented and the output verified successfully.
AIM:

To write a Java program to implement Data Encryption Standard (DES) algorithm.

DESCRIPTION:

DES is a symmetric encryption system that uses 64-bit blocks, 8 bits of which are used
for parity checks. The key therefore has a "useful" length of 56 bits, which means that
only 56 bits are actually used in the algorithm. The algorithm involves carrying out
combinations, substitutions and permutations between the text to be encrypted and
the key, while making sure the operations can be performed in both directions. The key
is ciphered on 64 bits and made of 16 blocks of 4 bits, generally denoted k1 to k16.
Given that "only" 56 bits are actually used for encrypting, there can be 2 56 different
keys.
The main parts of the algorithm are as follows:
Fractioning of the text into 64-bit blocks
Initial permutation of blocks
Breakdown of the blocks into two parts: left and right, named L and R
Permutation and substitution steps repeated 16 times
Re-joining of the left and right parts then inverse initial permutation
ALGORITHM:

STEP-1: Read the 64-bit plain text.


STEP-2: Split it into two 32-bit blocks and store it in two different arrays.
STEP-3: Perform XOR operation between these two arrays.
STEP-4: The output obtained is stored as the second 32-bit sequence and the original
second 32-bit sequence forms the first part.
STEP-5: Thus the encrypted 64-bit cipher text is obtained in this way. Repeat the same
process for the remaining plain text characters.
program
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 DES


{
public static void main(String[] argv) {

try{
System.out.println("Message Encryption Using DES Algorithm\n-------");
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher;
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] text = "Secret Information ".getBytes();
System.out.println("Message [Byte Format] : " + text);
System.out.println("Message : " + new String(text));
byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Encrypted Message: " + textEncrypted);
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
System.out.println("Decrypted Message: " + new String(textDecrypted));

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

}
}

OUTPUT:
Message Encryption Using DES Algorithm

Message [Byte Format] : [B@4dcbadb4


Message : Secret Information
Encrypted Message: [B@504bae78
Decrypted Message: Secret Information

RESULT:
Thus the java program for DES Algorithm has been implemented and the output
verified successfully.
AIM:
To use Advanced Encryption Standard (AES) Algorithm for a practical application
like URL Encryption.

ALGORITHM:
1. AES is based on a design principle known as a substitution–permutation.
2. AES does not use a Feistel network like DES, it uses variant of Rijndael.
3. It has a fixed block size of 128 bits, and a key size of 128, 192, or 256 bits.
4. AES operates on a 4 × 4 column-major order array of bytes, termed the state

PROGRAM:
AES.java
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AES {

private static SecretKeySpec secretKey;


private static byte[] key;

public static void setKey(String myKey) {


MessageDigest sha = null;
try {
key = myKey.getBytes("UTF-8");
sha = MessageDigest.getInstance("SHA-1");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}

public static String encrypt(String strToEncrypt, String secret) {


try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return
Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
return null;
}

public static String decrypt(String strToDecrypt, String secret) {


try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}

public static void main(String[] args) {


final String secretKey = "annaUniversity";

String originalString = "www.annauniv.edu";


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

System.out.println("URL Encryption Using AES Algorithm\n------------");


System.out.println("Original URL : " + originalString);
System.out.println("Encrypted URL : " + encryptedString);
System.out.println("Decrypted URL : " + decryptedString);
}
}

OUTPUT:
URL Encryption Using AES Algorithm

Original URL : www.annauniv.edu


Encrypted URL : vibpFJW6Cvs5Y+L7t4N6YWWe07+JzS1d3CU2h3mEvEg=
Decrypted URL : www.annauniv.edu

RESULT:
Thus the java program for AES Algorithm has been implemented for URL Encryption
and the output verified successfully.

AIM: Write a JAVA program to implement the BlowFish algorithm logic.


PROGRAM:
import java.io.*;
import java.io.FileInputStream;
import
java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import
javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import sun.misc.BASE64Encoder;
public class BlowFish{
public static void main(String[] args) throws Exception {
// TODO code application logic here KeyGeneratorkeyGenerator
= KeyGenerator.getInstance("Blowfish"); keyGenerator.init(128); Key
secretKey = keyGenerator.generateKey();
Cipher cipherOut =
Cipher.getInstance("Blowfish/CFB/NoPadding");
cipherOut.init(Cipher.ENCRYPT_MODE, secretKey);
BASE64Encoder encoder = new BASE64Encoder();

byte iv[] =
cipherOut.getIV(); if (iv !=
null) {

System.out.println("Initialization Vector of the Cipher: " +encoder.encode(iv)); }


FileInputStream fin = new FileInputStream("inputFile.txt");
FileOutputStreamfout = new FileOutputStream("outputFile.txt");
CipherOutputStreamcout = new CipherOutputStream(fout, cipherOut); int
input
= 0;
while ((input = fin.read()) != -1)
{ cout.write(input)

fin.close(); cout.close(); }}
OUTPUT:
Initialization Vector of the Cipher:
dI1MXzW97oQ=

Contents of inputFile.txt: Hello World

Contents of outputFile.txt: ùJÖ˜ NåI“


AIM:
To implement the Diffie-Hellman Key Exchange algorithm using Java language.
DESCRIPTION:
Diffie–Hellman Key Exchange establishes a shared secret between two parties
that can be used for secret communication for exchanging data over a public
network. It is primarily used as a method of exchanging cryptography keys for
use in symmetric encryption algorithms like AES. The algorithm in itself is very
simple. The process begins by having the two parties, Alice and Bob. Let's
assume that Alice wants to establish a shared secret with Bob.
ALGORITHM:

STEP-1: Both Alice and Bob shares the same public keys g and p.
STEP-2: Alice selects a random public key a.
STEP-3: Alice computes his secret key A as ga mod p.
STEP-4: Then Alice sends A to Bob.
STEP-5: Similarly Bob also selects a public key b and computes his secret key
as B and sends the same back to Alice.
STEP-6: Now both of them compute their common secret key as the other
one’s secret key power of a mod p.
class DiffieHellman {
public static void main(String args[]) {
int p = 23; /* publicly known (prime number) */
int g = 5; /* publicly known (primitive root) */
int x = 4; /* only Alice knows this secret */
int y = 3; /* only Bob knows this secret */
double aliceSends = (Math.pow(g, x)) % p;
double bobComputes = (Math.pow(aliceSends, y)) % p;
double bobSends = (Math.pow(g, y)) % p;
double aliceComputes = (Math.pow(bobSends, x)) % p;
double sharedSecret = (Math.pow(g, (x * y))) % p;
System.out.println("simulation of Diffie-Hellman key exchange
algorithm\n ");
System.out.println("Alice Sends : " + aliceSends);
System.out.println("Bob Computes : " + bobComputes);
System.out.println("Bob Sends : " + bobSends);
System.out.println("Alice Computes : " + aliceComputes);
System.out.println("Shared Secret : " + sharedSecret);
/* shared secrets should match and equality is transitive */
if ((aliceComputes == sharedSecret) && (aliceComputes == bobComputes))
System.out.println("Success: Shared Secrets Matches! " + sharedSecret);
else
System.out.println("Error: Shared Secrets does not Match");
}
}

OUTPUT:
simulation of Diffie-Hellman key exchange algorithm

Alice Sends : 4.0


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

RESULT:
Thus the Diffie-Hellman key exchange algorithm has been implemented
using Java Program and the output has been verified successfully
AIM:
To write a Java program to implement the RSA encryption algorithm.
DESCRIPTION:
RSA is an algorithm used by modern computers to encrypt and decrypt
messages. It is an asymmetric cryptographic algorithm. Asymmetric means
that there are two different keys. This is also called public key cryptography,
because one of them can be given to everyone. A basic principle behind RSA is
the observation that it is practical to find three very large positive integers
e, d and n such that with modular exponentiation for all integer m:

(me)d = m (mod n)
The public key is represented by the integers n and e; and, the private key, by
the integer d. m represents the message. RSA involves a public key and a
private key. The public key can be known by everyone and is used for
encrypting messages. The intention is that messages encrypted with the public
key can only be decrypted in a reasonable amount of time using the private
key.

EXAMPLE:
ALGORITHM:

STEP-1: Select two co-prime numbers as p and q.


STEP-2: Compute n as the product of p and q.
STEP-3: Compute (p-1)*(q-1) and store it in z.
STEP-4: Select a random prime number e that is less than that of z.
STEP-5: Compute the private key, d as e * mod-1(z). STEP-6: The cipher text is
computed as messagee * mod n.
STEP-7: Decryption is done as cipherdmod n.
import
java.io.BufferedReader;
import
java.io.InputStreamRead
er; import java.math.*;
import
java.util.Rando
m; import
java.util.Scanne
r; public class
RSA{
static Scanner sc = new
Scanner(System.in); public static void
main(String[] args){
// TODO code
application logic here
System.out.print("Enter a
Primenumber: ");

BigInteger p = sc.nextBigInteger(); // Here's one


prime number.. System.out.print("Enter another
prime number: "); BigInteger q =
sc.nextBigInteger(); // ..andanother.
BigInteger n = p.multiply(q);
BigInteger n2
=
p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)); BigInteger e
= generateE(n2);
BigInteger d = e.modInverse(n2); // Here's the multiplicative inverse

System.out.println("Encryption keys are: " +e+"," + n);


System.out.println("Decryption keys are: " + d + ", " + n);
}
public static
BigIntegergenerateE(BigIntegerfiofn) { int y,
intGCD;
BigIntege
r e;
BigInteger
gcd;
Random x = new Random();
do {

y=
x.nextInt(fiofn.intVal
ue()-1); String z =
Integer.toString(y);
e=new
BigInteger(z); gcd
= fiofn.gcd(e);
intGCD = gcd.intValue();
}
while(y <= 2 ||
intGCD!= 1);
return e;

OUTPUT:

Enter a Prime number: 5


Enteranotherprime
number:11

Encryption keys are:


33,55
Decryption keys are: 17, 55

RESULT:
Thus the Java program to implement RSA encryption technique had been
implemented successfully
EXPERIMENT NO.3

3. Using open SSL for web server - browser communication.

Open SSL is a software library for applications that secure communications


over computer network against dropping or need to identify the part at the
other end. It is widely used by Internet sever including majority of HTTP
websites.

Installation:-
1. Download the Open SSL for windows installation package
2. Double click the file.
3. If error occurs, you should install Microsoft visual C++.
4. Double click the installation file and click on next.
5. Click on I accept agreement and next.
6. Leave the default start menu folder and click on next.
7. Leave the windows system directory and click on next.
8. Click on install.
9. Click on finish once the installation completed.
.
HOW DOES SSL WORKS:-

SSL encrypts data communicated across the web to generate a high level of
privacy. Anyone attempting intercept this data will meet a jumbled mess of
character nearly hard to detect.
SSL begins on authentication process known as a handshake b/w two
communicating devices to confirm that both devices are who they say.
STEPS:
1. Generate a private key.
2. Generate a public key and matching the private key.
3. Generate a certificate using signing request.
4. Send the certificate signing request to a certificate authority.
5. Install private log and certificate key for your web, server software.
EXPERIMENT NO.4
4. Using GNU PGP
To encrypt email and files you need to know how to work with PGP keys. Get
up to speed on generating exporting and importing encryption keys with GNU
PGP.

 Encryption should be a priority for every business. In case you need an


encryption basis refresher, we have starting from the ground up and
showing how to create a PGP key so that you can encrypt files and
folder.
 After all with yours PGP key so that you can encrypt files and folders.
 After all without your PGP key, your control can spend you encrypted
email.
 First you need to install GPU win on windows.
Install GNUPG:
Emerge gnupg
Installation.
GNUPG should already be installed on your machine, if not install it with
command.
sudo apt-get install gnupg.
Generating your key pair:-
You must generate your key-pair, this will create private key and a public
key.
 The private key decrypt emails and files sent to you by those that are
your public key.
 The private must key remains secret.
 The public key is the key you share with others so that encrypt message
to you. To generate your key-pair, use command
 Gpg…gn…key
1. Please select what kind of key you want
1. RSA and RSA (default)
2. DSA and elagmal
3. DSA (sign only)
4. RSA (sign only)
Stick with the default here and press 1
2. Next, you must select key size.
RSA keys may be between 1024 and 4096 bits long.
What key size do you want (2048)
Select the default (2048) by hitting enter.
3. Enter the expiry dates for the key a means no expiration set.
D = key does not expire
<n> = key expires in n days
<n>w =key expires in n weeks
<n>y = key expires in n years.
OUTPUT:
cryp.txt
Cryptograph
User (Principal) key id (Alias)
Mangomango OXB183385A
@gmail.com E051EC
Key Type Key size Created on
Expiration
Diffe Hellman 1024 09/19/2018
02/13/2019
DES 1024 09/21/2018
02/15/2019
Encrypt & Sign Details

Encrypt and sign results


#Source Destination
1. C :/Users/U-lab/DESKTOP/Encrypt C :/Users/U-
lab/DESKTOP/Crypt.txt

Source Detected Error, if any

Summary

Number of file(s) Processed


Successful 1
Failed 0
Start Date & Time 09/19/18 3:52:17 PM
End Date & Time 09/19/18 3:52:17 PM
Time taken 0 seconds
EXPERIMENT-5: Performance evaluation of different cryptographic algorithms.
Cryptography: Cryptography is an effective way for using hyper sensitive
details. It is just a means for stocks and also sending into with kind in which
just these people it relay is created for go through and also procedure.
Plain text -----en-------- Cipher Text ----- de---Plain
Text en-Encryption
de-Decryption
VARIOUS FACTORS:-
Sno Factors DES AES RSA
Analyzed
1. Developed 1977 2000 1978
2. Key length 138,192,126 56 bits >1024 bits
value bits
3. Type of Symmetric Symmetric Asymmetric
Algorithm
4. Encryption Low high high
Ratio
5. Security Inadequate Highly Timing attack
Attacks secured
6. Stimulation fast Secured low Attack high
Speed

 COMPARISION OF VARIOUS PACKET SIZES FOR DES, AES &RSA


ALGORITHM:

S.no Algorithm Packet Encrypt Decrypt Buffer


size(KB) Time(sec) Time(Sec) size
1. DES 15 3.0 1 157
AES 3 1.6 1.1 152
RSA 7.3 4.9 222
2. DES 11 3.2 1.2 121
AES 8 1.7 1.2 110
RSA 10.0 5.0 188
3. DES 19 2.0 1.4 201
AES 6 1.7 1.24 200
RSA 8.5 5.9 257
4. DES 26 4.0 1.8 888
AES 8 2.0 1.2 889
RSA 8.2 5.1 934
5. DES 31 3.0 1.6 319
AES 2 1.8 1.3 300
RSA 7.8 5.1 411
6)Using IP tables or linux and setting the following rules
Introduction to Iptables:-
The term IP tables used to define the linux kernel, firewall, part of the Netfilter
project and the userspace tool used to configure their firewall. The Netfilter
framework provides a set of facilities that are used by iptables to look
functions.
->The structure of Ip tables is based on tables chain and rules
->Ip tables firewall is used ion based rules. Iptables comes with all linux
distribution.
->Ip tables linux firewall is used to monitor incoming and outcoming rules to
present any one from accessing the system.
Commands:
>sudo iptables -l -v
->This command is usedfor checking current iptables status
-l -> list of all rules
-v -> More tedious list
step-1:- Allowing incoming traffic on specific ports
jntua@ubuntu : sudo/table-A INPUT-P tcp-d port ssh- jACEPT
jntua@ ubuntu:sudo ptables-t
chain INPUT(policy ACCEPT)
target port opt source destination
chain OUTPUT(policy ACCEPT)
target port opt Source Destination.
Step -2:- Allowing Established Sessions
jntua@ubuntu: Sudo iptables -L
chain INPUT (policy ACCEPT);
target prot opt save Destination ACCEPT tep-...anywhele tep deptissh
ACCEPT all.....anywhere ctstat RELATED ESTABLISHED
Chain FORWARD policy ACCEPT).
Step 3:- Set default policy for iptables filter table using -p flag
jntu@ubuntu: sudo iptables + filter-p outPUT
DROP
jntu@ubuntu: Sudo iptable - 2
chain INPUT (policy ACCEPT)
target prot opt source Destination
ACCEPT----anywhere tcp: dpt:ssh
jntua@ubuntu: sudo iptables – L
Step-4:- If we want to disable firewall temporally, we Can finish all the rules
using the following Command.
jntua@ubuntu: Sodo iptables -t filter-P OUTPUT ACCEPT
jntua@ubuntu: Sudo iptables -L
chain INPUT(policy DROP)
target prot opt source destination
ACCEPT tcp.....anywhere tcp:dpt: ssh
ACCEPT all -- anywhere dstate RELATED ESTABLISHED
Chain FORWARD (policy ACCEPT)
target prot opt source destination
chain OUTPUT (policy ACCEPT)
target prot opt source Destination
ACCEPT tcp....anywhere tcp dptssh
ACCEPT all.. . .anywhere estate RELATED ESTABLISHED
Step 5: To Commands for machine to Send only http requests (port no:80) and
ssh request (port no: 22)
jntua@ obuntu sud0 iptables -n INPUT -p top ethaport 80
jntua@ubuntu: Sudo iptables - L
chain INPUT (polley ACCEPT)
taught port port source Destination
target prot opt source destination.
jntua@ ubuntu, Sudo iptables-A INPUT-P
tcp - iethed-port 22
jntua@ ubuntu Sudo iptables - L.
Step 6:- Allowing incoming traffic on of specific ports
jntua@ubuntu: suds iptables-A OUTPOT-P
ethepont 22
jntua@ ubuntu: sudo iptables -L chain input (policy Accept)
target part opt.. . .Couce Destination
ACCEPT top...anywhere top dpt is h
ACCEPT alt…anywhere estate RELATED, ESTABLISHED
Step 7:- filtering packets based on source If we want to accept or reject
packets based on QP Address or large of IP address you can Specify with -s opt
on
jntua@ ubuntu Sudo iptables - A INPUT-Path
-3192.168.1.30.211 -1 ACCEPT – CH5O
chain INPUT Epolicy ACCEPT)
target prot opt source destination
ACCEPT tep. . .anywhere top dpt/ssh
Chown FORLOARD (policy ACCEPT)
target port opt source destination
tcp.. .anywhere top dpt:ftp:date.
7. Configuring S/MIME for email communication.
Program:
To configure S/MIME (Secure/Multipurpose Internet Mail Extensions) for email
communication, you'll need to follow a series of steps. S/MIME provides end-
to- end encryption and digital signatures for email messages, ensuring their
confidentiality, integrity, and authenticity. The specific steps may vary
depending on the email client or application you're using, but I'll provide a
general guide:
1. Obtain a Digital Certificate:
- Purchase a digital certificate from a trusted Certificate Authority (CA) or use
a certificate provided by your organization.
- Generate a certificate signing request (CSR) and submit it to the CA.
- Complete the verification process required by the CA to issue your digital
certificate.
- Once issued, download and install the digital certificate on your computer
or device.
2. Configure S/MIME in your Email Client:
- Open your email client or application (e.g., Microsoft Outlook, Apple Mail,
Mozilla Thunderbird).
- Locate the settings or preferences section for email accounts.
- Look for the S/MIME or Security settings, usually found under the "Security"
or "Privacy" tab.
- Import your digital certificate into the email client by specifying the
certificate file location or importing it from a file.
- Associate your digital certificate with the email account you want to use for
S/MIME-protected communication.
3. Set Encryption and Signing Preferences:
- Within the S/MIME settings, specify your preferences for encryption and
signing.
- Choose whether you want to sign all outgoing messages, encrypt all
outgoing messages, or manually select encryption and signing options for each
message.
- Set the level of encryption (e.g., 128-bit, 256-bit) you want to use.
- Determine whether you want to include your digital certificate as an
attachment to outgoing signed messages.
4. Exchange Digital Certificates with Communication Partners:
- Share your digital certificate with the individuals or organizations you want
to communicate securely with.
- Request that your communication partners share their digital certificates
with you.
- Import the digital certificates received from your communication partners
into your email client.
5. Compose and Send Secure Emails:
- Compose a new email message as you normally would.
- If you want to sign the message, select the appropriate option to digitally
sign it.
- If you want to encrypt the message, select the appropriate option to
encrypt it.
- Choose the recipient's digital certificate from your contact list or address
book.
- Send the email as usual.
6. Decrypt and Verify Received Emails:
- When you receive an encrypted email, your email client should
automatically decrypt it if you have the corresponding private key for the
recipient's digital certificate.
- To verify the authenticity of a signed email, open the email and check for a
digital signature icon or indicator.
- If the email is signed, verify the signature to ensure it hasn't been tampered
with.
Experiment 8: Understanding the buffer overflow and format string attacks.
Program:
#include <stdio.h>
#include <string.h>
void vulnerableFunction(char* input) {
char buffer[10];
strcpy(buffer, input);
printf("Buffer contents: %s\n", buffer);
}
int main() {
char input[20];
printf("Enter input: ");
fgets(input, sizeof(input), stdin);
vulnerableFunction(input);
return 0;
}
Output:
[?2004l
Enter input: 12345678901
Buffer contents: 12345678901
b)program:
#include <stdio.h>
int main() {
char secret[] = "Sensitive Data";
char input[10];
printf("Enter your name: ");
fgets(input, sizeof(input), stdin);
printf(input);
printf("Welcome, %s!\n", input);
printf("The secret is: %s\n", secret);
return 0;
}
Output:
[?2004l
Enter your name: opiuytredfghjh
opiuytredWelcome, opiuytred!
The secret is: Sensitive Data
9. Using NMAP for ports monitoring.
PROCEDURE:
-> Open NMAP-ZENMAP in the search bar.
-> At the target column enter www.gmail.com and make profile to be as
‘intense
scan’ and click scan.
-> We can observe the code running in Nmap output.
-> By seeing the ports/hosts and topology after sometime we can observe the
changes in it, if not the command is not completed yet.
-> After completed we can observe the following changes.
NMAP OUTPUT
TRACEROUTE (using port 80/tcp)
HOP RTT ADDRESS
1 2.00 ms 192.168.108.132
2 ...
3 36.00 ms 56.14.148.169
4 38.00 ms bom07s35-in-f5.1e100.net (142.250.66.5)

PORTS/HOSTS

TOPOLOGY
HOST DETAILS

SCANS
10.To Implementation of proxy-based security protocols in c or c++ with
features like confidentiality,
integrity and authentication.
#include <stdio.h>
int main(){
FIL E *fp1, *fp2;
char a;
fp 1= fopen("test.txt", "r");
if (fp1 == NULL)
{ puts ("cannot open test. txt file");
exit(1);
}
fp2 = fopen ("test1, txt", "w");
if (fp2 == NULL){
puts ("Not able to test1 txt file");
fclose (fp1);
exit (1);
a= fget (fp1);
fprintf (fp2, “%c", a+3);
while (a! = EOF){
a= fgetc (fp₁);
fprintf (fp2,”%c", a+3);
printf("test.txt is successfully encrypted and stored to test1. txt");
printf ("n/test.txt can be forwarded to destination");
fclose (fp1);
fclose (fp2);
return 0;
}
test.txt
Deepika
Deepika

Output:-
test. txt is sucessfully encrypted and stored to test1.txt
test1.txt can be forwarded to destination.
test 1. Txt

19hhslnd

Confidentiality at Receivel side:-


#include <stdio.h>
int main() {
FILE *fp1; *fp2;
Char a ;
fp1 = fopen ("test1.txt", "r");
if (fp1 = NULL){
puts ("cannot open test.txt file");
exit (1)
}
fp2= fopen("test 2. txt", "w");
if (fp₂ == NULL) {
puts ("Not able to test text file");
fclose (fp1);
exit (1);
}
a = fgetc (fp1);
fprintf (fp2, "%c", a-3);
while (a!= EOF)
a = fgetc (fp1);
fprintf(fp2,”%c”,a-3);
return 0;
Output:-
test1.txt is Successfully decrypted and stored in test2.txt
User can read test2. txt file

You might also like