IS Krishna (4-10)

Download as pdf or txt
Download as pdf or txt
You are on page 1of 34

3170720 INFORMATION SECURITY 210170107518

Experiment No: 4
To implement Simple DES encryption-decryption.
Date:
Relevant CO: Implement and analyze various symmetric key cryptography algorithms
and their application in different context

Objectives: (a) to understand working fundamental of DES Algorithm


(b) to carry out Implementation of DES encryption-decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
DES is a symmetric encryption system that uses 64-bit blocks, 8 bits of which areused
for parity checks. The key therefore has a "useful" length of 56 bits, which means thatonly
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 on64 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:
3170720 INFORMATION SECURITY 210170107518

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:

#include <iostream>

using namespace std;

//Functions
void printArray(int arr[],int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
cout << endl;
}

void Permutation(int arr[], int index[], int n){


int temp[n];
for (int i=0; i<n; i++)
temp[i] = arr[index[i]-1];
for (int i=0; i<n; i++)
arr[i] = temp[i];
}
void ExPermutation(int arr[], int index[], int arr2[], int n){
for (int i=0; i<n; i++)
arr2[i] = arr[index[i]-1];
}

void Split(int arr[], int n, int *l, int *r){


for(int i=0;i<n/2;i++)
l[i] = arr[i];
for(int j=0,i=n/2;i<n;i++,j++)
r[j] = arr[i];
}

int bin2dec(int arr[],int size){


int decimal = 0 ;
for(int i = 0 ; i < size ; i++)
decimal = (decimal << 1) + arr[i] ;
return decimal;
}

void dec2bin(int opSn, int *ar){


int i=0;
while(opSn!=0)
{
ar[i] = opSn%2;
i++;
3170720 INFORMATION SECURITY 210170107518

opSn = opSn/2;
}
}

void combine(int arr1[], int arr2[], int *arr3, int n){


for (int i=0;i<n/2;i++)
arr3[i]=arr1[i];
for (int i=n/2,j=0;i<n;i++,j++)
arr3[i]=arr2[j];
}

void S_box(int a[],int b[],int *opS0S1){


int S0[4][4] = {{1,0,3,2},{3,2,1,0},{0,2,1,3},{3,1,3,2}}, S1[4][4] =
{{0,1,2,3},{2,0,1,3},{3,0,1,0},{2,1,0,3}};
//S0
int rowS0bin[2] = {a[0],a[3]}, colS0bin[2] = {a[1],a[2]};
int rowS0dec = bin2dec(rowS0bin,2), colS0dec = bin2dec(colS0bin,2);
int opS0dec = S0[rowS0dec][colS0dec];
int opS0bin[2]={};
dec2bin(opS0dec, opS0bin);

//S1
int rowS1bin[2] = {b[0],b[3]}, colS1bin[2] = {b[1],b[2]};
int rowS1dec = bin2dec(rowS1bin,2), colS1dec = bin2dec(colS1bin,2);
int opS1dec = S1[rowS1dec][colS1dec];
int opS1bin[2]={};
dec2bin(opS1dec, opS1bin);

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


opS0S1[i]=opS0bin[i];
for (int i=2,j=0;i<4;i++,j++)
opS0S1[i]=opS1bin[j];
cout<<"After S-Box: ";
printArray(opS0S1,4);
cout<<endl;
}

