0% found this document useful (0 votes)
3 views

INS Lab-Manual

The document outlines the implementation of four cryptographic algorithms: Caesar Cipher, Playfair Cipher, Hill Cipher, and Dijkstra's Algorithm using C language. Each section includes the aim, description, algorithm steps, example outputs, and relevant C code for each cipher. The document serves as a comprehensive guide for understanding and coding these encryption techniques.

Uploaded by

kanchana
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

INS Lab-Manual

The document outlines the implementation of four cryptographic algorithms: Caesar Cipher, Playfair Cipher, Hill Cipher, and Dijkstra's Algorithm using C language. Each section includes the aim, description, algorithm steps, example outputs, and relevant C code for each cipher. The document serves as a comprehensive guide for understanding and coding these encryption techniques.

Uploaded by

kanchana
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 35

PART A

1. IMPLEMENTATION OF CAESAR CIPHER

AIM:

To implement the simple substitution technique named Caesar cipher using C 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 becomes B, and Z
becomes C. To change a message back, each letter is replaced by the one three before it.

EXAMPLE:

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.
STEP-5: Display the cipher text obtained above.

1
PROGRAM:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char plain[10], cipher[10];
int key,i,length;
printf("\n Enter the plain text:");
scanf("%s", plain);
printf("\n Enter the key value:");
scanf("%d", &key);
printf("\n \n \t PLAIN TEXT: %s",plain);
printf("\n \n \t ENCRYPTED TEXT: ");
for(i = 0, length = strlen(plain); i < length; i++) {
cipher[i]=plain[i] + key;
if (isupper(plain[i]) && (cipher[i] > 'Z'))
cipher[i] = cipher[i] - 26;
if (islower(plain[i]) && (cipher[i] > 'z'))
cipher[i] = cipher[i] - 26;
printf("%c", cipher[i]); }
printf("\n \n \t AFTER DECRYPTION : ");
for(i=0;i<length;i++)
{
plain[i]=cipher[i]-key;
if(isupper(cipher[i])&&(plain[i]<'A'))
plain[i]=plain[i]+26;
if(islower(cipher[i])&&(plain[i]<'a'))
plain[i]=plain[i]+26;
printf("%c",plain[i]);
}
return 0;
}

OUTPUT:

Enter the plain text:hello

Enter the key value:3

PLAIN TEXT: hello

ENCRYPTED TEXT: khoor

AFTER DECRYPTION : hello

2
2. IMPLEMENTATION OF PLAYFAIR CIPHER

AIM:

To write a C 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.

EXAMPLE:

3
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:

#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define MX 5

void playfair(char ch1,char ch2, char key[MX][MX])


{
int i,j,w,x,y,z;
FILE *out;
if((out=fopen("cipher.txt","a+"))==NULL) {
printf("File Currupted."); }
for(i=0;i<MX;i++) {
for(j=0;j<MX;j++) { if(ch1==key[i][j]) {
w=i; x=j; }
else if(ch2==key[i][j]) {
y=i; z=j;
}}}

//printf("%d%d %d%d",w,x,y,z);
if(w==y)
{
x=(x+1)%5;z=(z+1)%5;
printf("%c%c",key[w][x],key[y][z]);
fprintf(out, "%c%c",key[w][x],key[y][z]);
}
else if(x==z)
{
w=(w+1)%5;y=(y+1)%5;
printf("%c%c",key[w][x],key[y][z]);
fprintf(out, "%c%c",key[w][x],key[y][z]);
}

4
else {
printf("%c%c",key[w][z],key[y][x]);
fprintf(out, "%c%c",key[w][z],key[y][x]);
}
fclose(out);
}

