0% found this document useful (0 votes)
12 views8 pages

Week 1 Program

The document provides Java programs for implementing three types of ciphers: Caesar Cipher, Substitution Cipher, and Hill Cipher. Each cipher includes an explanation of the encryption and decryption processes, along with sample code demonstrating how to perform these operations. The document also includes example outputs for each cipher to illustrate their functionality.

Uploaded by

shivayarraboina8
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)
12 views8 pages

Week 1 Program

The document provides Java programs for implementing three types of ciphers: Caesar Cipher, Substitution Cipher, and Hill Cipher. Each cipher includes an explanation of the encryption and decryption processes, along with sample code demonstrating how to perform these operations. The document also includes example outputs for each cipher to illustrate their functionality.

Uploaded by

shivayarraboina8
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

WEEK 1:

1A) Write a Java program to Implement Caesar Cipher


Caesar Cipher
The Caesar Cipher is a cryptographic substitution cipher that shifts each letter in a text by a fixed
number of places in the alphabet. (Non-alphabetic characters remain unchanged).This process is called
encryption.
Decryption reverses the process by shifting the letters back by the same number of places.

Caesar Cipher example with a shift of 3:

Original Text H e l l o (space) W o r l d

key->Shift (+3) K h o o r (space) Z r u o g

Encrypted Text K h o o r (space) Z r u o g

import [Link];
public class CaesarCipher {
public static String caesarCipherEncrypt(String plaintext, int key) {
// StringBuilder to store the resulting encrypted text
StringBuilder ciphertext = new StringBuilder();
for (char c : [Link]()) { // Iterate through each character in the input text
if ([Link](c)) { // Check if the character is a letter
char base = [Link](c) ? 'a' : 'A'; // check character is lowercase or uppercase
// Shift the character and wrap around within the alphabet using modulo
[Link]((char) ((c - base + key) % 26 + base));
/* ex. 'H' is uppercase → base = 'A'.
c - base = 'H' - 'A' = 72 - 65 = 7
7 + key = 7 + 3 = 10 % 26=10+ base =>10+65 =>75 => k */
} else {
// If the character is not a letter, leave it unchanged
[Link](c);
}
}
return [Link]();
}
// Method to decrypt text using Caesar Cipher
public static String caesarCipherDecrypt(String ciphertext, int key) {
// Decrypt by reversing the shift (26 - shift)
return caesarCipherEncrypt(ciphertext, 26 - key);
}

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
[Link]("Enter the plain text: ");
String text = [Link]();
[Link]("Enter key value: ");
int key = [Link]();
// Encrypt the input text using the Caesar Cipher
String encr = caesarCipherEncrypt(text, key);
[Link]("Encrypted Text: " + encr);
// Decrypt the encrypted text back to the original text
String decr = caesarCipherDecrypt(encr, key);
[Link]("Decrypted Text: " + decr);
[Link]();
}
}

Output:
Enter plain text: naveen
Enter key value: 2
Encrypted Text: pcxggp
Decrypted Text: naveen

1 b) Write a java program to implement Substitution Cipher

A substitution cipher is a method of encryption in which each letter of the plaintext is replaced with another
letter according to a fixed substitution rule. The rule is typically defined by a key, which maps each letter of the
alphabet to a unique replacement.

Example:
Key:

Plain Alphabet: ABCDEFGHIJKLMNOPQRSTUVWXYZ


Cipher Alphabet: QWERTYUIOPASDFGHJKLZXCVBNM

Encryption:
Plaintext: HELLO WORLD
Ciphertext: ITSSG VGKSR

Decryption:
Ciphertext: ITSSG VGKSR
Plaintext: HELLO WORLD

PROGRAM:
import [Link];
public class SubstitutionCipher {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
// Input: Substitution key
[Link]("Enter the substitution key (26 unique uppercase letters):");
String k = [Link]().toUpperCase();

// Validate key
if ([Link]() != 26 || ![Link]("[A-Z]{26}")) {
[Link]("Invalid key! Key must contain 26 unique uppercase letters.");
return;
}
// Input: Plain text to encrypt
[Link]("Enter the plain text to encrypt:");
String pt = [Link]();
// Encrypt and display the result
String ct = encrypt(pt, k);
[Link]("Encrypted Text: " + ct);
// Decrypt and display the result
String dt = decrypt(ct, k);
[Link]("Decrypted Text: " + dt);
[Link]();
}

// Encrypts the plaintext using the given substitution key


public static String encrypt(String pt, String k) {
StringBuilder ct = new StringBuilder();
for (char c : [Link]().toCharArray()) {
if ([Link](c)) {
[Link]([Link](c - 'A')); // Map letter using key
} else {
[Link](c); // Keep non-letters as is
}
}
return [Link]();
}
// Decrypts the ciphertext using the given substitution key
public static String decrypt(String ct, String k) {
StringBuilder pt = new StringBuilder();
for (char c : [Link]().toCharArray()) {
if ([Link](c)) {
[Link]((char) ('A' + [Link](c))); // Reverse mapping
} else {
[Link](c); // Keep non-letters as is
}
}
return [Link]();
}
}
OUTPUT:
Enter the substitution key (26 unique uppercase letters):
QWERTYUIOPASDFGHJKLZXCVBNM
Enter the plain text to encrypt:
NAVEEN
Encrypted Text: FQCTTF
Decrypted Text: NAVEEN
1c. Write a java program to implement Hill Cipher

The Hill Cipher is a polygraphic substitution cipher based on linear algebra. It encrypts plaintext by multiplying
it with an invertible key matrix modulo 26.

Each letter is represented by a number modulo 26. The simple substitution scheme is used where A = 0, B =
1, C = 2…Z = 25 .