void Swap(int *left_array, int *right_array, int n){


int temp[n];
for (int i=0; i<n; i++)
temp[i] = left_array[i];
for (int i=0; i<n; i++)
left_array[i]= right_array[i];
for (int i=0; i<n; i++)
right_array[i]= temp[i];

void XOR(int arr1[],int arr2[],int n){


int temp[n];
for(int i=0; i<n; i++)
{
temp[i] = arr1[i] ^ arr2[i];
}
for (int i=0; i<n; i++)
arr2[i] = temp[i];
}

void leftRotate(int arr[], int d, int n)


{
int temp[d];
3170720 INFORMATION SECURITY 210170107518

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


temp[i] = arr[i];
for (int i = 0; i < n-d; i++)
arr[i] = arr[i+d];
for (int i=n-d,j=0; i<n; i++,j++)
arr[i]=temp[j];

class KeyGeneration {
private:
int P10_rule[10] = {3,5,2,7,4,10,1,9,8,6};
int P8_rule[8] = {6,3,7,4,8,5,10,9};
int temp_left[5]={}, temp_right[5]={};

public:
KeyGeneration(){
cout<<endl;
cout<<"KEY GENERATION.."<<endl;
cout<<endl;
}
void key(int master_key[], int *k1, int *k2){
//P10
Permutation(master_key,P10_rule,10);
cout<<"After P10 Permutation: ";
printArray(master_key,10);
cout<<endl;
//Split
Split(master_key,10,temp_left,temp_right);
cout<<"After split, "<<endl;
cout<<"l = ";
printArray(temp_left,5);
cout<<"r = " ;
printArray(temp_right,5);
cout<<endl;
//LS-1
leftRotate(temp_left,1,5);
leftRotate(temp_right,1,5);
cout<<"After LeftShift-1, "<<endl;
cout<<"l = ";
printArray(temp_left,5);
cout<<"r = ";
printArray(temp_right,5);
cout<<endl;
//P-8
combine(temp_left,temp_right,master_key,10);
Permutation(master_key,P8_rule,10);
cout<<"After P8, Key-1: ";
for(int i=0;i<8;i++)
k1[i]=master_key[i];
printArray(k1,8);
cout<<endl;
//LS-2
leftRotate(temp_left,2,5);
leftRotate(temp_right,2,5);
cout<<"After LeftShift-2, "<<endl;
cout<<"l = ";
printArray(temp_left,5);
cout<<"r = ";
printArray(temp_right,5);
cout<<endl;
//P-8
3170720 INFORMATION SECURITY 210170107518

combine(temp_left,temp_right,master_key,10);
Permutation(master_key,P8_rule,10);
cout<<"After P8, Key-2: ";
for(int i=0;i<8;i++)
k2[i]=master_key[i];
printArray(k2,8);
}
};

class Roundfunction{
private:
int Expanrule[8] = {4,1,2,3,2,3,4,1};
int P4_rule[4] = {2,4,3,1};
int r_arr2[8]={},a[4]={},b[4]={};
int opS0S1[4]={};

public:
void roundfun(int *k1,int *l_arr, int *r_arr, int *fk1){
ExPermutation(r_arr, Expanrule, r_arr2,8);
cout<<"After EP: ";
printArray(r_arr2,8);
cout<<endl;

//XOR with K1
XOR(k1,r_arr2,8);
cout<<"XOR with key"<<endl;
printArray(r_arr2,8);
cout<<endl;
//Split
Split(r_arr2,8,a,b);
cout<<"After Split"<<endl;
cout<<"l = ";
printArray(a,4);
cout<<"r = ";
printArray(b,4);
cout<<endl;
//Sbox
S_box(a,b,opS0S1);
//P4
Permutation(opS0S1,P4_rule,4);
cout<<"After P4"<<endl;
printArray(opS0S1,4);
cout<<endl;
//XOR with left array
XOR(opS0S1,l_arr,4);
cout<<"XOR with leftarray"<<endl;
printArray(l_arr,4);
cout<<endl;
//combine
combine(l_arr,r_arr,fk1,8);
cout<<"After combine"<<endl;
printArray(fk1,8);
cout<<endl;

}
};

class encrypt : public Roundfunction{


private:
int IP_rule[8] = {2,6,3,1,4,8,5,7};
int IP_inv_rule[8] = {4,1,3,5,7,2,8,6};
int fkk[8]={};
3170720 INFORMATION SECURITY 210170107518

public:
encrypt(){
cout<<endl;
cout<<"ENCRYPTING.."<<endl;
cout<<endl;
}
int l_arr[4]={},r_arr[4]={};

//IP
void enc(int arr[], int *key1, int *key2, int *fk1){

Permutation(arr, IP_rule, 8);


cout<<"After IP: ";
printArray(arr,8);
cout<<endl;
//Split
Split(arr,8, l_arr,r_arr);
cout<<"After split, "<<endl;
cout<<"l = ";
printArray(l_arr,4);
cout<<"r = " ;
printArray(r_arr,4);
cout<<endl;
//fk1
cout<<"Round Function(fk)-1"<<endl;
Roundfunction::roundfun(key1,l_arr,r_arr,fk1);
//Swap
Swap(l_arr,r_arr,4);
cout<<"After Swap"<<endl;
cout<<"l = ";
printArray(l_arr,4);
cout<<"r = " ;
printArray(r_arr,4);
cout<<endl;
//fk2
cout<<"Round Function(fk)-2"<<endl;
Roundfunction::roundfun(key2,l_arr,r_arr,fk1);
//ipinv
Permutation(fk1,IP_inv_rule,8);
cout<<"After IP-Inverse, 8-bit Cipher Text is: "<<endl;
printArray(fk1,8);
}
};

class decrypt : public Roundfunction{


private:
int IP_rule[8] = {2,6,3,1,4,8,5,7};
int IP_inv_rule[8] = {4,1,3,5,7,2,8,6};
int fkk[8]={};

public:
int l_arr[4]={},r_arr[4]={};

//IP
void decryp(int arr[], int *key1, int *key2, int *fk1){

Permutation(arr, IP_rule, 8);


cout<<"IP"<<endl;
printArray(arr,8);
//Split
Split(arr,8, l_arr,r_arr);
3170720 INFORMATION SECURITY 210170107518

cout<<"Split"<<endl;
printArray(l_arr,4);
printArray(r_arr,4);
//fk1
Roundfunction::roundfun(key2,l_arr,r_arr,fk1);
//Swap
Swap(l_arr,r_arr,4);
cout<<"swap"<<endl;
printArray(l_arr,4);
printArray(r_arr,4);
//fk2
Roundfunction::roundfun(key1,l_arr,r_arr,fk1);
//ipinv
Permutation(fk1,IP_inv_rule,8);
cout<<"After IP-Inverse, 8-bit Plain Text is: "<<endl;
printArray(fk1,8);
}
};

int main()
{
char input;
int arr[8]={};
int master_key[10]={};
int k1[8]={},k2[8]={};
int fk1[8] = {};

//Key
cout<<"Enter 10-bit Master Key (using space)"<<endl;
for(int i=0;i<10;i++){
cin>>master_key[i];
}
if((sizeof(master_key)/sizeof(master_key[0]))!=10)
throw "Error. Enter 10-bits";
KeyGeneration k;
k.key(master_key,k1,k2);
cout<<"_____________________________________________________________________________"<<e
ndl;
cout<<endl;
cout<<"Enter e for Encryption | Enter d for Decryption | Enter b for Both"<<endl;
cin>>input;

if (input == 'b'||input == 'B'){


cout<<"Enter 8-bit Plain Text (using space)"<<endl;
for(int i=0;i<8;i++){
cin>>arr[i];
}
if((sizeof(arr)/sizeof(arr[0]))!=8)
throw "Error. Enter 8-bits";
encrypt e;
e.enc(arr,k1,k2,fk1);
for(int i=0;i<8;i++)
arr[i] = fk1[i];
cout<<"_____________________________________________________________________________"<
<endl;
decrypt d;
d.decryp(arr,k1,k2,fk1);
}
else if (input == 'e'||input == 'E'){
cout<<"Enter 8-bit Plain Text (using space)"<<endl;
for(int i=0;i<8;i++){
cin>>arr[i];
3170720 INFORMATION SECURITY 210170107518

}
if((sizeof(arr)/sizeof(arr[0]))!=8)
throw "Error. Enter 8-bits";
encrypt e;
e.enc(arr,k1,k2,fk1);
}
else if (input == 'd'||input == 'D'){
cout<<"Enter 8-bit Cipher Text (using space)"<<endl;
for(int i=0;i<8;i++){
cin>>arr[i];
}
if((sizeof(arr)/sizeof(arr[0]))!=8)
throw "Error. Enter 8-bits";
decrypt d;
d.decryp(arr,k1,k2,fk1);
}
else
throw "Error, Choose correct option";

return 0;
}

Output:
3170720 INFORMATION SECURITY 210170107518

Conclusion:
The provided program is intended to demonstrate Simplified DES (S-DES) encryption and decryption in C++.
However, the program contained errors in its initial implementation, and after correction, it successfully
encrypts and decrypts 8-bit plaintext with a 10-bit key using the S-DES algorithm, providing the expected
ciphertext and plaintext results.

Quiz:
1. DES works on 64-bits size of blocks ?

2. How many steps DES consists?


DES consists of 16 steps, which include permutation, substitution, and key generation rounds to encrypt
and decrypt the data.

Suggested Reference:
1. https://www.tutorialspoint.com/cryptography/data_encryption_standard.htm
References used by the students:
https://www.geeksforgeeks.org/simplified-data-encryption-standard-key-generation/

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks
3170720 INFORMATION SECURITY 210170107518

Experiment No: 5
To implement Simple AES encryption-decryption.
Date:
Relevant CO: Implement and analyze various symmetric key cryptography algorithms
and their application in different context

Objectives: (a) to understand working fundamental of AES Algorithm


(b) to carry out Implementation of AES encryption-decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
AES is a symmetric encryption system that uses 128 bit blocks, The key length is
128/192/256. 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 main parts of the algorithm are as follows:
• AES is a block cipher.
• The key size can be 128/192/256 bits.
• Encrypts data in blocks of 128 bits each
.

Example:

Algorithm:

STEP-1:Derive the set of round keys from the cipher key.


3170720 INFORMATION SECURITY 210170107518

STEP-2:Initialize the state array with the block data (plaintext).


STEP-3:Add the initial round key to the starting state array.
STEP-4:Perform nine rounds of state manipulation.
STEP-5:Perform the tenth and final round of state manipulation.
STEP-6:Copy the final state array out as the encrypted data (ciphertext).

Program:

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Scanner;

public class Experiment5 {


public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);

boolean exit = false;

while (!exit) {
System.out.println("\n=== Enhanced AES Encryption and Decryption ===");
System.out.println("1. Encrypt");
System.out.println("2. Decrypt");
System.out.println("3. Exit");
System.out.print("Enter your choice (1/2/3): ");
int choice = scanner.nextInt();
scanner.nextLine(); // Consume the newline

switch (choice) {
case 1:
System.out.print("Enter a 16-byte encryption key (e.g., 16 characters): ");
String keyString = scanner.nextLine();
SecretKey secretKey = new SecretKeySpec(keyString.getBytes(StandardCharsets.UTF_8), "AES");

System.out.print("Enter plaintext: ");


String plaintext = scanner.nextLine();
String ciphertext = encrypt(plaintext, secretKey);
System.out.println("\n=== Ciphertext ===");
System.out.println(ciphertext);
break;

case 2:
System.out.print("Enter a 16-byte encryption key (e.g., 16 characters): ");
keyString = scanner.nextLine();
secretKey = new SecretKeySpec(keyString.getBytes(StandardCharsets.UTF_8), "AES");

System.out.print("Enter ciphertext: ");


String cipherText = scanner.nextLine();
String decryptedText = decrypt(cipherText, secretKey);
System.out.println("\n=== Decrypted Plaintext ===");
System.out.println(decryptedText);
break;

case 3:
exit = true;
3170720 INFORMATION SECURITY 210170107518

System.out.println("Exiting the program. Goodbye!");


break;

default:
System.out.println("Invalid choice. Please enter 1, 2, or 3.");
break;
}
}
}

public static String encrypt(String plaintext, SecretKey secretKey) throws Exception {


Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
return Base64.getEncoder().encodeToString(encryptedBytes);
}

public static String decrypt(String ciphertext, SecretKey secretKey) throws Exception {


Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(ciphertext));
return new String(decryptedBytes, StandardCharsets.UTF_8);
}
}

Output:
3170720 INFORMATION SECURITY 210170107518

Conclusion:
The provided Java program offers a simple demonstration of AES encryption and decryption using a fixed 128-
bit key and block size. It allows users to choose between encryption and decryption, providing a basic example
of these operations while emphasizing the importance of using the correct key for decryption to avoid
"BadPaddingException" errors.

Quiz:

1. How many rounds does the AES-192 perform?


The AES-192 encryption algorithm performs a total of 12 rounds. Each round consists of various operations,
including substitution, permutation, and key mixing, as defined in the AES algorithm specification.

Suggested Reference:
1. https://www.geeksforgeeks.org/advanced-encryption-standard-aes/

References used by the students:

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks
3170720 INFORMATION SECURITY 210170107518

Experiment No: 6
To implement Simple RSA encryption-decryption.
Date:
Relevant CO: Compare public key cryptography with private key cryptography and
Implement various asymmetric key cryptography algorithms

Objectives: (a) to understand working fundamental of RSA Algorithm


(b) to carry out Implementation of RSA encryption-decryption.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
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 toeveryone. A
basic principle behind RSA is the observation that it is practical to find threevery large positive
integers e, d and n such that with modular exponentiation for all integer m:

(me)d = m (mod n)

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

Example:
3170720 INFORMATION SECURITY 210170107518

