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

CryptographyLabFile(KCS-751A)

crpytology file

Uploaded by

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

CryptographyLabFile(KCS-751A)

crpytology file

Uploaded by

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

PRANVEER SINGH INSTITUTE OF TECHNOLOGY, KANPUR

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

Odd Semester 2024-25

B. Tech.- Fourth Year

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

 PEOs / POs/PSOs of the Department

 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

Vision Statement of the Institute

To achieve excellence in professional education and create an ecosystem for the holistic development
of all stakeholders.

Mission Statement of the Institute

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

Vision Statement of the Department

To be recognized as an impeccable department, th


that
at escalates the scholar into Computer Science &
Engineering engineers for the innovative professional to make capable of adapting the ever-changing
ever
computer related industry.

Mission Statements of the Department

1. Impart quality education


cation in Computer Science & Engineering of global standards by providing
broad based knowledge and extensive practical training so as to prepare students for
career/self- employment and higher studies.
2. Promote continuous improvement in teaching learning process, foster innovation and research
for
or attaining academic excellence by students and faculty.
3. Promote collaboration with industry to bridge the gap between academic and indus
industrial
application in emerging Computer Science Technologies.
4. Inculcate value based socially committed professionalism for the cause of overall development
of students and society.
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Program Educational Objectives (PEOs)


PEOs Description
The graduate will excel in Computer Science & Engineering with strong foundation
PEO1 that prepares them in use of recent tools & techniques and be employable/pursue
higher studies.
The graduate will possess
possess in depth knowledge of Computer Science & Engineering
PEO2 Technologies, concepts of programming languages, software development process,
computer-networking
networking and communication technology.
The graduate will possess excellent communication skills, ethical thinking, leadership
PEO3 qualities and self/lifelong learning attitude.
The graduate will possess broad based knowledge, logical reasoning, and innovative
PEO4 approaches to solve real life problems.
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Program Outcomes (POs)


POs Graduate Attributes Description
PO1 Engineering
Apply the knowledge of mathematics, science and
Knowledge Computer Science & Engineering fundamentals to the solution
of complex engineering problems.
PO2 Problem Analysis Identify, formulate, review research literature, and analyze
complex Computer Science & Engineering problems reaching
substantiated conclusions using principles of mathematics,
natural sciences, and engineering.
PO3 Design/Development Use research-based knowledge of Computer Science &
of Solutions Engineering and research methods including design of
experiments, analysis and interpretation of data, and synthesis
of the information to provide valid conclusions.

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

Program Specific Outcomes (PSOs)


PSOs Description
Design an algorithm, component, or process to meet desired needs, within realistic
PSO1
constraints through analytical, logical and problem solving skills.

PSO2 Effectively integrate Computer Science & Engineering based solutions into the user
environment.

Course Outcomes

*Level of Bloom’s *Level of Bloom’s


Level to be met Level to be met
Taxonomy Taxonomy
L1: Knowledge 1 L2: Comprehension 2
L3: Application 3 L4: Analysis 4
L5: synthesis 5 L6: Evaluation 6

Student will be able to evaluate [2. Comprehension] the asymmetric and


CO1
symmetric key generation technique using various algorithms.
Student will be able to apply [3. Application] various encryption and decryption
CO2
algorithm for data security.
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

List of Experiments as per AKTU guideline

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

7 Write a C/JAVA program to implement the BlowFish algorithm logic CO2

8 Write a C/JAVA program to implement the Rijndael algorithm logic. CO2


9 Using Java Cryptography, encrypt the text “Hello world” using BlowFish. CO1
Create your own key using Java keytool.
10 Write a Java program to implement RSA Algorithm CO2
11 Implement the Diffie-Hellman
Hellman Key Exchange mechanism using HTML CO1
and JavaScript. Consider the end user as one of the parties (Alice) and the
JavaScript application as other party (Bob).

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

EXPERIMENT 1(a): XOR a string with a Zero

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 str[]="Hello World";

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

EXPERIMENT 1(b): XOR a string with a 127

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

EXPERIMENT 2: Encryption & Decryption using Cipher Algorithms

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;

