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

CNS_LAB_R20

The document outlines a series of experiments for a Cryptography and Network Security lab at BVC College of Engineering, focusing on various encryption algorithms and techniques using C and Java. It includes tasks such as implementing XOR and AND operations on strings, as well as encryption methods like Caesar Cipher, Substitution Cipher, Hill Cipher, DES, BlowFish, Rijndael, RSA, and Diffie-Hellman Key Exchange. Each experiment provides a description, source code, and expected output for the students to follow.

Uploaded by

226m1a0534
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)
6 views

CNS_LAB_R20

The document outlines a series of experiments for a Cryptography and Network Security lab at BVC College of Engineering, focusing on various encryption algorithms and techniques using C and Java. It includes tasks such as implementing XOR and AND operations on strings, as well as encryption methods like Caesar Cipher, Substitution Cipher, Hill Cipher, DES, BlowFish, Rijndael, RSA, and Diffie-Hellman Key Exchange. Each experiment provides a description, source code, and expected output for the students to follow.

Uploaded by

226m1a0534
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/ 33

BVC COLLEGE OF ENGINEERING

CRYPTOGRAPHY NETWORK SECURITY LAB (R20)


DEPARTMENT OF CSE
List of Experiments:
1. 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.
2. Write a C program that contains a string (char pointer) with a value
"Hello World". The program should AND or XOR each character in this
string with 127 and display the result.
3. Write a Java program to perform encryption and decryption using the
following algorithms:
a) Caesar Cipher
b) Substitution Cipher
c) Hill Cipher
4. Write a Java program to implement the DES algorithm logic.
5. Write a C/Java program to implement the BlowFish algorithm logic.
6. Write a C/Java program to implement the Rijndael algorithm logic.
7. Using Java Cryptography, encrypt the text “Hello world” using
BlowFish. Create your own key using Java key tool.
8. Write a Java program to implement RSA Algorithm.
9. Implement the Diffie-Hellman Key Exchange mechanism using HTML
and JavaScript. Consider the end user as one of the parties (Alice) and the
JavaScript application as the other party (Bob).
10. Calculate the message digest of a text using the SHA-1 algorithm in
Java.

BVCR, Rajahmundry

1
EXPERIMENT – 1
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 displays the
result.
DESCRIPTION:
When a string is XOR with ‘0’, an output will be the same string as the input
string. This is because XOR any value with ‘0’ reserve in the original value. The reason
for this is that the ‘XOR’ operation. Compare the bit of two values and if set the output
bit to ‘1’.
SOURCE CODE:

#include <stdio.h>
#include <string.h>
void 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

BVCR, Rajahmundry

2
EXPERIMENT – 2
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
DESCRIPTION:
XORing a string with 127 with flipping the 7th bit of each character in the string.
This is because 127 in binary is 0111111 and XORing any value with this binary pattern
will invest the 7th bit. Converting the resultant code back to a character.
SOURCE CODE:

#include <stdio.h>
#include <string.h>
void main() {
char str[] = "Hello World";
char and_result[12]; // Array to store AND results
char xor_result[12]; // Array to store XOR results
int i, len;
len = strlen(str);
// AND each character with 127 and print the result
for (i = 0; i < len; i++) {
and_result[i] = str[i] & 127;
}
and_result[len] = '\0'; // Null-terminate the string
printf("Final AND Result: %s\n", and_result);

// XOR each character with 127 and print the result


for (i = 0; i < len; i++) {
xor_result[i] = str[i] ^ 127;
}
xor_result[len] = '\0'; // Null-terminate the string
printf("Final XOR Result: %s\n", xor_result);
}

OUTPUT:
Final AND Result: Hello World
Final XOR Result: 7 -(

BVCR, Rajahmundry

3
EXPERIMENT – 3

AIM: Write a Java program to perform encryption and decryption using the following
algorithms: a) Ceaser Cipher b) Substitution Cipher c) Hill Cipher

*a) Ceaser Cipher

DESCRIPTION:
The Ceaser Cipher is one of the simplest and oldest encryption techniques. It is
a type of substitution cipher where each letter in the plaintext is replaced by a letter
some fixed number of positions down or up the alphabet. It is a symmetric cipher,
meaning the same key is used for both encryption and decryption.

SOURCE CODE:

import java.util.Scanner;

public class CaesarCipher {

// Function to encrypt the plaintext using Caesar Cipher


public static String encrypt(String plaintext, int shift) {
StringBuilder encryptedText = new StringBuilder();

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


char ch = plaintext.charAt(i);

// Encrypt uppercase letters


if (ch >= 'A' && ch <= 'Z') {
ch = (char) (((ch - 'A' + shift) % 26) + 'A');
}
// Encrypt lowercase letters
else if (ch >= 'a' && ch <= 'z') {
ch = (char) (((ch - 'a' + shift) % 26) + 'a');
}

encryptedText.append(ch);
}
return encryptedText.toString();
}

// Function to decrypt the ciphertext using Caesar Cipher


public static String decrypt(String ciphertext, int shift) {
BVCR, Rajahmundry

4
StringBuilder decryptedText = new StringBuilder();

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


char ch = ciphertext.charAt(i);

// Decrypt uppercase letters


if (ch >= 'A' && ch <= 'Z') {
ch = (char) (((ch - 'A' - shift + 26) % 26) + 'A');
}
// Decrypt lowercase letters
else if (ch >= 'a' && ch <= 'z') {
ch = (char) (((ch - 'a' - shift + 26) % 26) + 'a');
}

decryptedText.append(ch);
}
return decryptedText.toString();
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);

// Input the text and shift value from the user


System.out.print("Enter the text: ");
String text = scanner.nextLine();

System.out.print("Enter shift value: ");


int shift = scanner.nextInt();

// Encrypt the plaintext


String encryptedText = encrypt(text, shift);
System.out.println("Encrypted Text: " + encryptedText);

// Decrypt the ciphertext


String decryptedText = decrypt(encryptedText, shift);
System.out.println("Decrypted Text: " + decryptedText);

scanner.close();
}
}

BVCR, Rajahmundry

5
OUTPUT:
Enter the text: Engineering
Enter shift value: 3
Encrypted Text: Hqjlqhhulqj
Decrypted Text: Engineering

BVCR, Rajahmundry

6
*b) Substitution Cipher

DESCRIPTION:
A classical encryption method in CNS involves replacing each letter in the
plaintext with another letter or symbol to produce the ciphertext.
Apply the same substitution rule used during encryption.
It is a symmetric encryption, where same key is used for both encryption and
decryption.

SOURCE CODE:
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 {


// Original and reversed alphabets
String a = "abcdefghijklmnopqrstuvwxyz";
String b = "zyxwvutsrqponmlkjihgfedcba";

// Read input from user


System.out.print("Enter any string: ");
String str = br.readLine().toLowerCase(); // Convert input to
lowercase

String encrypt = "";


char c;

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


c = str.charAt(i);
int j = a.indexOf(c);
if (j != -1) { // If character is in the alphabet
encrypt = encrypt + b.charAt(j);
} else { // If character is not in the alphabet, leave it
unchanged
encrypt = encrypt + c;
}

BVCR, Rajahmundry

7
}

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


}
}
OUTPUT:
Enter any string: aceho
The encrypted data is: zxvsl

BVCR, Rajahmundry

8
*c) Hill Cipher

DESCRIPTION:
The Hill Cipher is a polygraphic substitution cipher. It was developed by Lesters
Hill in 1929. It uses linear algebraic techniques, especially matrix multiplication, to
transform plaintext into ciphertext. By using an invertible matrix as the key, each block
of plaintext letters is represented as a vector, and then multiplied by the key matrix to
produce the ciphertext vector. Decryption involves using the ciphertext vector.
Decryption involves using the inverse of the key matrix to revert the
Ciphertext back to plaintext.

SOURCE CODE:

import java.io.*;
import java.util.*;

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];
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
static Scanner sc = new Scanner(System.in);

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


getkeymes();
for (int i = 0; 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 string is : ");
for (int i = 0; i < 3; i++) {
System.out.print((char) (res[i][0] % 26 + 97));
res[i][0] = res[i][0];
}
inverse();
for (int i = 0; i < 3; i++) {
BVCR, Rajahmundry

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

public static void inverse() {


float p, q;
float[][] c = a;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (i == j) {
b[i][j] = 1;
} else {
b[i][j] = 0;
}
}
}

BVCR, Rajahmundry

10
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];
b[i][j] = b[i][j] * q - 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("\nInverse Matrix is : ");
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 3x3 matrix for key (It should be inversible):


13 64 09
19 02 55
98 45 34

Enter a 3 letter string: Hai

Encrypted string is : NXM


Inverse Matrix is :
-0.008650308 -0.006364644 0.012585533
0.017049048 -0.0015812776 -0.0019550342
0.0023683228 0.020438014 -0.0042766375

Decrypted string is : Hai

BVCR, Rajahmundry

11
EXPERIMENT – 4

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

DESCRIPTION:

The Data Encryption Standard (DES) is a symmetric – key block cipher that
was widely used for data encryption. Developed by IBM and adopted as a standard by
the U.S government in 1977, DES operates on 64 – bit blocks of data using a 56 – bit
key.

• Block Size: 64 bits


• Key Size: 56 bits
• Involves 16 rounds of permutations and substitutions.
• The same key is used for both encryption and decryption.

SOURCE CODE:

import java.util.*;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import java.util.Base64;

public class DES {


private static final String UNICODE_FORMAT = "UTF8";
public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
private KeySpec myKeySpec;
private SecretKeyFactory mySecretKeyFactory;
private Cipher cipher;
byte[] keyAsBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
SecretKey key;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));

BVCR, Rajahmundry

12
public DES() throws Exception {
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);
}

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);
encryptedString =
Base64.getEncoder().encodeToString(encryptedText);
} catch (Exception e) {
e.printStackTrace();
}
return encryptedString;
}

public String decrypt(String encryptedString) {


String decryptedText = null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] encryptedText =
Base64.getDecoder().decode(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText = bytes2String(plainText);
} catch (Exception e) {
e.printStackTrace();
}

BVCR, Rajahmundry

13
return decryptedText;
}

private static String bytes2String(byte[] bytes) {


StringBuffer stringBuffer = new StringBuffer();
for (int i = 0; i < bytes.length; i++) {
stringBuffer.append((char) bytes[i]);
}
return stringBuffer.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 Value : " + decrypted);
System.out.println("");
}
}

OUTPUT:

Enter the string: Engineering

String To Encrypt: Engineering

Encrypted Value: U81qif6xRmgGnvQCDZvwSA= =

Decrypted Value: Engineering

BVCR, Rajahmundry

14
EXPERIMENT – 5

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

DESCRIPTION:

Blowfish is a symmetric-key block cipher designed by Bruce Schneier in 1993.


It is known for its simplicity, efficiency, and security. Blowfish is commonly used for
secure data encryption and has been widely adopted in various applications, including
file encryption and secure communication protocols.

• Symmetric Key: Same key for encryption and decryption.


• Block Cipher: Encrypts data in 64-bit blocks.
• Flexible Key Length: Supports keys from 32 to 448 bits.
• Fast & Efficient: Suitable for systems with limited processing power.
• Simple Design: Easy to understand and implement.
• Feistel Network: Divides data into two halves for strong security.
• Widely Used: Common in password hashing, file encryption, etc.
• Security: Secure but 64-bit block size is less ideal for modern applications. AES
is recommended for higher security needs.

SOURCE CODE:

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 java.util.Base64;

public class BlowFish {


public static void main(String[] args) throws Exception {
// Generate a key for the Blowfish cipher
KeyGenerator keyGenerator =
KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128);
Key secretKey = keyGenerator.generateKey();

// Initialize the cipher for encryption


Cipher cipherOut =
Cipher.getInstance("Blowfish/CFB/NoPadding");

BVCR, Rajahmundry

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

// Encode the initialization vector (IV) using Base64


Base64.Encoder encoder = Base64.getEncoder();
byte[] iv = cipherOut.getIV();
if (iv != null) {
System.out.println("Initialization Vector of the Cipher: " +
encoder.encodeToString(iv));

// Create input and output streams for file encryption


FileInputStream fin = new FileInputStream("inputFile.txt");
FileOutputStream fout = new
FileOutputStream("outputFile.txt");
CipherOutputStream cout = new CipherOutputStream(fout,
cipherOut);

// Encrypt the input file and write it to the output file


int input = 0;
while ((input = fin.read()) != -1) {
cout.write(input);
}

// Close the input and output streams


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

BVCR, Rajahmundry

16
• In this Program, we’ll be using a text file named ‘inputFile.txt’ and perform
Encryption on its data using BlowFish Algorithm.

inputFile.txt:
This is a sample text file.
We are going to encrypt this file using the Blowfish algorithm.
Let's see how the encryption process works.

• Save the file as inputFile.txt in the directory where your Java program is located.
After creating the inputFile.txt file, run the program again.

OUTPUT:

Initialization Vector of the Cipher: JcB8nLbyitI=

BVCR, Rajahmundry

17
EXPERIMENT – 6
AIM: Write a C/JAVA program to implement the Rijndael algorithm logic.
DESCRIPTION:
AES (Advanced Encryption Standard) is a symmetric-key encryption algorithm
that was established as the standard encryption protocol by the National Institute of
Standards and Technology (NIST) in 2001. It is based on the Rijndael algorithm,
designed by cryptographers Joan Daemen and Vincent Rijmen. AES is widely
recognized for its security, efficiency, and versatility in various applications, such as
securing sensitive data in financial transactions, protecting communication channels,
and encrypting files.
• Symmetric Key: Uses the same key for encryption and decryption.
• Fixed Block Size: Operates on 128-bit data blocks.
• Variable Key Length: Supports 128, 192, and 256-bit keys.
• Efficient and Fast: Suitable for both software and hardware implementations.
• Substitution-Permutation Network: Employs substitution and permutation
steps for security.
• Widely Used: Common in secure communication, disk encryption, etc.
• Security: Highly secure and resistant to most known attacks.
• Public Standard: Open and widely accepted, ensuring interoperability.
SOURCE CODE:

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);
for (int i = 0; i < buf.length; i++) {
if (((int) buf[i] & 0xff) < 0x10)
strbuf.append("0");
strbuf.append(Long.toString((int) buf[i] & 0xff, 16));

BVCR, Rajahmundry

18
}
return strbuf.toString();
}

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