Algorithm:

STEP-1: Select two co-prime numbers as p and q.


STEP-2: Compute n as the product of p and q.
STEP-3: Compute (p-1)*(q-1) and store it in z.
STEP-4: Select a random prime number e that is less than that of z.
STEP-5: Compute the private key, d as e * mod-1(z).
STEP-6: The cipher text is computed as messagee * mod n.STEP-7: Decryption is done as
cipherdmod n.

Program:

import java.math.BigInteger;
import java.util.Scanner;

public class Experiment6 {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.println("***** RSA Encryption and Decryption *****");

while (true) {
System.out.println("1. Encrypt");
System.out.println("2. Decrypt");
System.out.println("3. Exit");
System.out.print("Enter your choice (1/2/3): ");
int choice = scanner.nextInt();

if (choice == 3) {
System.out.println("Exiting the program. Farewell!");
break;
}

switch (choice) {
case 1:
performEncryption(scanner);
break;

case 2:
performDecryption(scanner);
break;

default:
System.out.println("Invalid choice. Please try again.");
}
}
}

private static void performEncryption(Scanner scanner) {


System.out.print("Enter plaintext (as an integer): ");
BigInteger plaintext = new BigInteger(scanner.next());
System.out.print("Enter the recipient's public key (e, n): ");
BigInteger publicKeyE = new BigInteger(scanner.next());
BigInteger publicKeyN = new BigInteger(scanner.next());
BigInteger ciphertext = encrypt(plaintext, publicKeyE, publicKeyN);
3170720 INFORMATION SECURITY 210170107518

System.out.println("Encrypted Message: " + ciphertext);


System.out.println("************************************************");
}