int main()
{
int i,j,k=0,m=0,n;
char key[MX][MX],keyminus[25],keystr[10],str[25]={0};
char alpa[26]={'A','B','C','D','E','F','G','H','I','J','K','L' ,'M','N','O','P','Q','R','S','T','U','V',
'W','X','Y','Z'} ;
printf("\nEnter key:");
gets(keystr);
printf("\nEnter the plain text:");
gets(str);
n=strlen(keystr);
//convert the characters to uppertext
for (i=0; i<n; i++)
{
if(keystr[i]=='j')
keystr[i]='i';
else if(keystr[i]=='J')
keystr[i]='I';
keystr[i] = toupper(keystr[i]);
}

//convert all the characters of plaintext to uppertext


for (i=0; i < strlen(str); i++)
{
if(str[i]=='j')
str[i]='i';
else if(str[i]=='J')
str[i]='I';
str[i] = toupper(str[i]);
} j=0;
for(i=0;i<26;i++) {
for(k=0;k<n;k++) {
if(keystr[k]==alpa[i]) break;
else if(alpa[i]=='J') break;
}

if(k==n) {
keyminus[j]=alpa[i];j++;
}
}

5
//construct key keymatrix
k=0;
for(i=0;i<MX;i++) {
for(j=0;j<MX;j++) {
if(k<n) {
key[i][j]=keystr[k]; k++;}
else {
key[i][j]=keyminus[m];m++; }
printf("%c ",key[i][j]); }
printf("\n"); }
printf("\n\nEntered text :%s\nCipher Text :",str);
for(i=0;i<strlen(str);i++)
{
if(str[i]=='J')
str[i]='I';
if(str[i+1]=='\0')
playfair(str[i],'X',key);
else
{ if(str[i+1]=='J')
str[i+1]='I';
if(str[i]==str[i+1])
playfair(str[i],'X',key);
else {
playfair(str[i],str[i+1],key);i++; }}
}
return 0;
}

OUTPUT:

Enter key:hello

Enter the plain text:cse


HELLO
ABCDF
GIKMN
PQRST
UVWXY

Entered text :CSE


Cipher Text :DRLV

6
3. IMPLEMENTATION OF HILL CIPHER

AIM:

To write a C program to implement the hill cipher substitution techniques.

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 matrix used for
encryption. The matrix used for encryption is the cipher key, and it should be chosen
randomly from the set of invertible n × n matrices (modulo 26).

EXAMPLE:

Assume:- Input : Plaintext: ACT Key: GYBNQKURP


Then Output : Ciphertext: POH
1.Encryption

We have to encrypt the message ‘ACT’ (n=3).The key is ‘GYBNQKURP’ which can be written as
the nxn matrix:

The message ‘ACT’ is written as vector:

7
The enciphered vector is given as:

which corresponds to ciphertext of ‘POH’

2.Decryption

To decrypt the message, we turn the ciphertext back into a vector, then simply multiply by the
inverse matrix of the key matrix (IFKVIVVMI in letters).The inverse of the matrix used in the
previous example is:

For the previous Ciphertext ‘POH’:

which gives us back ‘ACT’.


Assume that all the alphabets are in upper case.

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.

8
PROGRAM:

#include<stdio.h>
#include<string.h>
int main()
{
unsigned int a[3][3]={{6,24,1},{13,16,10},{20,17,15}};
unsigned int b[3][3]={{8,5,10},{21,8,21},{21,12,8}};
int i,j, t=0;
unsigned int c[20],d[20]; char
msg[20];
printf("Enter plain text\n ");
scanf("%s",msg); for(i=0;i<strlen(msg);i+
+)
{ c[i]=msg[i]-65;
printf("%d ",c[i]);
}
for(i=0;i<3;i++) {
t=0; for(j=0;j<3;j++) {
t=t+(a[i][j]*c[j]); }
d[i]=t%26;
}
printf("\nEncrypted Cipher Text :"); for(i=0;i<3;i+
+)
printf(" %c",d[i]+65);
for(i=0;i<3;i++)
{ t=0;
for(j=0;j<3;j++) {
t=t+(b[i][j]*d[j]); }
c[i]=t%26; }
printf("\nDecrypted Cipher Text :"); for(i=0;i<3;i+
+)
printf(" %c",c[i]+65);
return 0;
}

