Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 28

1

THAKUR COLLEGE OF SCIENCE AND COMMERCE

TYBSC CS SEM V

INS PRACTICALS - E JOURNAL

NAME : Amit Pandey

CLASS:TYBSC CS

DIV: A

ROLL NO:3068
2

Contents of E- Journal

Practical No. Practical Name Date

To implement the Substitution


1. Cipher techniques: Caesar’s and
Monoalphabetic. (1)

To implement One Time Pad/


2.
Vernam Cipher technique. (2)

To implement Transposition
3. Cipher techniques: Rail fence and
Columnar. ( 3)

4. To implement RSA algorithm. (5)

To implement Diffie Hellman Key


5.
exchange algorithm. (6)

6. To implement MD5 algorithm.(7)

To implement SHA - 1 algorithm.


7.
(8)
To implement a program in SSL.
8.
(9)
3
4

PRACTICAL NO 1: A) MONO ALPHABETIC CIPHER

AIM: To implement the Substitution Cipher techniques: Caesar’s and


Monoalphabetic.

WRITEUP:
1]Monoalphabetic cipher is one where each symbol in plain text is mapped to a fixed symbol
in cipher text.
2] The relationship between a character in the plain text and the characters in the cipher
text is one-to-one.
3] It is a simple substituton cipher.

C ode:

import java.util.Scanner;
public class MonoALpha_Prac_1
{
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

public static String encrypt(String plainText,int shiftKey)


{
plainText=plainText.toLowerCase();
String cipherText="";
for(int i=0;i< plainText.length();i++)
{
int charPosition = ALPHABET.indexOf(plainText.charAt(i));
int keyval = (shiftKey + charPosition) % 26;
if(keyval > 25)
{
keyval = keyval - 26;
}
char replaceVal = ALPHABET.charAt(keyval);
cipherText += replaceVal;
}
return cipherText;
5

public static String decrypt(String cipherText,int shiftKey)


{
cipherText=cipherText.toLowerCase();
String plainText="";
for(int i=0;i< cipherText.length();i++)
{
int charPosition = ALPHABET.indexOf(cipherText.charAt(i));
int keyval = (charPosition - shiftKey) % 26;
if(keyval < 0)
{
keyval = 26 + keyval;
}
char replaceVal = ALPHABET.charAt(keyval);
plainText += replaceVal;
}
return plainText;
}

public static void main(String args[])


{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the string for Encryption:");
String message = new String();
message = sc.next();
System.out.println("Enter the shift value:");
int shift = sc.nextInt();
System.out.println("Encrypted Text :");
System.out.println(encrypt(message,shift));
System.out.println("Decrypted Text :");
System.out.println(decrypt(encrypt(message,shift),shift));
sc.close();
}

OUTPUT:
6

PRACTICAL NO 1:B) Caesar’s Cipher

Aim: To perform Caesar’s Cipher

Writeup:Created by Julius Caesar.


The Caesar cipher involves replacing each letter of
the alphabet with the letter standing 3 places further
down the alphabet.

Code:

import java.util.Scanner;
public class CaesarCipher
{

public static final String ALPHABET =


“abcdefghijklmnopqrstuvwxyz”;
7

public static String encrypt(String plainText, int


shiftKey)
{
plainText = plainText.toLowerCase(); //abc
String cipherText = “ ”;
for (int i = 0; i &lt; plainText.length(); i++)
{
int charPosition =
ALPHABET.indexOf(plainText.charAt(i)); //2
int keyVal = (shiftKey + charPosition) % 26;

char replaceVal = ALPHABET.charAt(keyVal);


cipherText += replaceVal;
}
return cipherText;
}
public static String decrypt(String cipherText, int
shiftKey)
{
//convert ct to lowercase
cipherText = cipherText.toLowerCase();
String plainText = “ ”;
for (int i = 0; i &lt; cipherText.length(); i++)
{
int charPosition =
ALPHABET.indexOf(cipherText.charAt(i));
int keyVal = (charPosition - shiftKey) % 26;
if (keyVal &lt; 0)
{
keyVal = 26 + keyVal;

}
char replaceVal = ALPHABET.charAt(keyVal);
plainText += replaceVal;
}
return plainText;
}
public static void main(String[] args)
{
8

Scanner sc = new Scanner(System.in);


System.out.println(“Enter the String for Encryption:”);
String message = new String();
message = sc.next();
System.out.println(”Encrypted Text:”);
System.out.println(encrypt(message, 3));
System.out.println(“Decrypted Text:”);
System.out.println(decrypt(encrypt(message, 3), 3));
sc.close();
}
}

OUTPUT:

PRACTICAL NO 2:One Time Pad/ Vernam Cipher

Aim: To implement One Time Pad/ Vernam Cipher technique

Writeup:
1]Also called as Vernam Cipher or the Perfect Cipher.
2]Here plaintext is combined with a random key.
3] The Key must be atleast as long as the plaintext.
9