private static void performDecryption(Scanner scanner) {


System.out.print("Enter ciphertext (as an integer): ");
BigInteger ciphertextToDecrypt = new BigInteger(scanner.next());
System.out.print("Enter your private key (d, n): ");
BigInteger privateKeyD = new BigInteger(scanner.next());
BigInteger privateKeyN = new BigInteger(scanner.next());
BigInteger decryptedMessage = decrypt(ciphertextToDecrypt, privateKeyD, privateKeyN);
System.out.println("Decrypted Message: " + decryptedMessage);
System.out.println("************************************************");
}

public static BigInteger encrypt(BigInteger plaintext, BigInteger publicKeyE, BigInteger publicKeyN) {


return plaintext.modPow(publicKeyE, publicKeyN);
}

public static BigInteger decrypt(BigInteger ciphertext, BigInteger privateKeyD, BigInteger privateKeyN) {


return ciphertext.modPow(privateKeyD, privateKeyN);
}
}

Output:

Conclusion:
The provided Java program demonstrates a simplified version of RSA encryption and decryption using small
values for educational purposes. Users can choose between encryption and decryption, entering plaintext,
ciphertext, and key values. In a real-world context, RSA encryption involves large prime numbers and security
considerations, which are not addressed in this simplified example.
3170720 INFORMATION SECURITY 210170107518

Quiz:

1. if p=7, q=1 and e=13 than what will be value of d?


In RSA encryption, if p = 7, q = 1, and e = 13, then it is not possible to calculate the value of d because it
violates the requirement that p and q must be distinct prime numbers. For RSA encryption to work securely,
p and q should be different prime numbers, and the values of e and d should be computed based on those
prime numbers.

Suggested Reference:
1. https://www.cemc.uwaterloo.ca/resources/real-world/RSA.pdf

References used by the students:

https://cppsecrets.com/users/1004910997104971161111071171109710849496410310997105108469
9111109/C00-RSA-Cryptography-Algorithm-Implementation.php

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks
3170720 INFORMATION SECURITY 210170107518

Experiment No: 7
Implement the Diffi-Hellman Key Exchange Method.
Date:
Relevant CO: Compare public key cryptography with private key cryptography and
Implement various asymmetric key cryptography algorithms

Objectives: (a) to understand working fundamental of Diffie–Hellman Key Exchange


(b) to carry out Implementation of Diffie–Hellman Key Exchange algorithm.

Equipment/Instruments: Computer System, Turbo-c/ JDK


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

Algorithm:

STEP-1: Both Alice and Bob shares the same public keys g and p.
STEP-2: Alice selects a random public key a.
STEP-3: Alice computes his secret key A as ga mod p.
STEP-4: Then Alice sends A to Bob.
STEP-5: Similarly Bob also selects a public key b and computes his secret key as Band
sends the same back to Alice.
STEP-6: Now both of them compute their common secret key as the other one’s secretkey
power of a mod p.
3170720 INFORMATION SECURITY 210170107518

Program:
import java.util.Scanner;
import java.math.BigInteger;

public class Experiment7 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

boolean exit = false;