OUTPUT:

Enter plain text


ACT
0 2 19
Encrypted Cipher Text : P O H
Decrypted Cipher Text : A C T

9
4. MPLEMENTATION OF DIJKSTRA’S ALGORITHM
AIM:

To write a C program to implement link state routing(Dijkstra's algorithm).

DESCRIPTION:

Finding the shortest distance, or path, from starting node to target node in a weighted graph is
known as Dijkstra’s Algorithm.
Dijkstra's algorithm makes use of weights of the edges for finding the path that minimizes the
total distance (weight) among the source node and all other nodes. It is based on the greedy
technique.This algorithm is also known as the single-source shortest path algorithm or link state
routing.
Dijkstra’s algorithm is the iterative algorithmic process to provide us with the shortest path from
one specific starting node to all other nodes of a graph.It is important to note that Dijkstra’s
algorithm is only applicable when all weights are positive because, during the execution, the weights
of the edges are added to find the shortest path.

ALGORITHM:

1. Mark the source node with a current distance of 0 and the rest with infinity.
2. Set the non-visited node with the smallest current distance as the current node.
3. For each neighbour, N of the current node adds the current distance of the adjacent
node with the weight of the edge connecting 0->1. If it is smaller than the current
distance of Node, set it as the new current distance of N.
4. Mark the current node 1 as visited.
5. Go to step 2 if there are any nodes are unvisited.

EXAMPLE:

Let's calculate the shortest path between node C and the other nodes in our graph:

10
Step 1:
During the algorithm execution, we'll mark every node with its minimum distance to node C (our
selected node). For node C, this distance is 0. For the rest of nodes, as we still don't know that
minimum distance, it starts being infinity (∞):

We'll also have a current node. Initially, we set it to C (our selected node). In the image, we mark
the current node with a red dot.

Step 2:

Now, we check the neighbours of our current node (A, B and D) in no specific order. Let's begin
with B. We add the minimum distance of the current node (in this case, 0) with the weight of the
edge that connects our current node with B (in this case, 7), and we obtain 0 + 7 = 7. We compare
that value with the minimum distance of B (infinity); the lowest value is the one that remains as the
minimum distance of B (in this case, 7 is less than infinity):

Next, we check neighbour A. We add 0 (the minimum distance of C, our current node) with 1 (the
weight of the edge connecting our current node with A) to obtain 1. We compare that 1 with the
minimum distance of A (infinity), and write it as the smallest value:

11
Repeat the same procedure for D:

We have checked all the neighbours of C. Because of that, we mark it as visited. Let's represent
visited nodes with a green check mark:

Step 3:

We now need to pick a new current node. That node must be the unvisited node with the smallest
minimum distance (so, the node with the smallest number and no check mark). That's A. Let's mark
it with the red dot:

And now we repeat the algorithm. We check the neighbours of our current node, ignoring the visited
nodes. This means we only check B.

For B, we add 1 (the minimum distance of A, our current node) with 3 (the weight of the edge
connecting A and B) to obtain 4. We compare that 4 with the minimum distance of B (7) and write it
as the smallest value: 4.

12
Afterwards, we mark A as visited and pick a new current node: D, which is the non-visited node
with the smallest current distance.

Step 4:

We repeat the algorithm again. This time, we check B and E.

For B, we obtain 2 + 5 = 7. We compare that value with B's minimum distance (4) and leave the
smallest value (4). For E, we obtain 2 + 7 = 9, compare it with the minimum distance of E (infinity)
and write it as the smallest one (9).

We mark D as visited and set our current node to B.

Step 5:

Next at last we only need to check E. 4 + 1 = 5, which is less than E's minimum distance (9), so we
write it as 5. Then, we mark B as visited and set E as the current node.

13
E doesn't have any non-visited neighbours, so we don't need to check anything. We mark it as
visited.

As there are not unvisited nodes, we're done! The minimum distance of each node now actually
represents the minimum distance from that node to node C (the node we picked as our initial node)!

