CryptographyLabFile(KCS-751A)
CryptographyLabFile(KCS-751A)
Semester- VII
Lab File
Cryptography and Network
Security Lab
(KCS751A)
Submitted To : Submitted By :
Faculty Name : Name :
Designation : Roll No. :
Section :
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
Table of Contents
Institute Vision/Mission
Department Vision/Mission
Course Outcomes
Outcomes/CO-PO/PSO Mapping
List of Experiments
Index
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
To achieve excellence in professional education and create an ecosystem for the holistic development
of all stakeholders.
To provide an environment of effective learning and innovation transforming students into dynamic,
responsible and productive professionals in their respective fields, who are capable of adapting to the
changing needs of the industry and society.
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
PO4 Investigation
Use research-based knowledge of Computer Science &
Engineering and research methods including design of
experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.
PO5 Modern Tool Usage Create, select, and apply appropriate techniques, resources,
and modern engineering and Computer Science & Engineering
tools including prediction and modelling to complex
Computer activities with an understanding of the limitations.
PO6 The Engineer and
Apply reasoning informed by the contextual knowledge to
Society assess societal, health, safety, legal and cultural issues and the
consequent responsibilities relevant to the professional
engineering practice in the field of Computer Scien Science &
Engineering.
PO7 Environment and Understand the impact of the professional Computer Science
Sustainability & Engineering solutions in societal and environmental
contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8 Ethics Apply ethical principles and commit to professional ethics and
responsibilities and norms of the Computer Science &
Engineering practice.
PO9 Individual and Team Function effectively as an individual, and as a member or
Work leader in diverse teams, and in multidisciplinary settings.
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
PO10 Communication Communicate effectively on complex being able to
comprehend and write effective reports and design
documentation, make effective presentations, and give and
receive clear instructions.
PO11 Project Management Demonstrate knowledge and understanding of the Computer
and Finance Science & Engineering and management principles and apply
these to one's own work, as a member and leader in a team,
to manage projects and in multidisciplinary environments.
PO12 Life-long Learning Recognize the need for, and have the preparation and ability to
engage in independent and life-long
long learning in the broadest
context of technological change.
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
PSO2 Effectively integrate Computer Science & Engineering based solutions into the user
environment.
Course Outcomes
S.NO. TOPIC CO
1 (a) Write a C program that contains a string (char pointer) with a value CO1
\Hello World’. The program should XOR each character in this
string with 0 and displays the result.
(b) Write a C program that contains a string (char pointer) with a value
\Hello World’. The program should AND, OR and XOR each
character in this string with 127 and display the result
2 Write a Java program to perform encryption and decryption using the CO2
following algorithms: a)Ceaser Cipher b)Substitution Cipher
3 Write a Java program to perform encryption and decryption using the CO2
following algorithms: a)Hill Cipher b)Playfair Cipher
4 Implement Rabin-Miller
Miller Primality Testing Algorithm. CO2
5 Implement the Euclid Algorithm to generate the GCD of an array of 10 CO2
integers.
6 Write a Java program to implement the DES algorithm logic CO2
12 Calculate the message digest of a text using the SHA-1 algorithm in JAVA. CO2
13 Calculate the message digest of a text using the MD5 algorithm in JAVA. CO2
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
INDEX
S No Lab Experiment Date of Date of Marks Faculty
Experiment Submission Signature
10
11
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
AIM: Write a C program that contains a string (char pointer) with a value \Hello
\ World’. The
program should XOR each character in this string with 0 and display the result.
PROGRAM:
#include<stdlib.h>
main()
char str1[11];
int i,len;
len=strlen(str);
for(i=0;i<len;i++)
str1[i]=str[i]^0;
printf("%c",str1[i]);
printf("\n");
Output:
Hello World
Hello World
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
AIM: Write a C program that contains a string (char pointer) with a value \Hello World’. The
program should AND or and XOR each character in this string with 127 and display the
result.
PROGRAM:
#include <stdio.h>
#include<stdlib.h>
void main()
{
char str[]="Hello World";
char str1[11];
char str2[11]=str[];
int i,len;
len = strlen(str);
for(i=0;i<len;i++)
{
str1[i] = str[i]&127;
printf("%c",str1[i]);
printf("\n");
for(i=0;i<len;i++)
{
str3[i] = str2[i]^127;
printf("%c",str3[i]);
}
printf("\n");
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
}
Output:
Hello World
Hello World
Hello World
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
AIM: Write a Java program to perform encryption and decryption using the following
algorithms:
a) Ceaser Cipher
b) Substitution Cipher
PROGRAM:
a) Ceaser Cipher
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
System.out.println("\nEncrypted
nEncrypted String is: " +encrypted);
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
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;
c = c + 26;
else if (Character.isLowerCase(c)) { c =
c - (key % 26);
if (c < 'a')
c = c + 26;
decrypted += (char) c;
return decrypted;
Output:
b) Substitution Cipher
PROGRAM:
import java.io.*;
import java.util.*;
char c;
for(int i=0;i<str.length();i++)
c = str.charAt(i);
int j = a.indexOf(c);
decrypt = decrypt+b.charAt(j);
}
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
Output:
AIM: Write a Java program to perform encryption and decryption using the following
algorithms:
a) Hill Cipher
b) Playfair Cipher
a) Hill Cipher
PROGRAM:
import java.io.*;
import java.util.*;
class HillCipher {
System.out.print((char)(res[i][0]%26+97));
res[i][0]=res[i][0];
inverse();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++) {
decrypt[i][j] = decrypt[i][j]+b[i][k]*res[k][j]; }
System.out.print("\nDecrypted
nDecrypted string is : ");
for(int i=0;i<3;i++){
System.out.print((char)(decrypt[i][0]%26+97));
System.out.print("\n");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j] = sc.nextFloat();
for(int i=0;i<3;i++)
mes[i][0] = msg.charAt(i)-97;
97;
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
floatp,q;
float[][] c = a;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
//a[i][j]=sc.nextFloat();
if(i==j)
b[i][j]=1;
else b[i][j]=0;
for(int k=0;k<3;k++) {
for(int i=0;i<3;i++) {
p = c[i][k];
q = c[k][k];
for(int j=0;j<3;j++) {
if(i!=k) {
c[i][j] = c[i][j]*q-p*c[k][j];
p*c[k][j];
b[i][j] = b[i][j]*q-p*b[k][j];
p*b[k][j];
}}}}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++) {
b[i][j] = b[i][j]/c[i][i]; }
System.out.println("");
System.out.println("\nInverse
nInverse Matrix is : ");
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++)
System.out.print("\n"); }
}}
Output:
Inverse Matrix is :
-0.41666666 -0.083333336
0.083333336 0.6666667
b) Playfair Cipher
Theory:
The Playfair cipher was the first practical digraph substitution cipher. The scheme was invented
in 1854 by Charles Wheatstone but was named after Lord Playfair who promoted the use of the
cipher. In playfair cipher unlike traditional cipher we encrypt
ncrypt a pair of alphabets(digraphs) instead of a
single alphabet.
It was used for tactical purposes by British forces in the Second Boer War and in World War I and for
the same purpose by the Australians during World War II. This was because Playfair is reasonably fast
to use and requires no special equipment.
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
Encryption Technique
Key: monarchy
Plain Text: instruments
The Playfair Cipher Encryption Algorithm: The Algorithm consists of 2 steps:
1. Generate the key Square(5×5):
The key square is a 5×5 grid of alphabets that acts as the key for encrypting the
plaintext. Each of the 25 alphabets must be unique and one letter of the alphabet (usually
J) is omitted from the table (as the table can hold only 25 alphabets). If the plaintext
contains J, then it is replaced by I.
The initial alphabets in the key square are the unique alphabets of the key in the order in
which they appear followed by the remaining letters of the alphabet in order.
2. Algorithm to encrypt the plain text: The plaintext is split into pairs of two letters (digraphs).
If there is an odd number of letters, a Z is added to the last letter.
For example:
PlainText: "instruments"
After Split: 'in' 'st' 'ru' 'me' 'nt' 'sz'
Rules for Encryption:
If both the letters are in the same column: Take the letter below each one (going back to the
top if at the bottom).
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 30
{
int i, count = 0;
for (i = 0; i < ps; i++)
if (plain[i] != ' ')
plain[count++] = plain[i];
plain[count] = '\0';
return count;
}
// a 26 character hashmap
// to store count of the alphabet
dicty = (int*)calloc(26, sizeof(int));
for (i = 0; i < ks; i++) {
if (key[i] != 'j')
dicty[key[i] - 97] = 2;
}
dicty['j' - 97] = 1;
i = 0;
j = 0;
}
}
if (a == 'j')
a = 'i';
else if (b == 'j')
b = 'i';
if (keyT[i][j] == a) {
arr[0] = i;
arr[1] = j;
}
else if (keyT[i][j] == b) {
arr[2] = i;
arr[3] = j;
}
}
}
}
{
int i, a[4];
if (a[0] == a[2]) {
str[i] = keyT[a[0]][mod5(a[1] + 1)];
str[i + 1] = keyT[a[0]][mod5(a[3] + 1)];
}
else if (a[1] == a[3]) {
str[i] = keyT[mod5(a[0] + 1)][a[1]];
str[i + 1] = keyT[mod5(a[2] + 1)][a[1]];
}
else {
str[i] = keyT[a[0]][a[3]];
str[i + 1] = keyT[a[2]][a[1]];
}
}
}
// Key
ks = strlen(key);
ks = removeSpaces(key, ks);
toLowerCase(key, ks);
// Plaintext
ps = strlen(str);
toLowerCase(str, ps);
ps = removeSpaces(str, ps);
ps = prepare(str, ps);
// Driver code
int main()
{
char str[SIZE], key[SIZE];
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
// Key to be encrypted
strcpy(key, "Monarchy");
printf("Key text: %s\n", key);
// Plaintext to be encrypted
strcpy(str, "instruments");
printf("Plain text: %s\n", str);
return 0;
}
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
Theory:
// It returns false if n is composite and returns true if n
// is probably prime. k is an input parameter that determines
// accuracy level. Higher value of k indicates more accuracy.
bool isPrime(int n, int k)
1) Handle base cases for n < 3
2) If n is even, return false.
3) Find an odd number d such that n-1 can be written as d*2r.
Note that since n is odd, (n-1)1) must be even and r must be
greater than 0.
4) Do following k times
if (millerTest(n, d) == false)
return false
5) Return true.
Program:
import java.io.*;
import java.math.*;
class GFG {
while (y > 0) {
return res;
}
// Compute a^d % n
int x = power(a, d, n);
if (x == 1 || x == n - 1)
return true;
if (x == 1)
return false;
if (x == n - 1)
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
return true;
}
// Return composite
return false;
}
// Corner cases
if (n <= 1 || n == 4)
return false;
if (n <= 3)
return true;
while (d % 2 == 0)
d /= 2;
return true;
}
// Driver program
public static void main(String args[]) {
Objective: Implement the Euclid Algorithm to generate the GCD of an array of 10 integers in
‘C’/Java.
Theory: One of the earliest known numerical algorithms is that developed by Euclid (the father of
geometry) in about 300 B.C. for computing the greatest common divi sor (GCD) of two positive
divisor
integers.
GCD(x,y) = GCD(x,x) = x
GCD(x,y) = GCD(x-y,y)
Program:
// Java program to find GCD of two or more numbers
return result;
}
PROGRAM:
import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
r;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
privateKeySpecmyKeySpec;
privateSecretKeyFactorymySecretKeyFactory;
byte[] keyAsBytes;
SecretKey key;
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
= new DESedeKeySpec(keyAsBytes);
mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
cipher = Cipher.getInstance(myEncryptionScheme);
key = mySecretKeyFactory.generateSecret(myKeySpec);
cretKeyFactory.generateSecret(myKeySpec);
try {
cipher.init(Cipher.ENCRYPT_MODE, key);
encryptedString = base64encoder.encode(encryptedText); }
catch (Exception e) {
e.printStackTrace(); }
returnencryptedString; }
{ String decryptedText=null;
try {
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
cipher.init(Cipher.DECRYPT_MODE, key);
bytes2String(plainText); }
catch (Exception e) {
e.printStackTrace(); }
returndecryptedText; }
returnstringBuffer.toString(); }
OUTPUT:
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;
if (iv != null) {
int input = 0;
fin.close(); cout.close(); }}
OUTPUT:
PROGRAM:
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
strbuf.append("0");
return strbuf.toString(); }
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
OUTPUT:
Input your message: Hello KGRCET
AIM: Using Java Cryptography, encrypt the text “Hello world” using BlowFish.
PROGRAM:
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.JOptionPane;
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
"\nDecrypted
nDecrypted text: " + new String(decrypted));
System.exit(0);
}}
OUTPUT:
It is a public-key scheme which may be used for encrypting messages, exchanging keys, and
creating digital signatures
is based on exponentiation in a finite (Galois) field over integers modulo a prime
o nb exponentiation takes O((log n)3) operations
its security relies on the difficulty of calculating factors of large numbers
o nb factorization takes O(e log n log log n) operations
o (same as for discrete logarithms)
the algorithm is patented in North America (although algorithms cannot be patented
elsewhere in the world)
o this is a source of legal difficulties in using the scheme
RSA is a public key encryption algorithm based on exponentiation using modular arithmetic
to use the scheme, first generate keys:
Key-Generation by each user consists of:
o selecting two large primes at random (~100 digit), p, q
o calculating the system modulus R=p.q p, q primes
o selecting at random the encryption key e,
o e < R, gcd(e, F(R)) = 1
o solving the congruence to find the decryption key d,
o e.d [[equivalence]] 1 mod [[phi]](R) 0 <= d <= R
o publishing the public encryption key: K1={e,R}
o securing the private decryption key: K2={d,p,q}
Encryption of a message M to obtain ciphertext C is:
C = Me mod R 0 <= d <= R
Decryption of a ciphertext C to recover the message M is:
o M = Cd = Me.d = M1+n.[[phi]](R) = M mod R
the RSA system is based on the following result:
if R = pq where p, q are distinct large primes then
X [[phi]](R) = 1 mod R
for all x not divisible by p or q
and [[Phi]](R) = (p-1)(q-1)
PROGRAM:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
import java.util.Random;
import java.util.Scanner;
BigInteger e = generateE(n2);
generateE(n
int y, intGCD;
BigInteger e;
BigInteger gcd;
do {
y = x.nextInt(fiofn.intValue()
x.nextInt(fiofn.intValue()-1);
String z = Integer.toString(y);
e = new BigInteger(z);
gcd = fiofn.gcd(e);
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
intGCD = gcd.intValue();
return e;
OUTPUT:
import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.SecureRandom;
import javax.crypto.spec.DHParameterSpec;
import javax.crypto.spec.DHPublicKeySpec;
public class DiffeHellman { public final static int
pValue = 47;
public final static int gValue = 71;
BigIntegerXa = new
BigInteger(Integer.toString(XaValue)); BigIntegerXb =
p = BigInteger.probablePrime(bitLength, rnd);
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India
g = BigInteger.probablePrime(bitLength, rnd);
createSpecificKey(p, g);
KeyPairGeneratorkpg = KeyPairGenerator.getInstance("DiffieHellman");
kpg.initialize(512);
KeyPairkp = kpg.generateKeyPair();
KeyFactorykfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec.class);
Exception { KeyPairGeneratorkpg =
DHParameterSpec(p,
rameterSpec(p, g); kpg.initialize(param);
KeyPairkp = kpg.generateKeyPair();
KeyFactorykfactory = KeyFactory.getInstance("DiffieHellman");
DHPublicKeySpec.class);
System.out.println("\nPublic
nPublic key is : " +kspec);
OUTPUT: