CyberSecurity Lab Programs
CyberSecurity Lab Programs
Part-A
1. Caesar Cipher
Code:
import java.util.*;
class Caesar {
// Encrypts the plain text using Caesar cipher with the given key
public static String encrypt(String pt, int key) {
String ct = ""; // To store the ciphertext
String letters = "abcdefghijklmnopqrstuvwxyz"; // List of all lowercase alphabets
// Decrypts the ciphertext using Caesar cipher with the given key
public static String decrypt(String ct, int key) {
String pt = ""; // To store the decrypted plaintext
String letters = "abcdefghijklmnopqrstuvwxyz"; // List of all lowercase alphabets
Logic:
Matrix Creation: A 5x5 matrix is constructed using the given key. The key is
inserted first, followed by the remaining letters of the alphabet (skipping 'J' since it's
treated as 'I').
Ignore 'J': The input is preprocessed to replace all occurrences of 'J' with 'I', as
the Playfair cipher does not distinguish between 'I' and 'J'.
Input Preparation: The input is processed to ensure it's in even length, inserting
'x' between repeated letters and appending 'x' if the length is odd.
Encryption/Decryption:
Same Row: If the letters are in the same row, they are replaced by the letters
immediately to their right.
Same Column: If the letters are in the same column, they are replaced by the
letters immediately below them.
Rectangle: Otherwise, the letters are replaced by the letters on the same row but
in the column of the other letter.
Functions Used:
ignoreJ(String input):
Purpose: This function replaces all occurrences of the letter 'J' in the input string
with 'I'. This is because the Playfair cipher treats 'I' and 'J' as the same letter in
the 5x5 matrix.
Logic: It loops through each character of the input and checks if it is 'J'. If so, it
adds 'I' to the result string, otherwise, it adds the character itself.
createMatrix(String key):
Purpose: This function creates a 5x5 matrix based on the provided key. The
matrix is filled with the letters from the key first, then the remaining letters of the
alphabet (skipping 'J').
Logic: It first fills the matrix with characters from the key. Afterward, it checks for
duplicate characters in the key, and if a character is not present, it adds it to the
matrix. The matrix size is restricted to 5x5, so characters are skipped accordingly.
inputBuilder(String input):
Purpose: This function prepares the input string for encryption by ensuring that
it's of even length. If two consecutive letters in the input are the same, it inserts 'x'
between them. If the input length is odd, it appends an 'x' at the end.
encrypt(String input):
Purpose: This function encrypts the input string using the Playfair cipher rules.
Logic: The function processes the input in pairs of characters. For each pair, it
finds their positions in the matrix:
o If the characters are in the same row, it replaces them with the characters
to their right.
o If the characters are in the same column, it replaces them with the
characters below them.
o If the characters form a rectangle, it swaps the corners to generate the
cipher text.
decrypt(String input):
Purpose: This function decrypts the ciphered string using the Playfair cipher
rules.
Logic: It is similar to the encrypt function, but the characters are shifted in the
opposite direction:
o If the characters are in the same row, they are replaced with the
characters to their left.
o If the characters are in the same column, they are replaced with the
characters above them.
Code:
import java.util.*;
class PlayFair {
// Define the alphabet (excluding 'j' as it is treated as 'i')
static String letters = "abcdefghijklmnopqrstuvwxyz";
// Method to create the Playfair cipher key matrix from the key
public static void createMatrix(String key) {
int counter = 0, letterCounter = 0;
boolean isPresent = false;
// Method to process the input string and handle double letters by adding 'x'
between them
public static String inputBuilder(String input) {
String finalString = "";
// Loop through the input string, check if consecutive characters are the same
for (int i = 0; i < input.length() - 1; i += 2) {
if (input.charAt(i) == input.charAt(i + 1))
// If consecutive characters are the same, add 'x' between them
finalString += input.charAt(i) + "x" + input.charAt(i + 1);
else
finalString += input.charAt(i) + "" + input.charAt(i + 1);
}
// If the input length is odd, add the last character with 'x' to make it even length
if (input.length() % 2 != 0)
finalString += input.charAt(input.length() - 1);
// If the resulting string has an odd length, append 'x' to make it even length
if (finalString.length() % 2 != 0)
finalString += "x";
return finalString;
}
return result;
}
return result;
}
String result;
switch (choice) {
case 1:
result = encrypt(passingString);
System.out.println("Cipher text: " + result);
break;
case 2:
result = decrypt(passingString);
System.out.println("Plain text: " + result);
break;
default:
System.out.println("Invalid choice!");
}
}
}
3. Hill Cipher (Akshit’s Alternative code)
Logic:
1. Input Phase
The user inputs:
Padding: The code adds 'X' to the end of the text if its length isn't divisible by the
matrix size (to make full blocks).
Block Processing:
3. Encryption Logic
Resulting vector values are taken mod 26, then converted back to letters.
4. Decryption Logic
Functions Used:
✅ modInv(int a, int m)
🔍 Purpose:
Finds the modular inverse of a under modulo m.
🧠 Logic:
Tries values from 1 to m-1.
Returns x if (a * x) % m == 1, meaning it is the multiplicative inverse.
If no such x exists, throws an error.
✅ det(int[][] m, int n)
🔍 Purpose:
Computes the determinant of matrix m of size n × n.
🧠 Logic:
For 2x2 matrix: uses the basic formula:
(m[0][0] * m[1][1] - m[0][1] * m[1][0])
For larger matrices: uses recursion and cofactor expansion along the first row.
Always returns result % 26 to stay in the alphabet range.
✅ inv(int[][] k, int n)
🔍 Purpose:
Calculates the inverse of the key matrix under modulo 26.
🧠 Logic:
1. Finds determinant d of the matrix.
2. Finds modular inverse di of that determinant.
3. Uses cofactors and adjugate transpose to build inverse matrix.
4. Scales by di and applies % 26 to all values to complete the inversion.
📌 Key Concepts Used:
Cofactor = signed minor of a matrix element.
Adjugate = transpose of cofactor matrix.
Code:
import java.util.Scanner;
// Matrix multiplication
for (int j = 0; j < s; j++) {
int sum = 0;
for (int l = 0; l < s; l++)
sum += v[l] * keyMatrix[l][j];
return r.toString();
}
}
4. Vigenere Cipher
Logic:
Code:
import java.util.Scanner;
public class VigenereCipher {
public static String encrypt(String text, String key) {
StringBuilder result = new StringBuilder();
char c, encryptedChar;
int shift;
text = text.toUpperCase();
key = key.toUpperCase();
scanner.close();
}
}
5. Simplified DES
Logic:
🔑 1. Key Generation
🔐 sBoxSubstitution(String input)
🔁 xor(String a, String b)
Code:
import java.util.*;
private static final int[][] SBOX1 = {{1, 0, 3, 2}, {3, 2, 1, 0}, {0, 2, 1, 3}, {3, 1, 0, 2}};
private static final int[][] SBOX2 = {{0, 1, 2, 3}, {2, 0, 1, 3}, {3, 0, 1, 0}, {2, 1, 0, 3}};
scanner.close();
}
}
Part-B
6. RSA
Logic:
1. Input Primes
phi = (p - 1) * (q - 1):
Euler's Totient Function — it gives the count of numbers less than n that are
coprime with n. It is used to calculate the keys.
The code tries every number from 1 to phi, and finds the first d such that:
o (d * e) % phi == 1
6. Decryption
The ciphertext C is decrypted using the private key with:
M = C^d mod n
Code:
import java.util.*;
// Step 2: Choose e such that 1 < e < phi and gcd(e, phi) == 1
System.out.print("Enter value of e: ");
long e = scan.nextLong();
scan.close();
}
}
7. Diffie-Hellman Key Exchange
Logic:
These two values are publicly shared and known to both Alice and Bob.
2. Private Keys
These public keys can be safely shared even over insecure channels.
Each party uses the other’s public key and their own private key to compute the same
shared secret:
Alice computes:
K = (Ba mod p)
= (gb)a mod p
= gab mod p
Bob computes:
K = (Ab mod p)
= (ga)b mod p
= gab mod p
So both get the same shared key without directly sending it.
5. Final Check
If both parties compute the same shared key, the key exchange is successful.
Code:
import java.util.Scanner;
scanner.close();
}
Logic:
2. Input a number p that is relatively prime to q (they must not have common
factors other than 1).
3. Alice chooses her private key Xa, and her public key Ya = (pXa) % q is
generated.
4. A message M is encrypted into (C1, C2) using a randomly chosen number k and
the recipient’s public key Ya.
5. The message is decrypted using the private key and the modular inverse of a
calculated value.
Functions Used:
a. User defined:
Function Purpose
import java.util.*;
scan.close();
}
// K = (Y^k) % q
long K = modExp(Y, k, q);
System.out.println("Shared key K = " + K);
// C1 = (p^k) % q
C1 = modExp(p, k, q);
// C2 = (K * M) % q
C2 = (K * M) % q;
// M = (C2 * K_inverse) % q
long M = (C2 * kinverse) % q;
Code:
import java.util.Scanner;
sc.close();
}
}
10. Digital Signature (Same as Akshit’s only with functions)
Logic:
o p = 17, q = 11 → n = 187
3. Choose a public key exponent e such that 1 < e < phi and gcd(e, phi) = 1.
o e = 7 is chosen and checked to be coprime with 160.
4. Compute the private key exponent d, the modular inverse of e mod phi.
o d × e ≡ 1 mod phi
o This is encrypting the hash with the private key, simulating a digital
signature.
7. Verification:
o The verifier computes sige mod n (i.e., decrypts the signature using the
public key).
o If the result matches the hash of the original message, the signature is
valid.
Functions Used:
Code:
import java.util.*;
// Simple GCD
public static long gcd(long a, long b) {
while (b != 0) {
long tmp = b;
b = a % b;
a = tmp;
}
return a;
}
// Step 2: Choose e such that 1 < e < phi and gcd(e, phi) == 1
System.out.print("Enter value of e: ");
long e = scan.nextLong();
// Message
System.out.print("Enter your message: ");
String message = scan.next();
if (decryptedHash == originalHash) {
System.out.println("✅ Signature verified successfully!");
} else {
System.out.println("❌ Signature verification failed!");
}
scan.close();
}
}
/*
Signature: 11
Decrypted Hash: 53
Original Hash : 53
✅ Signature verified successfully!
Signature: 63
Decrypted Hash: 87
Original Hash : 87
✅ Signature verified successfully!
*/