Hence, the final paths we concluded are:

1. C = 0 (C <- C)
2. A = 1 ( A<- C)
3. B =1+3= 4 (B <- A<-C)
4. D = 2 (D <-C)
5. E = 1 + 3+1 = 5 (E <- B<- A <- C)

14
PROGRAM:

#include<stdio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far
//create the cost matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
//initialize pred[],distance[] and visited[]
for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}

15
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
//check if a better path exists through nextnode
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}

16
OUTPUT:

Node 0 1 2 3 4
s

0 0 10 0 30 100

1 10 0 50 0 0

2 0 50 0 20 10

3 30 0 20 0 60

4 100 0 10 60 0

Fig: (a) Weighted graph Fig: (b) Adjacency matrix

For the above weighted graph and its adjacency matrix,we get the desired output as given below:

Enter no. of vertices:5

Enter the adjacency matrix:


0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 10 60 0

Enter the starting node:0

Distance of node1=10
Path=1<-0
Distance of node2=50
Path=2<-3<-0
Distance of node3=30
Path=3<-0
Distance of node4=60
Path=4<-2<-3<-0

17
5.IMPLEMENTATION OF RSA ALGORITHM
AIM:

To write a C++ program to apply RSA encryption algorithm on a text file to produce a
cipher text file.

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.

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 at the sender side. The
intention is that messages encrypted with the public key can only be decrypted in a
reasonable amount of time using the private key at the receiver side.

ALGORITHM:

STEP-1: Choose two large prime numbers (p and q)


STEP-2: Calculate n = p*q and z = (p-1)(q-1)
STEP-3: Choose a number e where 1 < e < z
And also calculate [ d =e-1 mod z ].
We can bundle public key pair as (n,e) and private key pair as (n,d).
Once we generate these keys, we then find ciphertext and plaintext
using the respective key.
STEP-4: Let the plaintext be a number m, and calculate ciphertext [ c= m e mod n ].
STEP-5: And then calculate plaintext [ m= cd mod n ].

18
PROGRAM:

#include <iostream>
#include <fstream>
#include <string>
#include <cmath>

using namespace std;

// Function to perform modular exponentiation


int modular_exp(int base, int exponent, int modulus) {
int result = 1;
while (exponent > 0) {
if (exponent % 2 == 1) {
result = (result * base) % modulus;
}
exponent >>= 1;
base = (base * base) % modulus;
}
return result;
}

int main() {
// Public key (n, e) - Replace with actual large prime numbers for n and relatively prime e < n
int n = 101;
int e = 7;

// Create and open a plain text file


ofstream myFile("message.txt");
if (!myFile.is_open()) {
cerr << "Error: Could not open message file." << endl;
return 1;
}
string plainText="Appa University 2017";
// Write to the file
myFile << plainText;
// Close the file
myFile.close();

// Convert message to integers (assuming single-byte characters)


string cipherText;
for (char c : plainText) {
int charValue = static_cast<int>(c);
int encryptedChar = modular_exp(charValue, e, n);
cipherText += to_string(encryptedChar) + " ";
}

19
// Create and open a cipher text file
ofstream cipherFile("cipher.txt");
if (!cipherFile.is_open()) {
cerr << "Error: Could not open cipher file." << endl;
return 1;
}
// Write the cipher text to a file
cipherFile << cipherText;
cipherFile.close();

cout << "Message encrypted (securely)!" << endl;


return 0;
}

OUTPUT:

Message encrypted (securely)!


message.txt file contents are:-
Appa University 2017
cipher.txt file contents are:-
17 29 29 79 39 21 13 22 14 0 45 6 22 99 33 39 86 28 20 94

20
PART B

1. IMPLEMENTATION OF DES ALGORITHM

AIM:

To write a program to implement Data Encryption Standard (DES) using JAVA


Language.

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 256 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

EXAMPLE:

21
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: (Save as DES.java)