while (!exit) {
System.out.println("== Diffie-Hellman Key Exchange ==");
System.out.println("1. Generate Public Key");
System.out.println("2. Compute Shared Secret Key");
System.out.println("3. Exit");
System.out.print("Enter your choice (1/2/3): ");

int choice = scanner.nextInt();

switch (choice) {
case 1:
generatePublicKey(scanner);
break;

case 2:
computeSharedSecret(scanner);
break;

case 3:
exit = true;
System.out.println("Exiting...");
break;

default:
System.out.println("Invalid choice. Please enter 1, 2, or 3.");
}
}
}

public static void generatePublicKey(Scanner scanner) {


System.out.print("Enter a prime number (p): ");
BigInteger p = new BigInteger(scanner.next());
System.out.print("Enter a primitive root of p (g): ");
BigInteger g = new BigInteger(scanner.next());
System.out.print("Enter your private key (a): ");
BigInteger a = new BigInteger(scanner.next());
BigInteger publicKeyA = generatePublicKey(p, g, a);
System.out.println("Your public key (A): " + publicKeyA);
System.out.println("== Public Key Generation Complete ==");
}

public static void computeSharedSecret(Scanner scanner) {


System.out.print("Enter the received public key (B): ");
BigInteger publicKeyB = new BigInteger(scanner.next());
System.out.print("Enter your private key (a): ");
BigInteger privateA = new BigInteger(scanner.next());
System.out.print("Enter the prime modulus (p): ");
BigInteger p = new BigInteger(scanner.next());
BigInteger sharedSecret = computeSharedSecret(publicKeyB, privateA, p);
3170720 INFORMATION SECURITY 210170107518

System.out.println("== Shared Secret Computation Complete ==");


System.out.println("Shared secret key: " + sharedSecret);
}

public static BigInteger generatePublicKey(BigInteger p, BigInteger g, BigInteger a) {


return g.modPow(a, p);
}

public static BigInteger computeSharedSecret(BigInteger publicKeyB, BigInteger privateA, BigInteger p) {


return publicKeyB.modPow(privateA, p);
}
}

Output:

Conclusion:
The provided Java program demonstrates a simplified version of the Diffie-Hellman key exchange method.
Users can choose to generate public keys or compute a shared secret key. Proper initialization of variables is
crucial, and in real-world applications, larger prime numbers and security considerations would be necessary.

Quiz:

1. Suppose that two parties A and B wish to set up a common secret key (D-H key) between
3170720 INFORMATION SECURITY 210170107518

themselves using the Diffie Hellman key exchange technique. They agree on 7 as the modulus
and 3 as the primitive root. Party A chooses 2 and party B chooses 5 as their respective secrets.
Their D-H key is ?
If Party A chooses 2 and Party B chooses 5 as their respective secret values, and they are using a modulus
of 7 and a primitive root of 3 in the Diffie-Hellman key exchange, their shared secret key can be computed
as follows: Party A computes: 25 mod 7 = 32 mod 7 = 4 Party B computes: 52 mod 7 = 25 mod 7 = 4 Both
parties will have the shared secret key of 4.

Suggested Reference:
1. https://www.techtarget.com/searchsecurity/definition/Diffie-Hellman-key-exchange

References used by the students:


https://www.javatpoint.com/diffie-hellmam-algorithm-in-cpp

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks
3170720 INFORMATION SECURITY 210170107518

Experiment No: 8
Write a program to generate MD5 hash.

Date:
Relevant CO: Explore the concept of hashing and implement various hashing
algorithms for message integrity

Objectives: (a) to understand working fundamental of MD5


(b) to carry out Implementation of MD5 techniques.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
MD5 processes a varia ble-length message into a fixed-length output of 128 bits. The
input message is broken up into chunks of 512-bit blocks. The message is pa dded so that its
e
length is divisible by 512. The padding works as follows: first a single bit, 1, is appended to
the end of the message. This is followed by as many zeros as are required to bring the lengthof
the message up to 64 bits less than a multiple of 512. The remaining bits are filled up with 64
bits representing the length of the original message, modulo 264.The main operates on a 128-
bit state, divided into four 32-bit words, denoted A, B, C, and D. These areinitialized to certain
fixed constants. The main algorithm then uses each 512-bit message block in turn to modify
the stat ..

Example:
3170720 INFORMATION SECURITY 210170107518

Algorithm:

STEP-1: Read the 128-bit plain text.


STEP-2: Divide into four blocks of 32-bits named as A, B, C and D.

STEP-3: Compute the functions f, g, h and i with operations such as, rotations,
permutations, etc,.
STEP-4: The output of these functions are combined together as F and performed
circular shifting and then given to key round.

STEP-5: Finally, right shift of ‘s’ times are performed and the results are combinedtogether to
produce the final output.