public class CeaserCipher {

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

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


r(System.in));

public static void main(String[] args) throws IOException {

// TODO code application logic here

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

String str = br.readLine();

System.out.print("\nEnter the Key: ");

int key = sc.nextInt();

String encrypted = encrypt(str, key);

System.out.println("\nEncrypted
nEncrypted String is: " +encrypted);
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

String decrypted = decrypt(encrypted, key);


System.out.println("\nDecrypted
nDecrypted String is: " +decrypted);
System.out.println("\n");
}

public static String encrypt(String str, int key)

{ String encrypted = "";

for(int i = 0; i < str.length(); i++) {

int c = str.charAt(i);
if (Character.isUpperCase(c)) {

c = c + (key % 26);

if (c > 'Z')

c = c - 26;

else if (Character.isLowerCase(c)) {

c = c + (key % 26);

if (c > 'z')

c = c - 26;

encrypted += (char) c;

return encrypted;

public static String decrypt(String str, int key)

{ String decrypted = "";


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

for(int i = 0; i < str.length(); i++) { int


c = str.charAt(i);
if (Character.isUpperCase(c)) { c =
c - (key % 26);
if (c < 'A')

c = c + 26;

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

c = c + 26;

decrypted += (char) c;

return decrypted;

Output:

Enter any String: Hello World

Enter the Key: 5

Encrypted String is: MjqqtBtwqi

Decrypted String is: Hello World


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

b) Substitution Cipher

PROGRAM:

import java.io.*;

import java.util.*;

public class SubstitutionCipher {

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

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

public static void main(String[] args) throws IOException {

// TODO code application logic here String a =


"abcdefghijklmnopqrstuvwxyz"; String b =
"zyxwvutsrqponmlkjihgfedcba";

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

String str = br.readLine();

String decrypt = "";

char c;

for(int i=0;i<str.length();i++)

c = str.charAt(i);

int j = a.indexOf(c);

decrypt = decrypt+b.charAt(j);

System.out.println("The encrypted data is: " +decrypt);

}
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

Output:

Enter any string: aceho

The encrypted data is: zxvsl


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

EXPERIMENT 3: Encryption & Decryption using Cipher Algorithms

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.*;

import java.io.*; public

class HillCipher {

static float[][] decrypt = new float[3][1];

static float[][] a = new float[3][3]; static

float[][] b = new float[3][3]; static

float[][] mes = new float[3][1]; static

float[][] res = new float[3][1];


[3][1];

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));


static Scanner sc = new Scanner(System.in); public static void main(String[] args) throws
IOException {
// TODO code application logic
here getkeymes();
for(int i=0;i<3;i++)
3;i++) for(int j=0;j<1;j++) for(int
k=0;k<3;k++) {
res[i][j]=res[i][j]+a[i][k]*mes[k][j]; }
System.out.print("\nEncrypted
nEncrypted string is : ");
for(int i=0;i<3;i++) {
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

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");

public static void getkeymes() throws IOException {

System.out.println("Enter 3x3 matrix for key (It should be inversible): ");

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

for(int j=0;j<3;j++)

a[i][j] = sc.nextFloat();

System.out.print("\nEnter a 3 letter string: ");

String msg = br.readLine();

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

public static void inverse() {

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(b[i][j] + " ");

System.out.print("\n"); }

}}

Output:

Enter a 3 letter string: hai

Encrypted string is :fdx

Inverse Matrix is :

0.083333336 0.41666666 -0.33333334

-0.41666666 -0.083333336
0.083333336 0.6666667

0.5833333 -0.083333336 --0.33333334

Decrypted string is: hai

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

For the encryption process let us consider the following example:

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

// Function to convert the string to lowercase


void toLowerCase(char plain[], int ps)
{
int i;
for (i = 0; i < ps; i++) {
if (plain[i] > 64 && plain[i] < 91)
plain[i] += 32;
}
}

// Function to remove all spaces in a string


int removeSpaces(char* plain, int ps)
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

{
int i, count = 0;
for (i = 0; i < ps; i++)
if (plain[i] != ' ')
plain[count++] = plain[i];
plain[count] = '\0';
return count;
}

// Function to generate the 5x5 key square


void generateKeyTable(char key[], int ks, char keyT[5][5])
{
int i, j, k, flag = 0, *dicty;

// 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;

for (k = 0; k < ks; k++) {


if (dicty[key[k] - 97] == 2) {
dicty[key[k] - 97] -= 1;
keyT[i][j] = key[k];
j++;
if (j == 5) {
i++;
j = 0;
}
}
}

for (k = 0; k < 26; k++) {


if (dicty[k] == 0) {
keyT[i][j] = (char)(k + 97);
j++;
if (j == 5) {
i++;
j = 0;
}
}
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

}
}

// Function to search for the characters of a digraph


// in the key square and return their position
void search(char keyT[5][5], char a, char b, int arr[])
{
int i, j;

if (a == 'j')
a = 'i';
else if (b == 'j')
b = 'i';

for (i = 0; i < 5; i++) {

for (j = 0; j < 5; j++) {

if (keyT[i][j] == a) {
arr[0] = i;
arr[1] = j;
}
else if (keyT[i][j] == b) {
arr[2] = i;
arr[3] = j;
}
}
}
}

// Function to find the modulus with 5


int mod5(int a)
{
return (a % 5);
}

// Function to make the plain text length to be even


int prepare(char str[], int ptrs)
{
if (ptrs % 2 != 0) {
str[ptrs++] = 'z';
str[ptrs] = '\0';
}
return ptrs;
}

// Function for performing the encryption


void encrypt(char str[], char keyT[5][5], int ps)
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

{
int i, a[4];

for (i = 0; i < ps; i += 2) {

search(keyT, str[i], str[i + 1], a);

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]];
}
}
}

// Function to encrypt using Playfair Cipher


void encryptByPlayfairCipher(char str[], char key[])
{
char ps, ks, keyT[5][5];

// 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);

generateKeyTable(key, ks, keyT);

encrypt(str, keyT, 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);

// encrypt using Playfair Cipher


encryptByPlayfairCipher(str, key);

printf("Cipher text: %s\n", str);

return 0;
}
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

EXPERIMENT 4: Rabin-Miller Primality Testing Algorithm

Objective: Implement Rabin-Miller


Miller Primality Testing Algorithm in ‘C’/Java.

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.

// This function is called for all k trials. It returns


// false if n is composite and returns false if n is probably
// prime.
// d is an odd number such that d*2r = n-1 for some r >= 1
bool millerTest(int n, int d)
1) Pick a random number 'a' in range [2, n-2]
2) Compute: x = pow(a, d) % n
3) If x == 1 or x == n-1, return true.

// Below loop mainly runs 'r-1' times.


4) Do following while d doesn't become n-1.
n
a) x = (x*x) % n.
b) If (x == 1) return false.
c) If (x == n-1) return true.

