CNS_LAB_R20
CNS_LAB_R20
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);
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
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;
encryptedText.append(ch);
}
return encryptedText.toString();
}
4
StringBuilder decryptedText = new StringBuilder();
decryptedText.append(ch);
}
return decryptedText.toString();
}
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.*;
BVCR, Rajahmundry
7
}
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.*;
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");
}
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:
BVCR, Rajahmundry
11
EXPERIMENT – 4
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.
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;
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);
}
BVCR, Rajahmundry
13
return decryptedText;
}
OUTPUT:
BVCR, Rajahmundry
14
EXPERIMENT – 5
DESCRIPTION:
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;
BVCR, Rajahmundry
15
cipherOut.init(Cipher.ENCRYPT_MODE, secretKey);
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:
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.*;
BVCR, Rajahmundry
18
}
return strbuf.toString();
}
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;
// Generate a key
SecretKey secretkey = keygenerator.generateKey();
BVCR, Rajahmundry
21
String inputText = JOptionPane.showInputDialog("Input your
message:");
// Encrypt message
byte[] encrypted = cipher.doFinal(inputText.getBytes());
// Decrypt message
byte[] decrypted = cipher.doFinal(encrypted);
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;
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);
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>
<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)
BVCR, Rajahmundry
28
exponent = Math.floor(exponent / 2);
base = (base * base) % modulus;
}
return result;
}
// 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.*;
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();
OUTPUT:
SHA1("") = DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
SHA1("abc") = A9993E364706816ABA3E25717850C26C9CD0D89D
SHA1("abcdefghijklmnopqrstuvwxyz") =
32D10C7B8CF96570CA04CE37F2A19D84240D3A89
BVCR, Rajahmundry
33