INS Lab-Manual
INS Lab-Manual
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:
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:
2
2. IMPLEMENTATION OF PLAYFAIR CIPHER
AIM:
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:
PROGRAM:
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#define MX 5
//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]);
}
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
6
3. IMPLEMENTATION OF HILL CIPHER
AIM:
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:
We have to encrypt the message ‘ACT’ (n=3).The key is ‘GYBNQKURP’ which can be written as
the nxn matrix:
7
The enciphered vector is given as:
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:
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:
9
4. MPLEMENTATION OF DIJKSTRA’S ALGORITHM
AIM:
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:
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).
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)!
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
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;
}
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++;
}
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
For the above weighted graph and its adjacency matrix,we get the desired output as given below:
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:
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:
18
PROGRAM:
#include <iostream>
#include <fstream>
#include <string>
#include <cmath>
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;
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();
OUTPUT:
20
PART B
AIM:
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.
EXAMPLE:
21
ALGORITHM:
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); }
}
23
OUTPUT:
24
2. IMPLEMENTATION OF AESALGORITHM
AIM :
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.
Figure: 1
25
ALGORI THM :
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.
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;
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:
28
3. IMPLEMENTATION OF DIFFIE HELLMAN KEY EXCHANGE ALGORITHM
AIM:
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.
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:
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:
EXAMPLE:
ALGORITHM:
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.
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:
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 :
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; }
33
public static void main (String[] args) throws java.lang.Exception
{
34
O U TP U T:
p is: 10601
q is: 53
g is: 479
x (private) is:29
k (secret) is: 32
y (public) is: 6084
h (rndhash) is: 3991
r is : 47
s is : 5
w is : 32
u1 is : 35
u2 is : 20
v is : 47
====================+++++++++++++++++++++++++++========================
35