BufferedReader reader = new BufferedReader(new
InputStreamReader(System.in));
System.out.print("Enter a message to encrypt: ");
String message = reader.readLine();

// 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");
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(message.getBytes());
System.out.println("Encrypted text: " + asHex(encrypted));

cipher.init(Cipher.DECRYPT_MODE, skeySpec);

BVCR, Rajahmundry

19
byte[] original = cipher.doFinal(encrypted);
String originalString = new String(original);
System.out.println("Decrypted text: " + originalString);
}
}
OUTPUT:
Enter a message to encrypt: Security
Encrypted text: f49e84702d09651860cccdf23f34e467
Decrypted text: Security

BVCR, Rajahmundry

20
EXPERIMENT - 7

AIM: Using Java Cryptography, encrypt the text “Hello world” using BlowFish. Create
your own key using Java key tool.

DESCRIPTION:
Steps,
• Key Generation: Uses KeyGenerator to create a Blowfish key.
• Cipher Creation: An instance of Cipher is created using the Blowfish
algorithm.
• Encryption: Cipher is initialized in encryption mode and the user input
message is encrypted.
• Decryption: Cipher is re-initialized in decryption mode and the encrypted
message is decrypted.
• User Interaction: Uses JOptionPane for input and output to display encrypted
and decrypted text.

SOURCE CODE:

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
KeyGenerator keygenerator =
KeyGenerator.getInstance("Blowfish");

// Generate a key
SecretKey secretkey = keygenerator.generateKey();

// Create a cipher based upon Blowfish cipher


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

// Initialize the cipher with the secret key


cipher.init(Cipher.ENCRYPT_MODE, secretkey);

// Get the text to encrypt

BVCR, Rajahmundry

21
String inputText = JOptionPane.showInputDialog("Input your
message:");

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

// Re-initialize the cipher to be in decrypt mode


cipher.init(Cipher.DECRYPT_MODE, secretkey);

// Decrypt message
byte[] decrypted = cipher.doFinal(encrypted);

// Display the results

JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
"\nEncrypted text: " + new String(encrypted) + "\n" +
"\nDecrypted text: " + new String(decrypted));

System.exit(0);
}
}

OUTPUT:

BVCR, Rajahmundry