Encryption: C = (K * P) mod 26
Where K is the key matrix and P is plain text in vector form.

Decryption: P = (K-1 * C) mod 26


Where K-1 is the inverse key matrix and C is the ciphertext in vector form

Example:

If plaint text has 3 or more characters, then divide the plaintext into pairs of letters.
Ex. Plaint text= RAVI → “RA” “ VI”
Ex HELLO
Divide the plaintext into pairs of letters: "HE" "LL" "O_" (where "_" is a padding character, like 'X').

PROGRAM (FOR ENCRYPTION)

import [Link];
public class HillCipher {
private static int[ ][ ] key;

public static void main(String[] args) {


Scanner sc = new Scanner([Link]);
key = new int[2][2];

// Input the 2x2 key matrix


[Link]("Enter key matrix (2x2):");
for (int i = 0; i < 2; i++) // Loop to fill the key matrix
for (int j = 0; j < 2; j++)
key[i][j] = [Link]();

// Input plaintext and format it


[Link]("Enter plaintext: ");
[Link]();
String plaintext = [Link]().toUpperCase().replaceAll("[^A-Z]", ""); // Remove non-alphabet characters
while ([Link]() % 2 != 0) plaintext += 'X'; // Pad plaintext if its length is odd

// Encrypt plaintext
String ciphertext = encrypt(plaintext, key);
[Link]("Ciphertext: " + ciphertext);
}

// Method to encrypt the text using the given matrix


private static String encrypt(String text, int[][] matrix) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < [Link](); i += 2) { // Process the text in blocks of 2 characters
int[] vec = new int[2];
for (int j = 0; j < 2; j++)
vec[j] = [Link](i + j) - 'A'; // Convert each character to a corresponding integer
int[] transformed = multiply(matrix, vec); // Multiply with the key matrix
for (int value : transformed)
[Link]((char) ('A' + (value % 26 + 26) % 26)); // Convert the result to characters and append
}
return [Link]();
}

// Method to multiply a matrix with a vector


private static int[] multiply(int[][] matrix, int[] vec) {
int[] result = new int[2];
for (int i = 0; i < 2; i++) // Multiply row of matrix with the vector
for (int j = 0; j < 2; j++)
result[i] += matrix[i][j] * vec[j]; // Sum the products for each element in the result
return result;
}
}

OUTPUT:
Enter key matrix (2x2):
3325
Enter plaintext: RAVI
Ciphertext: ZIJE

//PROGRAM FOR ENCRYPTION AND DECRYPTION [optional]


import [Link];
public class Main {
private static int[][] key, invKey;
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);
key = new int[2][2];

// Input the 2x2 key matrix


[Link]("Enter key matrix (2x2):");
for (int i = 0; i < 2; i++) // Loop to fill the key matrix
for (int j = 0; j < 2; j++)
key[i][j] = [Link]();

// Input plaintext and format it


[Link]("Enter plaintext: ");
[Link]();
String plaintext = [Link]().toUpperCase().replaceAll("[^A-Z]", ""); // Remove non-alphabet characters
while ([Link]() % 2 != 0) plaintext += 'X'; // Pad plaintext if its length is odd

// Encrypt plaintext
String ciphertext = process(plaintext, key);
[Link]("Ciphertext: " + ciphertext);

// Compute the inverse of the key matrix for decryption


invKey = inverse(key);
if (invKey != null) { // Decrypt ciphertext if the inverse exists
[Link]("Decrypted Text: " + process(ciphertext, invKey));
} else {
[Link]("Invalid key matrix! Cannot decrypt.");
}
[Link]();
}

// Method to process (encrypt/decrypt) the text using the given matrix


private static String process(String text, int[][] matrix) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < [Link](); i += 2) { // Process the text in blocks of 2 characters
int[] vec = new int[2];
for (int j = 0; j < 2; j++)
vec[j] = [Link](i + j) - 'A'; // Convert each character to a corresponding integer
int[] transformed = multiply(matrix, vec); // Multiply with the key matrix
for (int value : transformed)
[Link]((char) ('A' + (value % 26 + 26) % 26)); // Convert the result to characters and append
}
return [Link]();
}

// Method to multiply a matrix with a vector


private static int[] multiply(int[][] matrix, int[] vec) {
int[] result = new int[2];
for (int i = 0; i < 2; i++) // Multiply row of matrix with the vector
for (int j = 0; j < 2; j++)
result[i] += matrix[i][j] * vec[j]; // Sum the products for each element in the result
return result;
}

// Method to calculate the inverse of a 2x2 matrix


private static int[][] inverse(int[][] matrix) {
// Calculate the determinant of the 2x2 matrix modulo 26
int det = (matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]) % 26;
if (det < 0) det += 26; // Ensure the determinant is positive
int detInv = modInverse(det, 26); // Find the modular inverse of the determinant
if (detInv == -1) return null; // If no modular inverse exists, return null (invalid matrix)
// Return the inverse matrix using the formula for 2x2 matrix inverse
return new int[][]{
{matrix[1][1] * detInv % 26, (-matrix[0][1] + 26) * detInv % 26}, // First row of inverse
{(-matrix[1][0] + 26) * detInv % 26, matrix[0][0] * detInv % 26} // Second row of inverse
};
}
// Method to find the modular inverse of a number `a` modulo `m`
private static int modInverse(int a, int m) {
for (int x = 1; x < m; x++) // Iterate through values to find the inverse
if ((a * x) % m == 1) return x; // Return the inverse if found
return -1; // Return -1 if no modular inverse exists
}
}

OUTPUT:
Enter key matrix (2x2):
3325
Enter plaintext: RAVI
Ciphertext: ZIJE
Decrypted Text: RAVI

You might also like