DEPARTMENT
OF
COMPUTER SCIENCE AND ENGINEERING
LAB MANUAL
LAB NAME : CRYPTOGRAPHY AND NETWORK SECURITY (R20)
FACULTY NAME : MR. Y.DINESH KUMAR (ASSOCIATE PROFESSOR)
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.
Program:
#include<string.h>
#include<stdio.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
1
2. Write a C program that contains a string (char pointer) with a value ‘Hello World’. The program should AND and
XOR each character in this string with 127 and display the result.
Program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char str[] = "Hello World";
char str1[12];
char str2[12];
char str3[12];
strcpy(str2, str);
int i, len;
len = strlen(str);
for (i = 0; i < len; i++)
{
str1[i] = str[i] & 127;
printf("%c", str1[i]);
}
str1[len] = '\0';
printf("\n");
for (i = 0; i < len; i++)
{
str3[i] = str2[i] ^ 127;
printf("%c", str3[i]);
}
str3[len] = '\0';
printf("\n");
return 0;
}
Output:
Hello World
7␦_(
2
3. Write a Java program to perform encryption and decryption using the following algorithms:
(a)Caeser Cipher
(b)Substitution Cipher
(c)Hill Cipher
(a)Caeser Cipher
Program:
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));
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 String is: " + encrypted);
String decrypted = decrypt(encrypted, key);
System.out.println("\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;
}
3
return encrypted;
}
public static String decrypt(String str, int key) {
String decrypted = "";
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: Mjqqt Btwqi
Decrypted String is: Hello World
(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 = "";
4
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);
}
}
Output:
Enter any string: aceho
The encrypted data is: zxvsl
(c)Hill Cipher
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 {
// TODO code application logic here
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++) {
5
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;
}
}
}
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];
6
}
}
}
}
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 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):
123
014
560
Enter a 3 letter string: hai
Encrypted string is : fgj
Inverse Matrix is :
-24.0 18.0 5.0
20.0 -15.0 -4.0
-5.0 4.0 1.0
Decrypted string is : hai
7
4. 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;
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;
private byte[] keyAsBytes;
private String myEncryptionKey;
private String myEncryptionScheme;
private SecretKey key;
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);
}
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);
// Use java.util.Base64.Encoder to encode the byte array
encryptedString = Base64.getEncoder().encodeToString(encryptedText);
} catch (Exception e) {
e.printStackTrace();
}
return encryptedString;
8
}
public String decrypt(String encryptedString) {
String decryptedText = null;
try {
cipher.init(Cipher.DECRYPT_MODE, key);
// Use java.util.Base64.Decoder to decode the string back to byte array
byte[] encryptedText = Base64.getDecoder().decode(encryptedString);
byte[] plainText = cipher.doFinal(encryptedText);
decryptedText = bytes2String(plainText);
} catch (Exception e) {
e.printStackTrace();
}
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: Welcome
String To Encrypt: Welcome
Encrypted Value : BPQMwc0wKvg=
Decrypted Value : Welcome
9
5. Write a C/JAVA program to implement the BlowFish algorithm logic.
Program:
import java.io.*;
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 {
// Initialize Blowfish key generator and set up cipher
KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
keyGenerator.init(128); // Blowfish key size 128 bits
Key secretKey = keyGenerator.generateKey();
// Create and initialize cipher in encryption mode
Cipher cipherOut = Cipher.getInstance("Blowfish/CFB/NoPadding");
cipherOut.init(Cipher.ENCRYPT_MODE, secretKey);
// Base64 encoding for IV (Initialization Vector)
Base64.Encoder encoder = Base64.getEncoder();
byte[] iv = cipherOut.getIV();
if (iv != null) {
System.out.println("Initialization Vector of the Cipher: " + encoder.encodeToString(iv));
}
// Read data from input file and write encrypted data to output file
FileInputStream fin = new FileInputStream("inputFile.txt"); // Input file
FileOutputStream fout = new FileOutputStream("outputFile.txt"); // Output file
CipherOutputStream cout = new CipherOutputStream(fout, cipherOut);
int input = 0;
while ((input = fin.read()) != -1) {
cout.write(input); // Encrypt and write data to output file
}
// Close streams after operation
fin.close();
cout.close();
// Optionally, print out the contents of input and output files to verify
System.out.println("\nContents of inputFile.txt:");
printFileContent("inputFile.txt");
System.out.println("\nContents of outputFile.txt (Encrypted):");
printFileContent("outputFile.txt");
}
10
// Helper method to print the content of a file
private static void printFileContent(String filename) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // Print each line of the file
}
reader.close();
}
}
Output:
Initialization Vector of the Cipher: Uf4PJt6ZTDw=
Contents of inputFile.txt:
Hello World
Contents of outputFile.txt (Encrypted):
?-Tk←??~??8
11
6. 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.*;
import java.util.Base64; // Added for Base64 encoding/decoding
import java.util.Scanner; // Importing Scanner for user input
public class AES {
// Method to convert byte array to hex string
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));
}
return strbuf.toString();
}
public static void main(String[] args) throws Exception {
// Create a Scanner object to take user input
Scanner scanner = new Scanner(System.in);
// Taking input message from the user
System.out.print("Enter your message: ");
String message = scanner.nextLine(); // Reading the user's message
// Get the KeyGenerator
KeyGenerator kgen = KeyGenerator.getInstance("AES");
kgen.init(128); // 128-bit AES key
// 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");
// Encryption
cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
byte[] encrypted = cipher.doFinal(message.getBytes()); // Encrypt the message
// Base64 encode the encrypted text to make it readable as a string
String encryptedText = Base64.getEncoder().encodeToString(encrypted);
System.out.println("Encrypted text: " + encryptedText); // Output encrypted text
12
// Decryption
cipher.init(Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = cipher.doFinal(Base64.getDecoder().decode(encryptedText)); // Decrypt using Base64-
decoded text
String decryptedText = new String(decrypted);
System.out.println("Decrypted text: " + decryptedText); // Output decrypted text
scanner.close(); // Close the scanner
}
}
Output:
Enter your message: Hello KGRCET
Encrypted text: dRxdlNSQT1J5wCiHi2S/ug==
Decrypted text: Hello KGRCET
13
7. 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
KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");
// Create a key
SecretKey secretkey = keygenerator.generateKey();
// Create a cipher based upon Blowfish
Cipher cipher = Cipher.getInstance("Blowfish");
// Initialise cipher 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);
// Display the results
JOptionPane.showMessageDialog(JOptionPane.getRootFrame(),
"\nEncrypted text: " + new String(encrypted) + "\n" +
"\nDecrypted text: " + new String(decrypted));
System.exit(0);
}
}
Output:
Input your message: Hello world
Encrypted text: 3ooo&&(*&*4r4
Decrypted text: Hello world
14
8. Write a Java program to implement RSA Algoithm.
Program:
import java.math.BigInteger;
import java.util.Random;
import java.util.Scanner;
public class RSA {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
// Get two prime numbers
System.out.print("Enter a Prime number: ");
BigInteger p = sc.nextBigInteger(); // First prime number
System.out.print("Enter another prime number: ");
BigInteger q = sc.nextBigInteger(); // Second prime number
// Calculate n and phi(n)
BigInteger n = p.multiply(q);
BigInteger n2 = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
// Generate public exponent e
BigInteger e = generateE(n2);
// Calculate private exponent d
BigInteger d = e.modInverse(n2);
// Display the keys
System.out.println("Encryption keys are: " + e + ", " + n);
System.out.println("Decryption keys are: " + d + ", " + n);
// Encrypt a message
System.out.print("Enter a message to encrypt (in numeric form): ");
BigInteger message = sc.nextBigInteger(); // Input message as a numeric value
BigInteger encryptedMessage = encrypt(message, e, n);
System.out.println("Encrypted message: " + encryptedMessage);
// Decrypt the message
BigInteger decryptedMessage = decrypt(encryptedMessage, d, n);
System.out.println("Decrypted message: " + decryptedMessage);
}
// Method to generate a valid e
public static BigInteger generateE(BigInteger fiofn) {
int y;
BigInteger e;
Random x = new Random();
do {
15
y = x.nextInt(fiofn.intValue() - 1) + 2; // Generate random y between 2 and φ(n)-1
e = new BigInteger(Integer.toString(y));
} while (fiofn.gcd(e).compareTo(BigInteger.ONE) != 0); // Ensure gcd(e, φ(n)) = 1
return e;
}
// Encrypt a message using public key (e, n)
public static BigInteger encrypt(BigInteger message, BigInteger e, BigInteger n) {
return message.modPow(e, n); // message^e mod n
}
// Decrypt a message using private key (d, n)
public static BigInteger decrypt(BigInteger encryptedMessage, BigInteger d, BigInteger n) {
return encryptedMessage.modPow(d, n); // encryptedMessage^d mod n
}
}
Output:
Enter a Prime number: 5
Enter another prime number: 11
Encryption keys are: 7, 55
Decryption keys are: 23, 55
16
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 other party (bob).
Program:
import java.math.BigInteger;
import java.security.*;
import javax.crypto.*;
import javax.crypto.interfaces.DHPublicKey; // Import for DHPublicKey
import javax.crypto.spec.*;
public class DiffieHellmanExample {
public static void main(String[] args) throws Exception {
// Generate DH key pair for Alice
KeyPairGenerator keyGen = KeyPairGenerator.getInstance("DiffieHellman");
keyGen.initialize(512);
KeyPair aliceKeyPair = keyGen.generateKeyPair();
// Extract Alice's public key
PublicKey alicePublicKey = aliceKeyPair.getPublic();
PrivateKey alicePrivateKey = aliceKeyPair.getPrivate();
System.out.println("Alice's Public Key: " + alicePublicKey);
// Generate DH key pair for Bob using Alice's parameters
DHParameterSpec dhSpec = ((DHPublicKey) alicePublicKey).getParams(); // Fixed: Correctly casting to
DHPublicKey
keyGen.initialize(dhSpec);
KeyPair bobKeyPair = keyGen.generateKeyPair();
// Extract Bob's public key
PublicKey bobPublicKey = bobKeyPair.getPublic();
PrivateKey bobPrivateKey = bobKeyPair.getPrivate();
System.out.println("Bob's Public Key: " + bobPublicKey);
// Compute shared secret for Alice
KeyAgreement aliceKeyAgree = KeyAgreement.getInstance("DiffieHellman");
aliceKeyAgree.init(alicePrivateKey);
aliceKeyAgree.doPhase(bobPublicKey, true);
byte[] aliceSharedSecret = aliceKeyAgree.generateSecret();
// Compute shared secret for Bob
KeyAgreement bobKeyAgree = KeyAgreement.getInstance("DiffieHellman");
bobKeyAgree.init(bobPrivateKey);
bobKeyAgree.doPhase(alicePublicKey, true);
byte[] bobSharedSecret = bobKeyAgree.generateSecret();
// Convert shared secret to BigInteger for display
17
System.out.println("Shared Secret (Alice's View): " + new BigInteger(1, aliceSharedSecret));
System.out.println("Shared Secret (Bob's View): " + new BigInteger(1, bobSharedSecret));
// Verify if both shared secrets are the same
System.out.println("Keys Match: " + java.util.Arrays.equals(aliceSharedSecret, bobSharedSecret));
}
}
Output:
Alice's Public Key: SunJCE Diffie-Hellman Public Key:
y:
2b70a53f 16a939e3 1362ef5b 11dfe7da 73b7c06b 0604a0c5 187c9fb6 eeb5fe07
9c759c3e 3e40cc93 b8f6e373 8a5366b4 8ad40760 676b7092 c89e1bb4 1fb15429
p:
ffffffff ffffffff 8b479b3a 6e8de86c 294188f0 bf2cd86c db950adb 36d0f61f
d51e46f6 9c99ed95 abe5a7bb b230a6ed 1d0b4506 b5317284 ffffffff ffffffff
g:
02
l:
160
Bob's Public Key: SunJCE Diffie-Hellman Public Key:
y:
3f37e846 0a5b981f 5d82a1c9 632f11ae 3d5de324 81d725cf 2ffe3050 5f4e4549
5a89515d b4228601 45891022 7718fe7b 875bbeec 334f676d d19334dc 526ee7e5
p:
ffffffff ffffffff 8b479b3a 6e8de86c 294188f0 bf2cd86c db950adb 36d0f61f
d51e46f6 9c99ed95 abe5a7bb b230a6ed 1d0b4506 b5317284 ffffffff ffffffff
g:
02
l:
160
Shared Secret (Alice's View):
567458815451843948643709504551940572204309493322060086638664223647196139419079338087931176
2669004817912190171354686735202038412605756110268299151501385788
Shared Secret (Bob's View):
567458815451843948643709504551940572204309493322060086638664223647196139419079338087931176
2669004817912190171354686735202038412605756110268299151501385788
Keys Match: true
18
10. Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
Program:
import java.security.*;
public class SHA1 {
public static void main(String[] a) {
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
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());
String input = "";
md.update(input.getBytes());
byte[] output = md.digest();
System.out.println();
System.out.println("SHA1(\"" + input + "\") = " + bytesToHex(output));
input = "abc";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\"" + input + "\") = " + bytesToHex(output));
input = "abcdefghijklmnopqrstuvwxyz";
md.update(input.getBytes());
output = md.digest();
System.out.println();
System.out.println("SHA1(\"" + input + "\") = " + bytesToHex(output));
System.out.println("");
} catch (Exception e) {
System.out.println("Exception: " + e);
}
}
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();
for (int j = 0; j < b.length; j++) {
buf.append(hexDigit[(b[j] >> 4) & 0x0f]);
buf.append(hexDigit[b[j] & 0x0f]);
}
return buf.toString();
19
}
}
Output:
Message digest object info:
Algorithm = SHA1
Provider = SUN version 23
ToString = SHA1 Message Digest from SUN, <initialized>
SHA1("") = DA39A3EE5E6B4B0D3255BFEF95601890AFD80709
SHA1("abc") = A9993E364706816ABA3E25717850C26C9CD0D89D
SHA1("abcdefghijklmnopqrstuvwxyz") = 32D10C7B8CF96570CA04CE37F2A19D84240D3A89
20