22
EXPERIMENT – 8
AIM: Write a Java program to implement RSA Algorithm
DESCRIPTION:
1. Prime Number Input: Prompts the user to enter two prime numbers, p and q.
2. Key Generation:
• Calculates n as the product of the two primes.
• Calculates phi (also known as φ(n) or Euler's totient function) as (p-1) * (q-1).
• Generates the public exponent e that is coprime with phi (1 < e < φ(n)).
• Calculates the private key d as the modular multiplicative inverse of e modulo
phi.
3. Display Keys: Prints the public keys (e, n) and the private keys (d, n).

SOURCE CODE:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.math.*;
import java.util.Random;
import java.util.Scanner;

public class RSA {


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

public static void main(String[] args) {


System.out.print("Enter a Prime number: ");
BigInteger p = sc.nextBigInteger();
System.out.print("Enter another prime number: ");
BigInteger q = sc.nextBigInteger();

BVCR, Rajahmundry

23
BigInteger n = p.multiply(q);
BigInteger phi =
p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
BigInteger e = generateE(phi);
BigInteger d = e.modInverse(phi);

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


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

public static BigInteger generateE(BigInteger phi) {


BigInteger e;
BigInteger gcd;
Random rand = new Random();
do {
e = new BigInteger(phi.bitLength(), rand);
gcd = phi.gcd(e);
} while (e.compareTo(BigInteger.TWO) <= 0 ||
!gcd.equals(BigInteger.ONE));
return e;
}
}

BVCR, Rajahmundry

24
OUTPUT:
RUN-1:
Enter a Prime number: 5
Enter another prime number: 11
Encryption keys are: 7, 55
Decryption keys are: 23, 55
RUN-2:
Enter a Prime number: 5
Enter another prime number: 11
Encryption keys are: 33, 55
Decryption keys are: 17, 55

BVCR, Rajahmundry

25
EXPERIMENT - 9
AIM: Implement the 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).
DESCRIPTION:
The Diffie-Hellman Key Exchange is a method used to securely exchange
cryptographic keys over a public channel. It allows two parties, such as Alice and Bob,
to establish a shared secret key that can be used for encrypted communication, even if
they have never met before.
How Diffie-Hellman Works
o Choose Public Parameters:
Both parties agree on a large prime number 𝑝 and a base 𝑔 (a primitive
root modulo 𝑝).
o Generate Private Keys:
Alice chooses a private key 𝑎 (a random number) and Bob chooses a private
key 𝑏 (another random number).
o Compute Public Keys:
Alice computes her public key 𝐴 = 𝑔^𝑎 mod 𝑝 and sends it to Bob.
Bob computes his public key 𝐵 = 𝑔^𝑏 mod 𝑝 and sends it to Alice.
o Generate Shared Secret:
Alice uses Bob's public key to compute the shared secret 𝑠 = 𝐵^𝑎 mod 𝑝.
Bob uses Alice's public key to compute the shared secret 𝑠 = 𝐴^𝑏 mod 𝑝.

Since 𝐵^𝑎 mod 𝑝 is equal to 𝐴^𝑏 mod 𝑝, both parties now have the same shared secret
key 𝑠, which can be used for further encrypted communication.

BVCR, Rajahmundry

26
SOURCE PROGRAM:
FileName: index.html

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>Diffie-Hellman Key Exchange</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
padding: 10px;
background-color: #f4f4f4;
}
h1 {
color: #2c3e50;
}
input {
padding: 5px;
margin: 5px;
}
button {
padding: 10px;
background-color: #3498db;
color: white;
border: none;
cursor: pointer;
}
button:hover {
background-color: #2980b9;
}
.output {
margin-top: 20px;
padding: 10px;
background-color: #ecf0f1;

BVCR, Rajahmundry

27
border-radius: 5px;
}
</style>
</head>
<body>

<h1>Diffie-Hellman Key Exchange (Alice & Bob)</h1>

<label for="alicePrivateKey">Enter Alice's Private Key


(a):</label>
<input type="number" id="alicePrivateKey" placeholder="Private
Key (a)" min="1" required>

<button onclick="startKeyExchange()">Start Key


Exchange</button>

<div class="output" id="output">


<h3>Results:</h3>
<p id="alicePublicKey"></p>
<p id="bobPublicKey"></p>
<p id="sharedSecret"></p>
</div>

<script>
// Define the public parameters (shared by Alice and Bob)
const p = 23; // A prime number (a small example for
simplicity)
const g = 5; // A base (primitive root modulo p)

// Bob's private key (b) is randomly chosen


const bobPrivateKey = 6;

// Function to perform exponentiation mod p (g^a mod p)


function modExp(base, exponent, modulus) {
let result = 1;
base = base % modulus;
while (exponent > 0) {
if (exponent % 2 === 1) {
result = (result * base) % modulus;
}

BVCR, Rajahmundry

28
exponent = Math.floor(exponent / 2);
base = (base * base) % modulus;
}
return result;
}

// Function to start the Diffie-Hellman exchange