Program:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

public class Experiment8 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("=== MD5 Hash Generator ===");


System.out.print("Enter a string to generate a unique MD5 hash: ");
String input = scanner.nextLine();

String md5Hash = generateUniqueMD5Hash(input);

System.out.println("\n*** Unique MD5 Hash ***");


System.out.println(md5Hash);
}

public static String generateUniqueMD5Hash(String input) {


try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());

// Convert the byte array to a unique and stylized hexadecimal string


StringBuilder uniqueHexString = new StringBuilder();
for (int i = 0; i < messageDigest.length; i++) {
uniqueHexString.append(String.format("%02X", (messageDigest[i] & 0xFF) ^ (i * 10)));
}

return uniqueHexString.toString();
} catch (NoSuchAlgorithmException e) {
// Handle the exception appropriately (e.g., log or print an error message)
e.printStackTrace();
return null;
}
}
}
3170720 INFORMATION SECURITY 210170107518

Output:

Conclusion:
The Java program provided allows for user interaction to generate MD5 hashes of input strings. It utilizes the
`MessageDigest` class to compute the MD5 hash and then presents the hash as a hexadecimal string. This
program can be useful for generating MD5 hashes for various purposes, such as verifying the integrity of data
or storing hashed passwords securely.

Quiz:

1. MD5 produce hash value of 128 bits?

Suggested Reference:
1. https://www.simplilearn.com/tutorials/cyber-security-tutorial/md5-algorithm

References used by the students:


https://www.baeldung.com/java-md5

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks
3170720 INFORMATION SECURITY 210170107518

Experiment No: 9
Write a program to generate SHA-1 hash.
Date:
Relevant CO: Explore the concept of hashing and implement various hashing
algorithms for message integrity

Objectives: (a) to understand working fundamental of SHA-1


(b) to carry out Implementation of SHA-1.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
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 practicallyinfeasible 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.
STEP-4: The resultant value is permuted with block E.
3170720 INFORMATION SECURITY 210170107518

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:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

public class Experiment9 {

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

System.out.println("===== SHA-1 Hash Generator =====");


System.out.print("Enter a string to generate a unique SHA-1 hash: ");
String input = scanner.nextLine();

String sha1Hash = generateSHA1Hash(input);

System.out.println("\n>>> Unique SHA-1 Hash <<<");


System.out.println("[" + sha1Hash + "]");
}

public static String generateSHA1Hash(String input) {


try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] messageDigest = md.digest(input.getBytes());

// Convert the byte array to a hexadecimal string


StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
hexString.append(String.format("%02x", b));
}

return hexString.toString();
} catch (NoSuchAlgorithmException e) {
// Handle the exception appropriately (e.g., log or print an error message)
e.printStackTrace();
return null;
}
}
}

Output:
3170720 INFORMATION SECURITY 210170107518

Conclusion:
The Java program provided enables user interaction to generate SHA-1 hashes for input strings. It employs the
`MessageDigest` class to compute the SHA-1 hash and displays the hash as a hexadecimal string. This program
can be useful for various security and data integrity applications.

Quiz:

1. What is the number of round computation steps in the SHA-256 algorithm?


The SHA-256 algorithm involves 64 rounds of computation steps.

2. SHA-1 produces a hash value of 160 bits ?

Suggested Reference:
1. https://www.geeksforgeeks.org/sha-1-hash-in-java/.

References used by the students:


https://justcryptography.com/sha-1/

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks
3170720 INFORMATION SECURITY 210170107518

Experiment No: 10
Implement a digital signature algorithm.

Date:
Relevant CO: Explore and use the techniques and standards of digital signature, key
management and authentication

Objectives: (a) to understand working fundamental of digital signature standard


(b) to carry out Implementation of digital signature standard.

Equipment/Instruments: Computer System, Turbo-c/ JDK


Theory:
Digital Signature Standard (DSS) is a Federal Information Processing Standard(FIPS) which defines
algorithms that are used to generate digital signatures with the help of Secure Hash Algorithm(SHA)
for the authentication of electronic documents. DSS only provides us with the digital signature function
and not with any encryption or key exchanging stretegy.

Example:

Algorithm:

STEP-1: Key Generation.


STEP-2: Signature Generation.
STEP-3: Key Distribution.
STEP-4: Signature Verification.
3170720 INFORMATION SECURITY 210170107518

Program:
import java.security.*;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.util.Base64;
import java.util.Scanner;

