Ex:1 Caesar Cipher in Cryptography
import java.io.*;
import java.util.*;
public class Solution { //to keep track of index
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String decrypt(String cipherText, int shiftKey) {
cipherText = cipherText.toLowerCase();
String message = "";
for (int ii = 0; ii < cipherText.length(); ii++) {
int charPosition = ALPHABET.indexOf(cipherText.charAt(ii));
int keyVal = (charPosition - shiftKey) % 26;
if (keyVal < 0) {
keyVal = ALPHABET.length() + keyVal;
char replaceVal = ALPHABET.charAt(keyVal);
message += replaceVal;
return message;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String message = new String();
int key = 0;
System.out.print("Enter the String for Encryption:");
message = sc.next();
System.out.println("\n\nEnter Shift Key:");
key = sc.nextInt();
// System.out.println("\nEncrpyted msg:"+encrypt(message, key));
System.out.println("\nDecrypted Message:" + decrypt(message, key));
}
Ex:2 Playfair Cipher
import java.util.Scanner;
public class Main {
private static char[][] matrix = new char[5][5];
private static void generateMatrix(String key) {
boolean[] used = new boolean[26];
key = key.toUpperCase().replaceAll("[^A-Z]", "").replace("J", "I");
int index = 0;
for (char c : key.toCharArray()) {
if (!used[c - 'A']) {
matrix[index / 5][index % 5] = c;
used[c - 'A'] = true;
index++;
for (char c = 'A'; c <= 'Z'; c++) {
if (c != 'J' && !used[c - 'A']) {
matrix[index / 5][index % 5] = c;
index++;
private static String prepareText(String text) {
text = text.toUpperCase().replaceAll("[^A-Z]", "").replace("J", "I");
StringBuilder prepared = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char current = text.charAt(i);
prepared.append(current);
if (i + 1 < text.length() && current == text.charAt(i + 1)) {
prepared.append('X');
if (prepared.length() % 2 != 0) {
prepared.append('X');
return prepared.toString();
private static int[] findPosition(char c) {
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (matrix[i][j] == c) {
return new int[]{i, j};
return null;
private static String encryptPair(char a, char b) {
int[] posA = findPosition(a);
int[] posB = findPosition(b);
if (posA[0] == posB[0]) {
return "" + matrix[posA[0]][(posA[1] + 1) % 5] + matrix[posB[0]][(posB[1] + 1) % 5];
} else if (posA[1] == posB[1]) {
return "" + matrix[(posA[0] + 1) % 5][posA[1]] + matrix[(posB[0] + 1) % 5][posB[1]];
} else {
return "" + matrix[posA[0]][posB[1]] + matrix[posB[0]][posA[1]];
public static String encrypt(String key, String plaintext) {
generateMatrix(key);
String preparedText = prepareText(plaintext);
StringBuilder ciphertext = new StringBuilder();
for (int i = 0; i < preparedText.length(); i += 2) {
ciphertext.append(encryptPair(preparedText.charAt(i), preparedText.charAt(i + 1)));
return ciphertext.toString();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the key: ");
String key = scanner.nextLine();
System.out.print("Enter the plaintext: ");
String plaintext = scanner.nextLine();
String ciphertext = encrypt(key, plaintext);
System.out.println("Ciphertext: " + ciphertext);
scanner.close();
}
EX 3: vigenere cipher
class Main
static String generateKey(String str, String key)
int x = str.length();
for (int i = 0; ; i++)
if (x == i)
i = 0;
if (key.length() == str.length())
break;
key+=(key.charAt(i));
return key;
static String cipherText(String str, String key)
String cipher_text="";
for (int i = 0; i < str.length(); i++)
int x = (str.charAt(i) + key.charAt(i)) %26;
x += 'A';
cipher_text+=(char)(x);
return cipher_text;
static String originalText(String cipher_text, String key)
String orig_text="";
for (int i = 0 ; i < cipher_text.length() &&
i < key.length(); i++)
int x = (cipher_text.charAt(i) -
key.charAt(i) + 26) %26;
x += 'A';
orig_text+=(char)(x);
return orig_text;
static String LowerToUpper(String s)
StringBuffer str =new StringBuffer(s);
for(int i = 0; i < s.length(); i++)
if(Character.isLowerCase(s.charAt(i)))
str.setCharAt(i, Character.toUpperCase(s.charAt(i)));
}
}
s = str.toString();
return s;
public static void main(String[] args)
String Str = "GEEKSFORGEEKS";
String Keyword = "AYUSH";
String str = LowerToUpper(Str);
String keyword = LowerToUpper(Keyword);
String key = generateKey(str, keyword);
String cipher_text = cipherText(str, key);
System.out.println("Ciphertext : " + cipher_text + "\n");
System.out.println("Original/Decrypted Text : “ + originalText(cipher_text, key));
}
EX 4: hill cipher
class Main
static void getKeyMatrix(String key, int keyMatrix[][])
int k = 0;
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
keyMatrix[i][j] = (key.charAt(k)) % 65;
k++;
static void encrypt(int cipherMatrix[][],
int keyMatrix[][],
int messageVector[][])
int x, i, j;
for (i = 0; i < 3; i++)
for (j = 0; j < 1; j++)
cipherMatrix[i][j] = 0;
for (x = 0; x < 3; x++)
cipherMatrix[i][j] +=
keyMatrix[i][x] * messageVector[x][j];
}
cipherMatrix[i][j] = cipherMatrix[i][j] % 26;
static void HillCipher(String message, String key)
int [][]keyMatrix = new int[3][3];
getKeyMatrix(key, keyMatrix);
int [][]messageVector = new int[3][1];
for (int i = 0; i < 3; i++)
messageVector[i][0] = (message.charAt(i)) % 65;
int [][]cipherMatrix = new int[3][1];
encrypt(cipherMatrix, keyMatrix, messageVector);
String CipherText="";
for (int i = 0; i < 3; i++)
CipherText += (char)(cipherMatrix[i][0] + 65);
System.out.print(" Ciphertext:" + CipherText);
public static void main(String[] args)
String message = "ACT";
String key = "GYBNQKURP";
HillCipher(message, key);
}
EX 5: rail fence cipher
// Java program to illustrate Rail Fence Cipher
// Encryption and Decryption
import java.util.Arrays;
class RailFence {
// function to encrypt a message
public static String encryptRailFence(String text, int key)
// create the matrix to cipher plain text
// key = rows , length(text) = columns
char[][] rail = new char[key][text.length()];
// filling the rail matrix to distinguish filled
// spaces from blank ones
for (int i = 0; i < key; i++)
Arrays.fill(rail[i], '\n');
boolean dirDown = false;
int row = 0, col = 0;
for (int i = 0; i < text.length(); i++) {
// check the direction of flow
// reverse the direction if we've just
// filled the top or bottom rail
if (row == 0 || row == key - 1)
dirDown = !dirDown;
// fill the corresponding alphabet
rail[row][col++] = text.charAt(i);
// find the next row using direction flag
if (dirDown)
row++;
else
row--;
// now we can construct the cipher using the rail
// matrix
StringBuilder result = new StringBuilder();
for (int i = 0; i < key; i++)
for (int j = 0; j < text.length(); j++)
if (rail[i][j] != '\n')
result.append(rail[i][j]);
return result.toString();
// This function receives cipher-text and key
// and returns the original text after decryption
public static String decryptRailFence(String cipher,
int key)
// create the matrix to cipher plain text
// key = rows , length(text) = columns
char[][] rail = new char[key][cipher.length()];
// filling the rail matrix to distinguish filled
// spaces from blank ones
for (int i = 0; i < key; i++)
Arrays.fill(rail[i], '\n');
// to find the direction
boolean dirDown = true;
int row = 0, col = 0;
// mark the places with '*'
for (int i = 0; i < cipher.length(); i++) {
// check the direction of flow
if (row == 0)
dirDown = true;
if (row == key - 1)
dirDown = false;
// place the marker
rail[row][col++] = '*';
// find the next row using direction flag
if (dirDown)
row++;
else
row--;
// now we can construct the fill the rail matrix
int index = 0;
for (int i = 0; i < key; i++)
for (int j = 0; j < cipher.length(); j++)
if (rail[i][j] == '*'
&& index < cipher.length())
rail[i][j] = cipher.charAt(index++);
StringBuilder result = new StringBuilder();
row = 0;
col = 0;
for (int i = 0; i < cipher.length(); i++) {
// check the direction of flow
if (row == 0)
dirDown = true;
if (row == key - 1)
dirDown = false;
// place the marker
if (rail[row][col] != '*')
result.append(rail[row][col++]);
// find the next row using direction flag
if (dirDown)
row++;
else
row--;
return result.toString();
public static void main(String[] args)
{
// Encryption
System.out.println("Encrypted Message: ");
System.out.println( encryptRailFence("attack at once", 2));
System.out.println( encryptRailFence("GeeksforGeeks ", 3));
System.out.println( encryptRailFence("defend the east wall", 3));
System.out.println("\nDecrypted Message: ");
System.out.println(decryptRailFence("atc toctaka ne", 2));
System.out.println(decryptRailFence("GsGsekfrek eoe", 3));
System.out.println(decryptRailFence("dnhaweedtees alf tl", 3));