4] Each key is used only once and sender receiver must destroy the
key after use.
5] There should be only two copies of the keys,1 with sender other
with receiver.

Code:

import java.util.Scanner;
public class vvv {
public static final String ALPHABET="abcdefghijklmnopqrstuvwxyz";
public static String Encrypt(String plainText,String Key)
{
plainText=plainText.toLowerCase();
String cipherText="";
for(int i=0;i<plainText.length();i++)
{
int
charPositionPT=ALPHABET.indexOf(plainText.charAt(i));
int charPositionKey=ALPHABET.indexOf(Key.charAt(i));
int finalPosition=charPositionPT + charPositionKey;
if(finalPosition>25)
{
finalPosition=finalPosition-26;
}
char replaceVal=ALPHABET.charAt(finalPosition);
cipherText+=replaceVal;
}
return cipherText;

}
public static String Decrypt(String cipherText,String Key)
{
cipherText=cipherText.toLowerCase();
String plainText="";
for(int i=0;i<cipherText.length();i++)
{
int
charPositionCT=ALPHABET.indexOf(cipherText.charAt(i));
int charPositionKey=ALPHABET.indexOf(Key.charAt(i));
10

int finalPosition=charPositionCT - charPositionKey;


if(finalPosition<0)
{
finalPosition=finalPosition + 26;
}
char replaceVal=ALPHABET.charAt(finalPosition);
plainText+=replaceVal;
}
return plainText;
}

public static void main(String[] args)


{
Scanner sc=new Scanner(System.in);
System.out.println("Enter String for Ercryption:");
String message =new String();
message=sc.next();
System.out.println("Enter the key for Encryption:");
String key=new String();
key=sc.next();
System.out.println("Encrypted Text:");
System.out.println(Encrypt(message,key));
System.out.println("Decrypted Text:");
System.out.println(Decrypt((Encrypt(message,key)),key));
sc.close();
}

OUTPUT:
11

PRACTICAL NO 3:A)COLUMNAR
Aim: To implement Transposition Cipher techniques: Columnar.

Writeup:
1] The message is written out in rows of a fixed length, and then
read out again column by column, and the columns are chosen in
some scrambled order.
2] Width of the rows and the permutation of the columns are usually
definedby a keyword.
3] For example, the word HACK is of length 4 (so the rows are of
length 4),and the permutation is defined by the alphabetical order of
the letters in thekeyword.
4] In this case, the order would be “3 1 2 4”.
Any spare spaces are filled with nulls or left blank or placed by Filler
alphabets

Code:

import java.util.Scanner;
public class CC
{
public static void Encrypt(String plainText,String key)
{
//make string arrays of key and plaintext
String pt[]=plainText.split("");
//String ky[]=key.split("");

//get the no of columns and rows to build matrix


int columns = key.length();
int rows;
if (plainText.length() % columns== 0)
{
rows=(plainText.length())/columns;
12

}
els
e
{
rows=(plainText.length()/columns) + 1;

String [][] mat = new String [rows][columns];


String var="";
int c=0;

//enter key in first row of matrix


/*for(int i = 0; i < columns; i++)
{
mat[0][i] = ky[i];
}*/

//fill up the matrix with plaintext


for(int i = 0; i < rows; i++)
{
for(int j = 0; j< columns; j++)
{
if(c != plainText.length())
{
var = pt[c];
mat[i][j]=var;
//System.out.print(mat[i][j]+"\t");
c++;
}
else
break;
}
//System.out.println();
}

//pad the empty spaces with either numeric values or


characters
for(int i = 0; i < rows; i++)
{
for(int j = 0; j< columns; j++)
{
13

if(mat[i][j] == null)
{
mat[i][j]="@";
}
}
}

//display the matrix


for(int i = 0; i < rows; i++)
{
for(int j = 0; j< columns; j++)
{
System.out.print(mat[i][j]+"\t");

}
System.out.println();
}

//display the encrypted string


String output="";
for(int i = 0; i < columns; i++)
{
for(int j = 0; j< rows ; j++)
{
output=output+mat[j][i];

}
}
System.out.println("Encrypted String:"+output);
}

public static void main(String[] args)


{ Scanner sc = new
Scanner(System.in);
System.out.println("Enter the String for Encryption: ");
String str = new String();
str = sc.next();
System.out.println("Enter the key for Encryption: ");
String key = new String();
key = sc.next();
Encrypt(str,key);
14

}
OUTPUT:

PRACTICAL NO 3:RAILFENCE
Aim: To implement Transposition Cipher techniques: Rail fence.

Writeup:
1] The rail fence cipher (also called a zigzag cipher) is a form of
transposition cipher.
2] It derives its name from the way in which it is encoded.In the rail
fence cipher, the plain-text is written downwards and diagonally on
successive rails of an imaginary fence.
3] When we reach the bottom rail, we traverse upwards moving
diagonally, after reaching the top rail, the direction is changed
again. Thus the alphabets of the message are written in a zig-zag
manner.
15

Code:
import java.util.Arrays;
import java.util.Scanner;
public class railfence {
public static void Encrypt(String str, int n)
{

if (n == 1)
{
System.out.print(str);
return ;
}
char[] str1 = str.toCharArray();
int len = str.length();
String[] arr = new String[n];
Arrays.fill(arr, "");
int row = 0;
boolean down = true;
//LEN = NO OF COLUMNS OR PLAINTEXT SIZE
for (int i = 0; i<len; i++)
{
arr[row] = arr[row] + (str1[i]);
if (row == n - 1)
{
down = false;
}
else if (row == 0)
{
down = true;
}
if (down)
{
row++;
}
else

{
row--;
}
}
16

for (int i = 0; i < n; i++)


{
System.out.print(arr[i]);
}
}
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in);
System.out.println("Enter the String for Encryption:");
String str = new String();
str = sc.next();
int n = 3;
System.out.println("Encrypted String:");
Encrypt(str, n);
}
}

OUTPUT:
17

PRACTICAL NO 5:RSA
Aim: To implement RSA algorithm

Writeup:
1] RSA algorithm is a public key encryption technique and is
considered as the most secure way of encryption. It was
invented byRivest, Shamir and Adleman in year 1978 and
hence name RSA algorithm.
2] The entire RSA is all about creating public key, private key for
encryption and decryption.

Code:
import java.util.Scanner;