import javax.swing.*;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Random ;
class DES {
byte[] skey = new byte[1000]; String
skeyString;
static byte[] raw;
String inputMessage,encryptedData,decryptedMessage;
public DES()
{
try {
generateSymmetricKey();
inputMessage=JOptionPane.showInputDialog(null,"Enter message to
encrypt");
byte[] ibyte = inputMessage.getBytes();
byte[] ebyte=encrypt(raw, ibyte);
String encryptedData = new String(ebyte);
System.out.println("Encrypted message "+encryptedData);
JOptionPane.showMessageDialog(null,"Encrypted Data "+"\
n"+encryptedData);
byte[] dbyte= decrypt(raw,ebyte);
String decryptedMessage = new String(dbyte);
System.out.println("Decrypted message "+decryptedMessage);
JOptionPane.showMessageDialog(null,"Decrypted Data "+"\
n"+decryptedMessage);
}

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

22
void generateSymmetricKey() {
try {
Random r = new Random();
int num = r.nextInt(10000);
String knum = String.valueOf(num);
byte[] knumb = knum.getBytes();
skey=getRawKey(knumb);
skeyString = new String(skey);
System.out.println("DES Symmetric key = "+skeyString); }
catch(Exception e) {
System.out.println(e); }
}

private static byte[] getRawKey(byte[] seed) throws Exception {


KeyGenerator kgen = KeyGenerator.getInstance("DES");
SecureRandom sr = SecureRandom.getInstance("SHA1PRNG");
sr.setSeed(seed);
kgen.init(56, sr);
SecretKey skey = kgen.generateKey();
raw = skey.getEncoded();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[]
encrypted = cipher.doFinal(clear); return encrypted;
}

private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception


{
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}

public static void main(String args[])


{
DES des = new DES();
}
}

23
OUTPUT:

24
2. IMPLEMENTATION OF AESALGORITHM

AIM :

To write a program to implement Advanced Encryption Standard (DES) using


JAVA Language.

DESCRIPTION:

The AES algorithm (also known as the Rijndael algorithm) is a symmetrical block cipher
algorithm that takes plain text in blocks of 128 bits and converts them to ciphertext using keys of
128, 192, and 256 bits. Since the AES algorithm is considered secure, it is in the worldwide
standard.

The AES algorithm uses a substitution-permutation, or SP network, with multiple rounds to


produce ciphertext. The number of rounds depends on the key size being used. A 128-bit key size
dictates ten rounds, a 192-bit key size dictates 12 rounds, and a 256-bit key size has 14 rounds. Each
of these rounds requires a round key, but since only one key is inputted into the algorithm, this key
needs to be expanded to get keys for each round, including round 0.

Figure: 1

25
ALGORI THM :

Each round in the above Figure:1 consists of four steps.

1. Substitution of the bytes


In the first step, the bytes of the block text are substituted based on rules dictated by predefined S-
boxes (short for substitution boxes).

2. Shifting the rows


Next comes the permutation step. In this step, all rows except the first are shifted by one, as shown
below.

3. Mixing the columns


In the third step, the Hill cipher is used to jumble up the message more by mixing the block’s
columns.

26
4. Adding the round key

In the final step, the message is XORed with the respective round key.

When done repeatedly, these steps ensure that the final ciphertext is secure.

PROGRAM : (Save as 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();
}
}

27
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) {
System.out.println("\nEnter the secret key: ");
String secretKey= System.console().readLine();
System.out.println("\nEnter an Alphanumeric message: ");
String originalString= System.console().readLine();
String encryptedString = AES.encrypt(originalString, secretKey);
String decryptedString = AES.decrypt(encryptedString, secretKey);
System.out.println("\nEncryption & Decryption using AES Algorithm :-\n");
System.out.println("Original message : " + originalString);
System.out.println("Encrypted message : "+ encryptedString);
System.out.println("Decrypted message : "+ decryptedString);
}
}

O U TP U T:

Enter the secret key:


BigKeyNumber
Enter an Alphanumeric message:
AppaUniversity2017year

Encryption & Decryption using AES Algorithm :-


Original message :
AppaUniversity2017year
Encrypted message :
awLv+wBAxfPWdfmegzJ6I8jlygZXXVYMiJu0uYMNbjg=
Decrypted message :
AppaUniversity2017year

28
3. IMPLEMENTATION OF DIFFIE HELLMAN KEY EXCHANGE ALGORITHM

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.

EXAMPLE:

29
ALGORITHM:

STEP-1: Sender and receiver publicly agree to use a modulus p and base g which is a
primitive root modulo p.
STEP-2. Sender chooses a secret integer x then sends Bob R1 = gx mod p
STEP-3. Receiver chooses a secret integer y, then sends Alice R2 = gy mod p
STEP-4. Sender computes k1 = Bx mod p
STEP-5. Receiver computes k2 = Ay mod p
STEP-6. Sender and Receiver now share a secret key.

PROGRAM: (Save as dh.java)

import java.io.*;
import java.math.BigInteger;
class dh
{
public static void main(String[]args)throws IOException {
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter prime number:");
BigInteger p=new BigInteger(br.readLine());
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("Keycalculated at Sender's side: "+ k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Receiver's side: "+ k2);
System.out.println("Diffie-Hellmansecret keywas calculated.");
}
}

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 Sender's side:9
Key calculated at Receiver's side:9
Diffie-Hellman secret key was calculated.

30
4. IMPLEMENTATION OF SECURE HASH ALGORITHM

AIM:

To write a program to implement the Secure Hash Algorithm(SHA-I) for data integrity
using Java language.

DESCRIPTION:

In cryptography, SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function.


SHA-1 produces a 160-bit hash value known as a message digest. The way
this algorithm works is that for a message of size < 264 bits it computes a 160-bit condensed
output called a message digest. The SHA-1 algorithm is designed so that it is practically
infeasible to find two input messages that hash to the same output message. A hash function
such as SHA-1 is used to calculate an alphanumeric string that serves as the cryptographic
representation of a file or a piece of data. This is called a digest and can serve as a digital
signature. It is supposed to be unique and non-reversible.

EXAMPLE:

ALGORITHM:

STEP-1: Read the 256-bit key values.


STEP-2: Divide into five equal-sized blocks named A, B, C, D and E.
STEP-3: The blocks B, C and D are passed to the function F.

31
STEP-4: The resultant value is permuted with block E.
STEP-5: The block A is shifted right by ‘s’ times and permuted with the result of step-4.

STEP-6: Then it is permuted with a weight value and then with some other key pair and
taken as the first block.
STEP-7: Block A is taken as the second block and the block B is shifted by ‘s’ times and
taken as the third block.
STEP-8: The blocks C and D are taken as the block D and E for the final output.

PROGRAM: (Save as sha1.java)

import java.util.Scanner;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class sha1
{
public static void main(String[] args)throws NoSuchAlgorithmException {
Scanner sc = new Scanner(System.in);
System.out.println("Enter the String:");
String message = new String(); message = sc.next();
System.out.println("Mesage Digest is=");
System.out.println(sha1(message));
}
static String sha1(String input) throws NoSuchAlgorithmException {
MessageDigest mDigest =MessageDigest.getInstance("SHA1");
byte[] result = mDigest.digest(input.getBytes());
StringBuffer sb= new StringBuffer();
for(int i= 0;i<result.length;i++)
{
sb.append(Integer.toString((result[i] & 0xff) +0x100, 16).substring(1));
}
return sb.toString();
}
}

O U TP U T:

Enter the String:


SECURE HASH ALGORITHM EXAMPLE
Mesage Digest is=
e7dddf606d95d6a4f5ca7fae44435abe7b427c0b

32
5.IMPLEMENTATION OF D IGITAL SI GNATURE STANDARD

AIM :
To write a program to implement the signature scheme - Digital Signature Standard
using Java language.

ALGORI THM :

1. Declare the class and required variables.


2. Create the object for the class in the main program.
3. Access the member functions using the objects.
4. Implement the SIGNATURE SCHEME - Digital Signature
Standard. 5. It uses a hash function.
6. The hash code is provided as input to a signature function along with a
random number K generated for the particular signature.
7. The signature function also depends on the sender„s private
key. 8. The signature consists of two components.
9. The hash code of the incoming message is generated.
10. The hash code and signature are given as input to a verification function.

PROGRAM :(Save as dsaAlg.java)

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

class dsaAlg {
final static BigInteger one = new BigInteger("1");
final static BigInteger zero = new BigInteger("0");
public static BigInteger getNextPrime(String ans)
{
BigInteger test = new BigInteger(ans);
while (!test.isProbablePrime(99))
e: {
test =test.add(one); }
return test; }
public static BigInteger findQ(BigInteger n) {
BigInteger start = new BigInteger("2");
while (!n.isProbablePrime(99))
{ while(!((n.mod(start)).equals(zero))) {
start = start.add(one); }
n= n.divide(start); }
return n; }

public static BigInteger getGen(BigInteger p, BigInteger q, Random r)


{
BigInteger h= new BigInteger(p.bitLength(), r);
h= h.mod(p);
return h.modPow((p.subtract(one)).divide(q), p); }

33
public static void main (String[] args) throws java.lang.Exception
{

Random randObj = new Random();


BigInteger p = getNextPrime("10600"); /* approximate prime */
BigInteger q = findQ(p.subtract(one));
BigInteger g= getGen(p,q,randObj);
System.out.println(" \n Simulation of Digital Signature Algorithm\n");
System.out.println("Global public key components are:\n");
System.out.println(" p is: " + p);
System.out.println("\n q is: " + q);
System.out.println("\n g is: "+ g);
BigInteger x = new BigInteger(q.bitLength(), randObj);
x= x.mod(q);
BigInteger y= g.modPow(x,p);
BigInteger k = new BigInteger(q.bitLength(), randObj);
k = k.mod(q);
BigInteger r= (g.modPow(k,p)).mod(q);
BigInteger hashVal= new BigInteger(p.bitLength(), randObj);
BigInteger kInv= k.modInverse(q);
BigInteger s =kInv.multiply(hashVal.add(x.multiply(r)));
s = s.mod(q);
System.out.println("\nSecret information are:\n");
System.out.println("x (private) is:" + x);
System.out.println("k (secret) is: "+ k);
System.out.println("y (public) is: " + y);
System.out.println("h (rndhash) is: " + hashVal);
System.out.println("\n Generating digital signature:\n");
System.out.println("r is : " + r);
System.out.println("s is : " + s);
BigInteger w=s.modInverse(q);
BigInteger u1 = (hashVal.multiply(w)).mod(q);
BigInteger u2 =(r.multiply(w)).mod(q);
BigInteger v= (g.modPow(u1,p)).multiply(y.modPow(u2,p));
v= (v.mod(p)).mod(q);
System.out.println("\nVerifying digital signature (checkpoints):\n");
System.out.println("w is : " + w);
System.out.println("u1 is : " + u1);
System.out.println("u2 is : " + u2);
System.out.println("v is : " + v);
if (v.equals(r))
{
System.out.println("\nSuccess:digital signature is verified!\n "+ r); }
else {
System.out.println("\nerror: incorrect digitalsignature\n "); }
}
}

34
O U TP U T:

Simulation of Digital Signature Algorithm

Global public key components are:

p is: 10601

q is: 53

g is: 479

Secret information are:

x (private) is:29
k (secret) is: 32
y (public) is: 6084
h (rndhash) is: 3991

Generating digital signature:

r is : 47
s is : 5

Verifying digital signature (checkpoints):

w is : 32
u1 is : 35
u2 is : 20
v is : 47

Success:digital signature is verified!


47

====================+++++++++++++++++++++++++++========================

35

You might also like