function startKeyExchange() {
const alicePrivateKey =
parseInt(document.getElementById("alicePrivateKey").value);

if (isNaN(alicePrivateKey) || alicePrivateKey <= 0) {


alert("Please enter a valid positive number for Alice's
private key.");
return;
}

// Step 1: Alice computes her public key (A)


const alicePublicKey = modExp(g, alicePrivateKey, p);

// Step 2: Bob computes his public key (B)


const bobPublicKey = modExp(g, bobPrivateKey, p);

// Step 3: Alice computes the shared secret using Bob's


public key
const sharedSecretAlice = modExp(bobPublicKey,
alicePrivateKey, p);

// Step 4: Bob computes the shared secret using Alice's


public key
const sharedSecretBob = modExp(alicePublicKey,
bobPrivateKey, p);

// Display results
document.getElementById("alicePublicKey").innerText =
`Alice's Public Key (A) = ${alicePublicKey}`;
document.getElementById("bobPublicKey").innerText =
`Bob's Public Key (B) = ${bobPublicKey}`;

BVCR, Rajahmundry

29
document.getElementById("sharedSecret").innerText =
`Shared Secret = ${sharedSecretAlice} (Both Alice and Bob
have the same secret: ${sharedSecretAlice})`;
}
</script>

</body>
</html>

OUTPUT:
Click the below link to visit the WebPage and check the working of Diffie-Hellman
Key Exchange Algorithm…

Link: https://encr.pw/iHPa5

BVCR, Rajahmundry

30
EXPERIMENT – 10

AIM: Calculate the message digest of a text using the SHA-1 algorithm in JAVA.

DESCRIPTION:
SHA-1 (Secure Hash Algorithm 1) is a cryptographic hash function that
generates a fixed-size 160-bit (20-byte) hash value from an input. It is used in various
security applications and protocols to ensure data integrity.
How SHA-1 Works:
1. Padding: The input data is padded to a length that is a multiple of 512 bits.
2. Initialize Hash Values: Use predefined initial hash values.
3. Process Blocks: Divide the padded input into 512-bit blocks and process each
block through 80 rounds of operations, updating the hash values.
4. Generate Output: Concatenate the final hash values to produce the 160-bit
hash value (digest).
Characteristics:
• Deterministic: Same input, same hash value.
• Fixed Output: Always produces a 160-bit hash.
• Pre-image Resistant: Hard to find the original input from the hash.
• Collision Resistant: Hard to find two different inputs with the same hash.
Note:
SHA-1 is no longer considered secure for cryptographic purposes (due to
vulnerabilities discovered over time), and it's generally recommended to use
stronger hash functions like SHA-256 or SHA-3 in modern applications.

BVCR, Rajahmundry

31
SOURCE CODE:

import java.security.*;

public class SHA1 {


public static void main(String[] a) {
try {
// Create a MessageDigest object for SHA-1
MessageDigest md = MessageDigest.getInstance("SHA1");

// Print out the MessageDigest object details


System.out.println("Message digest object info: ");
System.out.println(" Algorithm = " + md.getAlgorithm());
System.out.println(" Provider = " + md.getProvider());
System.out.println(" ToString = " + md.toString());

// Compute and print the SHA-1 hash of an empty string


String input = "";
md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("SHA1(\"" + input + "\") = " + bytesToHex(output));

// Compute and print the SHA-1 hash of the string "abc"


input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\"" + input + "\") = " + bytesToHex(output));

// Compute and print the SHA-1 hash of the string


"abcdefghijklmnopqrstuvwxyz"
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\"" + input + "\") = " + bytesToHex(output));

System.out.println(""); // Print a blank line


} catch (Exception e) {
// Catch any exceptions and print the error message
System.out.println("Exception: " + e);
}
}

BVCR, Rajahmundry

32
// Helper method to convert a byte array to a hexadecimal string
public static String bytesToHex(byte[] b) {
char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E',
'F'};
StringBuffer buf = new StringBuffer();

// Convert each byte to its hexadecimal representation


for (int j = 0; j < b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]); // Upper nibble
buf.append(hexDigit[b[j] & 0x0f]); // Lower nibble
}

return buf.toString(); // Return the hexadecimal string


}
}

OUTPUT:

Message digest object info:


Algorithm = SHA1
Provider = SUN version 21
ToString = SHA1 Message Digest from SUN, <initialized>

SHA1("") = DA39A3EE5E6B4B0D3255BFEF95601890AFD80709

SHA1("abc") = A9993E364706816ABA3E25717850C26C9CD0D89D

SHA1("abcdefghijklmnopqrstuvwxyz") =
32D10C7B8CF96570CA04CE37F2A19D84240D3A89

BVCR, Rajahmundry

33

You might also like