public class RSA {


public static int pvtkey;

public static void ComputeRSA(int p,int q)


{
int N;
N = p * q;

//Step 2: Calculate Derived Number


int m;
m = (p-1)*(q-1);

//Step 3: Choose a public key that follows the two conditions of


// 1< e < m
// e is a prime number
int e; //public key
Scanner sc = new Scanner(System.in);
System.out.println("Enter value for public key");
e = sc.nextInt();
boolean isPrime = checkForPrime(e);
//checking if e is greater than 1 and lesser than derived number m
if (e > 1 && e < m) {
if (isPrime) {
18

//Step 4 : Constructing the table


int[] a = new int[25];
int[] b = new int[25];
int[] d = new int[25];
int[] k = new int[25];

//Giving the default values


a[0] = 1; b[0] = 0; d[0] = m; k[0] = 0;
a[1] = 0; b[1] = 1; d[1] = e;
k[1] = d[0] / d[1];

//loop that checks if d = 1 and stops at that point


System.out.println("a \t b \t d \t k");
int i = 2;
while (d[i] != 1) {
a[i] = a[i - 2] - (a[i - 1] * k[i - 1]);
b[i] = b[i - 2] - (b[i - 1] * k[i - 1]);
d[i] = d[i - 2] - (d[i - 1] * k[i - 1]);
k[i] = d[i - 1] / d[i];
System.out.println(a[i] + "\t " + b[i] + "\t " + d[i] +
"\t " + k[i]);

if (d[i] == 1)
{
pvtkey = b[i];
break;
}
els
e
{ i++;

//Step 5: Applying conditions on your private key


if (pvtkey > m) {
pvtkey = pvtkey % m;
}
if (pvtkey < 0) {
pvtkey = pvtkey + m;
19

//Printing the public and private key


System.out.println();
System.out.println("******************************");
System.out.println("Public Key: " + e);
System.out.println("Private Key: " + pvtkey);
System.out.println("*****************************");
}
else
System.out.println("The public key you chose is not a
prime number.");
}
else
System.out.println("The public key you chose is bigger than
derived number " +m);
}

public static boolean checkForPrime(int inputNumber)


{
boolean isItPrime = true;

if(inputNumber <= 1)
{
isItPrime = false;
return isItPrime;
}
els
e
{ for (int i = 2; i<= inputNumber/2; i++)
{
if ((inputNumber % i) == 0)
{
isItPrime = false;
break;
}
}

return isItPrime;
}
20

}
public static void main(String[] args)
{ Scanner sc = new
Scanner(System.in);
System.out.println("Enter value for p(prime no. 1)- ");
int p;
p = sc.nextInt();
System.out.println("Enter value for q(prime no. 2)- ");
int q;
q = sc.nextInt();
ComputeRSA(p,q);
}
}
OUTPUT:

PRACTICAL NO 6: Diffie Hellman


Aim: To implement Diffie Hellman
Key exchange algorithm Diffie
Hellman

Writeup:
1] The Diffie–Hellman key exchange method allows two parties that
have no prior knowledge of each other to jointly establish a shared
secret key over an insecure channel.
21

2] This key can then be used to encrypt subsequent


communications using a symmetric key cipher.

3] The whole point is to share a secret symmetric key between alice


and bob which they can use for further communication.

Code:
import java.util.Scanner;
public class DFHellman
{
public static void ComputeDF(double q, double p)
{
//Compute CipherKey for Alice and Bob
Scanner sc = new Scanner(System.in);
System.out.println("Enter private key for Alice:");
double pvtAlice = sc.nextInt();
System.out.println("Enter private key for Bob:");
double pvtBob = sc.nextInt();
double cipherKeyAlice, cipherKeyBob;
cipherKeyAlice = Math.pow(p, pvtAlice) % q;
cipherKeyBob = Math.pow(p, pvtBob)% q;
//System.out.println("Cipher Key of Alice :"+cipherKeyAlice);
//System.out.println("Cipher Key of Bob :"+cipherKeyBob);

//Step 3: Compute Shared Secret Key


double SecretKeyAlice = Math.pow(cipherKeyBob, pvtAlice) %q;
double SecretKeyBob = Math.pow(cipherKeyAlice, pvtBob) %q;

if (SecretKeyAlice == SecretKeyBob)
{
System.out.println("Shared Secret Key = " +
(int)SecretKeyAlice);
}
else
System.out.println("Your values don't match. Please try
again.");
sc.close();
22

public static boolean checkForPrime(double inputNumber)


{
boolean isItPrime = true;

if(inputNumber <= 1)
{
isItPrime = false;
return isItPrime;
}
els
e
{ for (int i = 2; i<= inputNumber/2; i++)
{
if ((inputNumber % i) == 0)
{
isItPrime = false;
break;
}
}

return isItPrime;
}
}

public static void main(String[] args)


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

//Step 1 : take q and p as input


System.out.println("Enter value for q(prime no.)- ");
double q;
q = sc.nextInt();
boolean IsPrime = checkForPrime(q);
if (IsPrime)
{
System.out.println("Enter value for p(primitive root of q)- ");
double p;
p = sc.nextInt();
23

ComputeDF(q, p);
}
els
e System.out.println("The value you entered for q is not prime
number. Please try again.");
sc.close();

OUTPUT:

PRACTICAL NO 7: MD5
Aim: To implement MD5 algorithm

Writeup:
The MD5 message-digest algorithm is a widely used hash function producing a 128-bit
hash value. Although MD5 was initially designed to be used as a cryptographic hash
function, it has been found to suffer from extensive vulnerabilities. It can still be used as
a checksum to verify data integrity, but only against unintentional corruption. It remains
suitable for other non-cryptographic purposes, for example for determining the partition
for a particular key in a partitioned database.MD5 was designed by Ronald Rivest in
[4]
1991 to replace an earlier hash function MD4, and was specified in 1992 as one basic
requirement of any cryptographic hash function is that it should be computationally
infeasible to find two distinct messages that hash to the same value. MD5 fails this
24

requirement catastrophically; such collisions can be found in seconds on an ordinary


home computer.
The weaknesses of MD5 have been exploited in the field, most infamously by the Flame
malware in 2012. The CMU Software Engineering Institute considers MD5 essentially
"cryptographically broken and unsuitable for further use".

Code:
package md5;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
// Java program to calculate MD5 hash value
public class MD5 {
public static String getMd5(String input)
{
try {

MessageDigest md = MessageDigest.getInstance(“MD5”);
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashval = no.toString(16);
return hashval;
}

catch (NoSuchAlgorithmException e)
{
throw new RuntimeException(e);
}
}
public static void main(String args[]) throws
NoSuchAlgorithmException
{
String s = “Anurag”;
System.out.println(“Your HashCode Generated by MD5 is: “ +
getMd5(s));
}
}
25

OUTPUT:

PRACTICAL NO 8:SHA - 1
Aim: To implement SHA - 1 algorithm

Writeup:
1] In cryptography, SHA-1 (Secure Hash Algorithm 1) is a
cryptographic hash function which takes an input and
produces a 160-bit (20-byte) hash value known as a message
digest.
2] This was designed by the National Security Agency (NSA)
to be part of the Digital Signature Algorithm. Cryptographic
weaknesses were discovered in SHA-1, and the standard was
no longer approved for most cryptographic uses after 2010.

Code:
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA_1 {
public static String encryptThisString(String input)
{
try
{
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger(1, messageDigest);

String hashtext = no.toString(16);

return hashtext;
}

catch (NoSuchAlgorithmException e) {
26

throw new RuntimeException(e);


}
}
// Driver code
public static void main(String args[])
throws NoSuchAlgorithmException
{
System.out.println("HashCode Generated by SHA-
1 for:"); String s1 = "Hello";
System.out.println("\n " + s1 +" : " +
encryptThisString(s1)); String s2 = "World";
System.out.println("\n" + s2 +" : " + encryptThisString(s2));
}
}

OUTPUT:
27

PRAC NO. 9
Aim:- To implement a program in SSL
Write up:-
Secure Socket Layer (SSL) provide security to the data that is transferred between web
browser and server. SSL encrypt the link between a web server and a browser which
ensures that all data passed between them remain private and free from attack.
Secure Socket Layer Protocols:
 SSL record protocol
 Handshake protocol
 Change-cipher spec protocol
 Alert protocol

SERVER code:

import java.io.*;
import java.net.*;
public class Server
{
public static void main(String[] args){
try
{
//ServerSocket class provides a mechanism for the
server program to listen for clients
ServerSocket ss=new ServerSocket(6666);
//establishes connection Socket
s=ss.accept();
//Data Input stream creates a stream to read the
incoming data
DataInputStream dis=new
DataInputStream(s.getInputStream());
//readUTF reads the incoming streaming data in string
format
String str=(String)dis.readUTF();
System.out.println("message= "+str); ss.close();

}
catch(Exception e)
{
System.out.println(e);}
}
}
28

CLIENT code:
import java.io.*;
import java.net.*;
public class Client
{
public static void main(String[] args)
{
try{
Socket s=new Socket("localhost",6666);
//Creates a stream to send data
DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
//Writes data in String format
dout.writeUTF("Hello Server");
//flush() method clears the stream dout.flush();
dout.close();
s.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output:-

You might also like