1. Implement the following SUBSTITUTION & TRANSPOSITION TECHNIQUES.
(a). Caesar Cipher
import java.util.Scanner;
public class CaesarCipherExample
{
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static String encryptData(String inputStr, int shiftKey)
{
inputStr = inputStr.toLowerCase();
String encryptStr = "";
for (int i = 0; i < inputStr.length(); i++)
{
int pos = ALPHABET.indexOf(inputStr.charAt(i));
int encryptPos = (shiftKey + pos) % 26;
char encryptChar = ALPHABET.charAt(encryptPos);
encryptStr += encryptChar;
}
return encryptStr;
}
public static String decryptData(String inputStr, int shiftKey)
{
inputStr = inputStr.toLowerCase();
String decryptStr = "";
for (int i = 0; i < inputStr.length(); i++)
{
int pos = ALPHABET.indexOf(inputStr.charAt(i));
int decryptPos = (pos - shiftKey) % 26;
if (decryptPos < 0){
decryptPos = ALPHABET.length() + decryptPos;
}
char decryptChar = ALPHABET.charAt(decryptPos);
decryptStr += decryptChar;
}
return decryptStr;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter a string for encryption using Caesar
Cipher: ");
String inputStr = sc.nextLine();
System.out.println("Enter the value by which each character in
the plaintext message gets shifted: ");
int shiftKey = Integer.valueOf(sc.nextLine());
System.out.println("Encrypted Data ===> "+encryptData(inputStr,
shiftKey));
System.out.println("Decrypted Data ===>
"+decryptData(encryptData(inputStr, shiftKey), shiftKey));
sc.close();
}
}
(b) Playfair Cipher
import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher
{
private int length = 0;
private String [][] table;
public static void main(String args[])
{
PlayfairCipher pf = new PlayfairCipher();
}
private PlayfairCipher()
{
System.out.print("Enter the key for playfair cipher: ");
Scanner sc = new Scanner(System.in);
String key = parseString(sc);
while(key.equals(""))
key = parseString(sc);
table = this.cipherTable(key);
System.out.print("Enter the plaintext to be encipher: ");
String input = parseString(sc);
while(input.equals(""))
input = parseString(sc);
String output = cipher(input);
String decodedOutput = decode(output);
this.keyTable(table);
this.printResults(output,decodedOutput);
}
private String parseString(Scanner sc)
{
String parse = sc.nextLine();
parse = parse.toUpperCase();
parse = parse.replaceAll("[^A-Z]", "");
parse = parse.replace("J", "I");
return parse;
}
private String[][] cipherTable(String key)
{
String[][] playfairTable = new String[5][5];
String keyString = key + "ABCDEFGHIKLMNOPQRSTUVWXYZ";
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
playfairTable[i][j] = "";
for(int k = 0; k < keyString.length(); k++)
{
boolean repeat = false;
boolean used = false;
for(int i = 0; i < 5; i++)
{
for(int j = 0; j < 5; j++)
{
if(playfairTable[i][j].equals("" + keyString.charAt(k)))
{
repeat = true;
}
else if(playfairTable[i][j].equals("") && !repeat && !used)
{
playfairTable[i][j] = "" + keyString.charAt(k);
used = true;
}
}
}
}
return playfairTable;
}
private String cipher(String in)
{
length = (int) in.length() / 2 + in.length() % 2;
for(int i = 0; i < (length - 1); i++)
{
if(in.charAt(2 * i) == in.charAt(2 * i + 1))
{
in = new StringBuffer(in).insert(2 * i + 1, 'X').toString();
length = (int) in.length() / 2 + in.length() % 2;
}
}
String[] digraph = new String[length];
for(int j = 0; j < length ; j++)
{
if(j == (length - 1) && in.length() / 2 == (length - 1))
in = in + "X";
digraph[j] = in.charAt(2 * j) +""+ in.charAt(2 * j + 1);
}
String out = "";
String[] encDigraphs = new String[length];
encDigraphs = encodeDigraph(digraph);
for(int k = 0; k < length; k++)
out = out + encDigraphs[k];
return out;
}
private String[] encodeDigraph(String di[])
{
String[] encipher = new String[length];
for(int i = 0; i < length; i++)
{
char a = di[i].charAt(0);
char b = di[i].charAt(1);
int r1 = (int) getPoint(a).getX();
int r2 = (int) getPoint(b).getX();
int c1 = (int) getPoint(a).getY();
int c2 = (int) getPoint(b).getY();
if(r1 == r2)
{
c1 = (c1 + 1) % 5;
c2 = (c2 + 1) % 5;
}
else if(c1 == c2)
{
r1 = (r1 + 1) % 5;
r2 = (r2 + 1) % 5;
}
else
{
int temp = c1;
c1 = c2;
c2 = temp;
}
encipher[i] = table[r1][c1] + "" + table[r2][c2];
}
return encipher;
}
private String decode(String out)
{
String decoded = "";
for(int i = 0; i < out.length() / 2; i++)
{
char a = out.charAt(2*i);
char b = out.charAt(2*i+1);
int r1 = (int) getPoint(a).getX();
int r2 = (int) getPoint(b).getX();
int c1 = (int) getPoint(a).getY();
int c2 = (int) getPoint(b).getY();
if(r1 == r2)
{
c1 = (c1 + 4) % 5;
c2 = (c2 + 4) % 5;
}
else if(c1 == c2)
{
r1 = (r1 + 4) % 5;
r2 = (r2 + 4) % 5;
}
else
{
int temp = c1;
c1 = c2;
c2 = temp;
}
decoded = decoded + table[r1][c1] + table[r2][c2];
}
return decoded;
}
private Point getPoint(char c)
{
Point pt = new Point(0,0);
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
if(c == table[i][j].charAt(0))
pt = new Point(i,j);
return pt;
}
private void keyTable(String[][] printTable)
{
System.out.println("Playfair Cipher Key Matrix: ");
System.out.println();
for(int i = 0; i < 5; i++) {
for(int j = 0; j < 5; j++)
{
System.out.print(printTable[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
private void printResults(String encipher, String dec)
{
System.out.print("Encrypted Message: ");
System.out.println(encipher);
System.out.println();
System.out.print("Decrypted Message: ");
System.out.println(dec);
}
}
(c) Hill Cipher
import java.util.ArrayList;
import java.util.Scanner;
public class HillCipherExample {
private static int[][] getKeyMatrix() {
Scanner sc = new Scanner(System.in);
System.out.println("Enter key matrix:");
String key = sc.nextLine();
double sq = Math.sqrt(key.length());
if (sq != (long) sq) {
System.out.println("Cannot Form a square matrix");
}
int len = (int) sq;
int[][] keyMatrix = new int[len][len];
int k = 0;
for (int i = 0; i < len; i++)
{
for (int j = 0; j < len; j++)
{
keyMatrix[i][j] = ((int) key.charAt(k)) - 97;
k++;
}
}
return keyMatrix;
}
private static void isValidMatrix(int[][] keyMatrix) {
int det = keyMatrix[0][0] * keyMatrix[1][1] - keyMatrix[0][1] *
keyMatrix[1][0];
if(det == 0) {
throw new java.lang.Error("Det equals to zero, invalid key
matrix!");
}
}
private static void isValidReverseMatrix(int[][] keyMatrix,
int[][] reverseMatrix) {
int[][] product = new int[2][2];
product[0][0] = (keyMatrix[0][0]*reverseMatrix[0][0] +
keyMatrix[0][1] * reverseMatrix[1][0]) % 26;
product[0][1] = (keyMatrix[0][0]*reverseMatrix[0][1] +
keyMatrix[0][1] * reverseMatrix[1][1]) % 26;
product[1][0] = (keyMatrix[1][0]*reverseMatrix[0][0] +
keyMatrix[1][1] * reverseMatrix[1][0]) % 26;
product[1][1] = (keyMatrix[1][0]*reverseMatrix[0][1] +
keyMatrix[1][1] * reverseMatrix[1][1]) % 26;
if(product[0][0] != 1 || product[0][1] != 0 || product[1][0] !=
0 || product[1][1] != 1) {
throw new java.lang.Error("Invalid reverse matrix found!");
}
}
private static int[][] reverseMatrix(int[][] keyMatrix) {
int detmod26 = (keyMatrix[0][0] * keyMatrix[1][1] -
keyMatrix[0][1] * keyMatrix[1][0]) % 26; // Calc det
int factor;
int[][] reverseMatrix = new int[2][2];
for(factor=1; factor < 26; factor++)
{
if((detmod26 * factor) % 26 == 1)
{
break;
}
}
reverseMatrix[0][0] = keyMatrix[1][1] * factor % 26;
reverseMatrix[0][1] = (26 - keyMatrix[0][1]) * factor % 26;
reverseMatrix[1][0] = (26 - keyMatrix[1][0]) * factor % 26;
reverseMatrix[1][1] = keyMatrix[0][0] * factor % 26;
return reverseMatrix;
}
private static void echoResult(String label, int adder,
ArrayList<Integer> phrase) {
int i;
System.out.print(label);
for(i=0; i < phrase.size(); i += 2) {
System.out.print(Character.toChars(phrase.get(i) + (64 +
adder)));
System.out.print(Character.toChars(phrase.get(i+1) + (64 +
adder)));
if(i+2 <phrase.size()) {
System.out.print("-");
}
}
System.out.println();
}
public static void encrypt(String phrase, boolean alphaZero)
{
int i;
int adder = alphaZero ? 1 : 0;
int[][] keyMatrix;
ArrayList<Integer> phraseToNum = new ArrayList<>();
ArrayList<Integer> phraseEncoded = new ArrayList<>();
phrase = phrase.replaceAll("[^a-zA-Z]","").toUpperCase();
if(phrase.length() % 2 == 1) {
phrase += "Q";
}
keyMatrix = getKeyMatrix();
isValidMatrix(keyMatrix);
for(i=0; i < phrase.length(); i++) {
phraseToNum.add(phrase.charAt(i) - (64 + adder));
}
for(i=0; i < phraseToNum.size(); i += 2) {
int x = (keyMatrix[0][0] * phraseToNum.get(i) +
keyMatrix[0][1] * phraseToNum.get(i+1)) % 26;
int y = (keyMatrix[1][0] * phraseToNum.get(i) +
keyMatrix[1][1] * phraseToNum.get(i+1)) % 26;
phraseEncoded.add(alphaZero ? x : (x == 0 ? 26 : x ));
phraseEncoded.add(alphaZero ? y : (y == 0 ? 26 : y ));
}
echoResult("Encoded phrase: ", adder, phraseEncoded);
}
public static void decrypt(String phrase, boolean alphaZero)
{
int i, adder = alphaZero ? 1 : 0;
int[][] keyMatrix, revKeyMatrix;
ArrayList<Integer> phraseToNum = new ArrayList<>();
ArrayList<Integer> phraseDecoded = new ArrayList<>();
phrase = phrase.replaceAll("[^a-zA-Z]","").toUpperCase();
keyMatrix = getKeyMatrix();
isValidMatrix(keyMatrix);
for(i=0; i < phrase.length(); i++) {
phraseToNum.add(phrase.charAt(i) - (64 + adder));
}
revKeyMatrix = reverseMatrix(keyMatrix);
isValidReverseMatrix(keyMatrix, revKeyMatrix);
for(i=0; i < phraseToNum.size(); i += 2) {
phraseDecoded.add((revKeyMatrix[0][0] * phraseToNum.get(i)
+ revKeyMatrix[0][1] * phraseToNum.get(i+1)) % 26);
phraseDecoded.add((revKeyMatrix[1][0] * phraseToNum.get(i)
+ revKeyMatrix[1][1] * phraseToNum.get(i+1)) % 26);
}
echoResult("Decoded phrase: ", adder, phraseDecoded);
}
public static void main(String[] args) {
String opt, phrase;
byte[] p;
Scanner sc = new Scanner(System.in);
System.out.println("Hill Cipher Implementation (2x2)");
System.out.println("-------------------------");
System.out.println("1. Encrypt text (A=0,B=1,...Z=25)");
System.out.println("2. Decrypt text (A=0,B=1,...Z=25)");
System.out.println("3. Encrypt text (A=1,B=2,...Z=26)");
System.out.println("4. Decrypt text (A=1,B=2,...Z=26)");
System.out.println();
System.out.println("Type any other character to exit");
System.out.println();
System.out.print("Select your choice: ");
opt = sc.nextLine();
switch (opt)
{
case "1":
System.out.print("Enter phrase to encrypt: ");
phrase = sc.nextLine();
encrypt(phrase, true);
break;
case "2":
System.out.print("Enter phrase to decrypt: ");
phrase = sc.nextLine();
decrypt(phrase, true);
break;
case "3":
System.out.print("Enter phrase to encrypt: ");
phrase = sc.nextLine();
encrypt(phrase, false);
break;
case "4":
System.out.print("Enter phrase to decrypt: ");
phrase = sc.nextLine();
decrypt(phrase, false);
break;
}
}
}
(d).Rail fence
import java.util.*;
class RailFenceBasic{
int depth;
String Encryption(String plainText,int depth)throws Exception
{
int r=depth,len=plainText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String cipherText="";
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
if(k!=len)
mat[j][i]=plainText.charAt(k++);
else
mat[j][i]='X';
}
}
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
cipherText+=mat[i][j];
}
}
return cipherText;
}
String Decryption(String cipherText,int depth)throws Exception
{
int r=depth,len=cipherText.length();
int c=len/depth;
char mat[][]=new char[r][c];
int k=0;
String plainText="";
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
mat[i][j]=cipherText.charAt(k++);
}
}
for(int i=0;i< c;i++)
{
for(int j=0;j< r;j++)
{
plainText+=mat[j][i];
}
}
return plainText;
}
}
class RailFence{
public static void main(String args[])throws Exception
{
RailFenceBasic rf=new RailFenceBasic();
Scanner scn=new Scanner(System.in);
int depth;
String plainText,cipherText,decryptedText;
System.out.println("Enter plain text:");
plainText=scn.nextLine();
System.out.println("Enter depth for Encryption:");
depth=scn.nextInt();
cipherText=rf.Encryption(plainText,depth);
System.out.println("Encrypted text is:\n"+cipherText);
decryptedText=rf.Decryption(cipherText, depth);
System.out.println("Decrypted text is:\n"+decryptedText);
}
}
Output.