public class Experiment10 {

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


Scanner scanner = new Scanner(System.in);

System.out.println("=== Enhanced Digital Signature ===");


System.out.print("Enter a message to sign: ");
String message = scanner.nextLine();

// Generate key pair


KeyPair keyPair = generateKeyPair();

// Sign the message


byte[] signature = signMessage(message, keyPair.getPrivate());

System.out.println("\n*** Message Signature ***");


System.out.println(Base64.getEncoder().encodeToString(signature));

// Verify the signature


boolean isVerified = verifySignature(message, signature, keyPair.getPublic());
if (isVerified) {
System.out.println("\nSignature Verified: Message Authentic");
} else {
System.out.println("\nSignature Not Verified: Message May be Altered");
}
}

public static KeyPair generateKeyPair() throws Exception {


KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048); // Key size (adjust as needed)
return keyPairGenerator.generateKeyPair();
}

public static byte[] signMessage(String message, PrivateKey privateKey) throws Exception {


Signature signature = Signature.getInstance("SHA256withRSA");
signature.initSign(privateKey);
signature.update(message.getBytes());
return signature.sign();
}

public static boolean verifySignature(String message, byte[] signature, PublicKey publicKey) throws
Exception {
Signature verifySignature = Signature.getInstance("SHA256withRSA");
verifySignature.initVerify(publicKey);
verifySignature.update(message.getBytes());
return verifySignature.verify(signature);
}
}
3170720 INFORMATION SECURITY 210170107518

Output:

Conclusion:
The Java program provides a basic demonstration of digital signature generation and verification using RSA
with SHA-256. It allows users to input a message, sign it, and then verify the signature's authenticity. In a real-
world application, secure key management and additional security measures would be necessary.

Quiz:

1. How many sub-algorithms does digital signature consist of?


A digital signature typically consists of two main sub-algorithms:
1. Signing Algorithm: This sub-algorithm uses the signer's private key to generate a digital
signature from the message or data.
2. Verification Algorithm: This sub-algorithm uses the corresponding public key to verify the
authenticity and integrity of the digital signature.

These two sub-algorithms work together to ensure the security and trustworthiness of digital
signatures

Suggested Reference:
1. https://www.geeksforgeeks.org/digital-signature-standard-dss/

References used by the students:


https://www.includehelp.com/cryptography/digital-signature-algorithm-dsa.aspx

Rubric wise marks obtained:

Rubrics 1 2 3 4 5 Total
Marks
3170720 INFORMATION SECURITY 210170107518

Tools and Case Studies

1. Study Cryptography and cryptanalysis concepts using CrypTool.


Date:

Objectives: (a) to understand the working fundamentals of CrypTool

Equipment/Instruments: Computer System, CrypTool.

Introduction:

The CrypTool installation is simple: download and extract the zip archive, launch the main
program and get started.

Demonstration of Caesar Encryption using CrypTool


In this CrypTool demonstration, we will use Caesar, one of the oldest encryption algorithms.

Encryption
1. Open the Cryptool UI and the document that needs to be encrypted.

2. Click Encrypt/Decrypt > Symmetric (classic) > Caesar


3170720 INFORMATION SECURITY 210170107518

3. Select Caesar mode and the “alphabet character” is “N.” That means that the text will have
characters replaced starting with N. So A >N, B>M, and so on. Click on “encrypt.”

4. The document is encrypted as per the configured policy. This is a very basic example of how
symmetric encryption works.
3170720 INFORMATION SECURITY 210170107518

Decryption process

Perform the following steps to decrypt the encrypted document.

1. Open the encrypted document, and click on “Encrypt.Decrypt” >Symmetric >Caesar.


2. Enter “N” as the alphabet character. This is the shared secret that both parties must know in
order to encrypt and decrypt.
3. Click on decrypt.

Conclusion:
In this study, we explored the fundamental concepts of cryptography and cryptanalysis using CrypTool. We
learned how to use the CrypTool software to perform encryption and decryption, with a specific demonstration
of the Caesar encryption algorithm. This hands-on experience provided insights into the basics of symmetric
3170720 INFORMATION SECURITY 210170107518

encryption and decryption, emphasizing the importance of a shared secret (the alphabet character 'N') for secure
communication. Overall, the exercise helped to gain a practical understanding of cryptographic techniques and
tools.

Suggested Reference:
1. https://www.c-sharpcorner.com/article/encryption-decryption-using-cryptool/

References used by the students:


https://www.c-sharpcorner.com/article/encryption-decryption-using-cryptoo/

You might also like