Program:
import java.io.*;
import java.math.*;

class GFG {

// Utility function to do modular


// exponentiation. It returns (x^y) % p
static int power(int x, int y, int p) {

int res = 1; // Initialize result


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

//Update x if it is more than or


// equal to p
x = x % p;

while (y > 0) {

// If y is odd, multiply x with result


if ((y & 1) == 1)
res = (res * x) % p;

// y must be even now


y = y >> 1; // y = y/2
x = (x * x) % p;
}

return res;
}

// This function is called for all k trials.


// It returns false if n is composite and
// returns false if n is probably prime.
// d is an odd number such that d*2<sup>r</sup>
// = n-1 for some r >= 1
static boolean miillerTest(int d, int n) {

// Pick a random number in [2..n-2]


// Corner cases make sure that n > 4
int a = 2 + (int)(Math.random() % (n - 4));

// Compute a^d % n
int x = power(a, d, n);

if (x == 1 || x == n - 1)
return true;

// Keep squaring x while one of the


// following doesn't happen
// (i) d does not reach n-1
// (ii) (x^2) % n is not 1
// (iii) (x^2) % n is not n-1
while (d != n - 1) {
x = (x * x) % n;
d *= 2;

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

// 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.
static boolean isPrime(int n, int k) {

// Corner cases
if (n <= 1 || n == 4)
return false;
if (n <= 3)
return true;

// Find r such that n = 2^d * r + 1


// for some r >= 1
int d = n - 1;

while (d % 2 == 0)
d /= 2;

// Iterate given nber of 'k' times


for (int i = 0; i < k; i++)
if (!miillerTest(d, n))
return false;

return true;
}

// Driver program
public static void main(String args[]) {

int k = 4; // Number of iterations

System.out.println("All primes smaller "


+ "than 100: ");

for (int n = 1; n < 100; n++)


if (isPrime(n, k))
System.out.print(n + " ");
}
}
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

EXPERIMENT 5: Program for Euclid Algorithm

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.

Let GCD(x,y) be the GCD of positive integers x and y. If x = y, then obviously

GCD(x,y) = GCD(x,x) = x

Euclid's insight was to observe that, if x > y, then

GCD(x,y) = GCD(x-y,y)

Program:
// Java program to find GCD of two or more numbers

public class GCD {


// Function to return gcd of a and b
static int gcd(int a, int b)
{
if (a == 0)
return b;
return gcd(b % a, a);
}

// Function to find gcd of array of


// numbers
static int findGCD(int arr[], int n)
{
int result = arr[0];
for (int i = 1; i < n; i++)
result = gcd(arr[i], result);

return result;
}

public static void main(String[] args)


{
int arr[] = { 2, 4, 6, 8, 16 };
int n = arr.length;
System.out.println(findGCD(arr, n));
}
}
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

EXPERIMENT 6: Java program for DES algorithm logic

AIM: Write a Java program to implement the DES algorithm logic.

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;

public class DES {

private static final String UNICODE_FORMAT = "UTF8";

public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";

privateKeySpecmyKeySpec;

privateSecretKeyFactorymySecretKeyFactory;

private Cipher cipher;

byte[] keyAsBytes;

private String myEncryptionKey;

private String myEncryptionScheme;

SecretKey key;
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

static BufferedReader br = new BufferedReader(new


InputStreamReader(System.in)); public DES() throws Exception {
// TODO code application logic here myEncryptionKey
= "ThisIsSecretEncryptionKey"; myEncryptionScheme =
DESEDE_ENCRYPTION_SCHEME; keyAsBytes =
myEncryptionKey.getBytes(UNICODE_FORMAT); myKeySpec

= new DESedeKeySpec(keyAsBytes);

mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);

cipher = Cipher.getInstance(myEncryptionScheme);

key = mySecretKeyFactory.generateSecret(myKeySpec);
cretKeyFactory.generateSecret(myKeySpec);

public String encrypt(String unencryptedString)

{ String encryptedString = null;

try {

cipher.init(Cipher.ENCRYPT_MODE, key);

byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);

byte[] encryptedText = cipher.doFinal(plainText);

BASE64Encoder base64encoder = new BASE64Encoder();

encryptedString = base64encoder.encode(encryptedText); }

catch (Exception e) {

e.printStackTrace(); }

returnencryptedString; }

public String decrypt(String encryptedString)

{ 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);

BASE64Decoder base64decoder = new BASE64Decoder();

byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);

byte[] plainText = cipher.doFinal(encryptedText); decryptedText=

bytes2String(plainText); }

catch (Exception e) {

e.printStackTrace(); }

returndecryptedText; }

private static String bytes2String(byte[] bytes)

{ StringBufferstringBuffer = new StringBuffer();


for (int i = 0; i <bytes.length;i++) {
stringBuffer.append((char) bytes[i]); }

returnstringBuffer.toString(); }

public static void main(String args []) throws Exception

{ System.out.print("Enter the string: "); DES


myEncryptor= new DES();
String stringToEncrypt = br.readLine();

String encrypted = myEncryptor.encrypt(stringToEncrypt); String decrypted =


myEncryptor.decrypt(encrypted); System.out.println("\nString To Encrypt: "
+stringToEncrypt); System.out.println("\nEncrypted Value : " +encrypted);
System.out.println("\\nDecrypted
nDecrypted Value : " +decrypted); System.out.println("");
}

OUTPUT:

Enter the string: Welcome


String To Encrypt: Welcome
Encrypted Value : BPQMwc0wKvg=
Decrypted Value : Welcome
PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

EXPERIMENT 7: Program to implement BlowFish algorithm logic

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

PROGRAM:

import java.io.*;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.security.Key;

import javax.crypto.Cipher;

import javax.crypto.CipherOutputStream;

import javax.crypto.KeyGenerator;

import sun.misc.BASE64Encoder;

public class BlowFish {

public static void main(String[] args) throws Exception {

// TODO code application logic here


KeyGeneratorkeyGenerator = KeyGenerator.
KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128); Key secretKey = keyGenerator.generateKey();
Cipher cipherOut = Cipher.getInstance("Blowfish/CFB/NoPadding");

cipherOut.init(Cipher.ENCRYPT_MODE, secretKey); BASE64Encoder

encoder = new BASE64Encoder();

byte iv[] = cipherOut.getIV();

if (iv != null) {

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

FileInputStream fin = new FileInputStream("inputFile.txt");

FileOutputStreamfout = new FileOutputStream("outputFile.txt");

CipherOutputStreamcout = new CipherOutputStream(fout, cipherOut);


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

int input = 0;

while ((input = fin.read()) != -1) {

fin.close(); cout.close(); }}

OUTPUT:

Initialization Vector of the Cipher: dI1MXzW97oQ=

Contents of inputFile.txt: Hello World

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


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

EXPERIMENT 8: Program to implement Rijndael algorithm logic

AIM: Write a C/JAVA program to implement the Rijndael algorithm logic.

PROGRAM:

import java.security.*;

import javax.crypto.*;

import javax.crypto.spec.*;

import java.io.*;

public class AES {

public static String asHex (byte buf[]) { StringBuffer strbuf


= new StringBuffer(buf.length * 2); int i;
for (i = 0; i < buf.length; i++) {

if (((int) buf[i] & 0xff) < 0x10)

strbuf.append("0");

strbuf.append(Long.toString((int) buf[i] & 0xff, 16)); }

return strbuf.toString(); }

public static void main(String[] args) throws Exception {


String message="AES still rocks!!";
// Get the KeyGenerator

KeyGenerator kgen = KeyGenerator.getInstance("AES");


kgen.init(128); // 192 and 256 bits may not be available
// Generate the secret key specs.

SecretKey skey = kgen.generateKey();

byte[] raw = skey.getEncoded();

SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

// Instantiate the cipher

Cipher cipher = Cipher.getInstance("AES");


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

cipher.init(Cipher.ENCRYPT_MODE, skeySpec);

byte[] encrypted = cipher.doFinal((args.length == 0 ? message :


args[0]).getBytes()); System.out.println("encrypted string: " +
asHex(encrypted)); cipher.init(Cipher.DECRYPT_MODE, skeySpec); byte[]
original = cipher.doFinal(encrypted); String originalString = new
String(original);
System.out.println("Original string: " + originalString + " " + asHex(original));
}
}

OUTPUT:
Input your message: Hello KGRCET

Encrypted text: 3ooo&&(*&*4r4

Decrypted text: Hello KGRCET


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

EXPERIMENT 9: Encrypt a string using BlowFish algorithm

AIM: Using Java Cryptography, encrypt the text “Hello world” using BlowFish.

Create your own key using Java keytool.

PROGRAM:

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.swing.JOptionPane;

public class BlowFishCipher {

public static void main(String[] args) throws Exception {

// create a key generator based upon the Blowfish cipher


KeyGeneratorkeygenerator = KeyGenerator.getInstance("Blowfish");
// create a key
// create a cipher based upon Blowfish Cipher
cipher = Cipher.getInstance("Blowfish");
r.getInstance("Blowfish");

// initialise cipher to with secret key


cipher.init(Cipher.ENCRYPT_MODE, secretkey);
// get the text to encrypt
String inputText = JOptionPane.showInputDialog("Input your message:

"); // encrypt message

byte[] encrypted = cipher.doFinal(inputText.getBytes());

// re-initialise the cipher to be in decrypt mode


cipher.init(Cipher.DECRYPT_MODE, secretkey);
// decrypt message
byte[] decrypted = cipher.doFinal(encrypted);

// and display the results


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),

"\nEncrypted text: " + new String(encrypted) + "\n" +

"\nDecrypted
nDecrypted text: " + new String(decrypted));

System.exit(0);

}}

OUTPUT:

Input your message: Hello world

Encrypted text: 3ooo&&(*&*4r4

Decrypted text: Hello world


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

EXPERIMENT 10: RSA Algorithm

AIM: Write a Java program to implement RSA Algoithm.


Theory:

 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;

public class RSA {

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


static void main(String[] args) {
// TODO code application logic here
System.out.print("Enter a Prime number: ");
BigInteger p = sc.nextBigInteger(); // Here's one prime number..
System.out.print("Enter another prime number: "); BigInteger q =
sc.nextBigInteger(); // ..and another. BigInteger n = p.multiply(q);
BigInteger n2 = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));

BigInteger e = generateE(n2);
generateE(n

BigInteger d = e.modInverse(n2); // Here's the multiplicative inverse

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

System.out.println("Decryption keys are: " + d + ", " + n);

public static BigIntegergenerateE(BigIntegerfiofn) {

int y, intGCD;

BigInteger e;

BigInteger gcd;

Random x = new Random();

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

while(y <= 2 || intGCD != 1);

return e;

OUTPUT:

Enter a Prime number: 5

Enter another prime number: 11

Encryption keys are: 33, 55

Decryption keys are: 17, 55


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-19), Bhauti, Kanpur-209305 (U.P.), India

EXPERIMENT 11: Diffie-Hellman

AIM: Implement the Diffie


Diffie-Hellman Key Exchange mechanism using HTML and JavaScript.
Consider the end user as one of the parties (Alice) and the JavaScript application as other
party (bob).
PROGRAM:

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;

public final static int XaValue = 9;

public final static int XbValue = 14;

public static void main(String[] args) throws Exception { //


TODO code application logic here
BigInteger p = new BigInteger(Integer.toString(pValue));

BigInteger g = new BigInteger(Integer.toString(gValue));

BigIntegerXa = new

BigInteger(Integer.toString(XaValue)); BigIntegerXb =

new BigInteger(Integer.toString(XbValue)); createKey();

intbitLength = 512; // 512 bits

SecureRandomrnd = new SecureRandom();

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

public static void createKey() throws Exception {

KeyPairGeneratorkpg = KeyPairGenerator.getInstance("DiffieHellman");
kpg.initialize(512);
KeyPairkp = kpg.generateKeyPair();

KeyFactorykfactory = KeyFactory.getInstance("DiffieHellman");

DHPublicKeySpeckspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),

DHPublicKeySpec.class);

System.out.println("Public key is: " +kspec);

public static void createSpecificKey(BigInteger p, BigInteger g) throws

Exception { KeyPairGeneratorkpg =

KeyPairGenerator.getInstance("DiffieHellman"); DHParameterSpecparam = new

DHParameterSpec(p,
rameterSpec(p, g); kpg.initialize(param);

KeyPairkp = kpg.generateKeyPair();

KeyFactorykfactory = KeyFactory.getInstance("DiffieHellman");

DHPublicKeySpeckspec = (DHPublicKeySpec) kfactory.getKeySpec(kp.getPublic(),

DHPublicKeySpec.class);

System.out.println("\nPublic
nPublic key is : " +kspec);

OUTPUT:

Public key is: javax.crypto.spec.DHPublicKeySpec@5afd29

Public key is: javax.crypto.spec.DHPublicKeySpec@9971ad


PSIT-Pranveer Singh Institute of Technology
Kanpur-Delhi National Highway (NH-2), Bhauti, Kanpur-209305 (U.P.), India

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING KCS751A

You might also like