0% found this document useful (0 votes)
165 views28 pages

Cipher

The document outlines the implementation of three ciphers: Playfair, Hill, and Vigenere, using Java code. It provides detailed algorithms and code snippets for each cipher, including steps for encryption and decryption processes. The Playfair cipher focuses on creating a 5x5 matrix for encoding, while the Hill cipher emphasizes the use of a key matrix for transformations based on linear algebra.

Uploaded by

mageshproject123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
165 views28 pages

Cipher

The document outlines the implementation of three ciphers: Playfair, Hill, and Vigenere, using Java code. It provides detailed algorithms and code snippets for each cipher, including steps for encryption and decryption processes. The Playfair cipher focuses on creating a 5x5 matrix for encoding, while the Hill cipher emphasizes the use of a key matrix for transformations based on linear algebra.

Uploaded by

mageshproject123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Playfair cipher, Hill cipher and

vigenere cipher
NAME :Magesh

RRN :2001816
01013

[Link] CIPHER
AIM:

TO FIND THE PLAYFAIR CIPHER PROGRAM USING JAVA CODE

ALGORITHM:

STEP1 : TO START THE PROGRAM

STEP2 :ENTER THE CLASS NAME

STEP3 :ENTER KEY AND PLAINTEXT

STEP4 :USE FOR LOOP FOR THE TABLE

STEP5 :PRINT THE CIPHER KEY

STEP6 :END THE PROGRAM

PROGRAM:

import [Link];

import [Link];

public class PlayfairCipher

//length of digraph array

private int length = 0;

//creates a matrix for Playfair cipher


Playfair cipher, Hill cipher and
vigenere cipher
private String [][] table;

//main() method to test Playfair method

public static void main(String args[])

PlayfairCipher pf = new PlayfairCipher();

//main run of the program, Playfair method

//constructor of the class

private PlayfairCipher()

//prompts user for the keyword to use for encoding & creates tables

[Link]("Enter the key for playfair cipher: ");

Scanner sc = new Scanner([Link]);

String key = parseString(sc);

while([Link](""))

key = parseString(sc);

table = [Link](key);

//prompts user for message to be encoded

[Link]("Enter the plaintext to be encipher: ");

//[Link]("using the previously given keyword");

String input = parseString(sc);


Playfair cipher, Hill cipher and
vigenere cipher
while([Link](""))

input = parseString(sc);

//encodes and then decodes the encoded message

String output = cipher(input);

String decodedOutput = decode(output);

//output the results to user

[Link](table);

[Link](output,decodedOutput);

//parses an input string to remove numbers, punctuation,

//replaces any J's with I's and makes string all caps

private String parseString(Scanner sc)

String parse = [Link]();

//converts all the letters in upper case

parse = [Link]();

//the string to be substituted by space for each match (A to Z)

parse = [Link]("[^A-Z]", "");

//replace the letter J by I

parse = [Link]("J", "I");

return parse;
Playfair cipher, Hill cipher and
vigenere cipher
}

//creates the cipher table based on some input string (already parsed)

private String[][] cipherTable(String key)

//creates a matrix of 5*5

String[][] playfairTable = new String[5][5];

String keyString = key + "ABCDEFGHIKLMNOPQRSTUVWXYZ";

//fill string array with empty string

for(int i = 0; i < 5; i++)

for(int j = 0; j < 5; j++)

playfairTable[i][j] = "";

for(int k = 0; k < [Link](); 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("" + [Link](k)))

{
Playfair cipher, Hill cipher and
vigenere cipher
repeat = true;

else if(playfairTable[i][j].equals("") && !repeat && !used)

playfairTable[i][j] = "" + [Link](k);

used = true;

return playfairTable;

//cipher: takes input (all upper-case), encodes it, and returns the output

private String cipher(String in)

length = (int) [Link]() / 2 + [Link]() % 2;

//insert x between double-letter digraphs & redefines "length"

for(int i = 0; i < (length - 1); i++)

if([Link](2 * i) == [Link](2 * i + 1))


Playfair cipher, Hill cipher and
vigenere cipher
{

in = new StringBuffer(in).insert(2 * i + 1, 'X').toString();

length = (int) [Link]() / 2 + [Link]() % 2;

//------------makes plaintext of even length--------------

//creates an array of digraphs

String[] digraph = new String[length];

//loop iterates over the plaintext

for(int j = 0; j < length ; j++)

//checks the plaintext is of even length or not

if(j == (length - 1) && [Link]() / 2 == (length - 1))

//if not addends X at the end of the plaintext

in = in + "X";

digraph[j] = [Link](2 * j) +""+ [Link](2 * j + 1);

//encodes the digraphs and returns the output

String out = "";

String[] encDigraphs = new String[length];

encDigraphs = encodeDigraph(digraph);
Playfair cipher, Hill cipher and
vigenere cipher
for(int k = 0; k < length; k++)

out = out + encDigraphs[k];

return out;

//---------------encryption logic-----------------

//encodes the digraph input with the cipher's specifications

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();

//executes if the letters of digraph appear in the same row

//in such case shift columns to right

if(r1 == r2)

{
Playfair cipher, Hill cipher and
vigenere cipher
c1 = (c1 + 1) % 5;

c2 = (c2 + 1) % 5;

//executes if the letters of digraph appear in the same column

//in such case shift rows down

else if(c1 == c2)

r1 = (r1 + 1) % 5;

r2 = (r2 + 1) % 5;

//executes if the letters of digraph appear in the different row and different
column

//in such case swap the first column with the second column

else

int temp = c1;

c1 = c2;

c2 = temp;

//performs the table look-up and puts those values into the encoded array

encipher[i] = table[r1][c1] + "" + table[r2][c2];


Playfair cipher, Hill cipher and
vigenere cipher
}

return encipher;

//-----------------------decryption logic---------------------

// decodes the output given from the cipher and decode methods (opp. of
encoding process)

private String decode(String out)

String decoded = "";

for(int i = 0; i < [Link]() / 2; i++)

char a = [Link](2*i);

char b = [Link](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;
Playfair cipher, Hill cipher and
vigenere cipher
}

else if(c1 == c2)

r1 = (r1 + 4) % 5;

r2 = (r2 + 4) % 5;

else

//swapping logic

int temp = c1;

c1 = c2;

c2 = temp;

decoded = decoded + table[r1][c1] + table[r2][c2];

//returns the decoded message

return decoded;

// returns a point containing the row and column of the letter

private Point getPoint(char c)

{
Playfair cipher, Hill cipher and
vigenere cipher
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;

//function prints the key-table in matrix form for playfair cipher

private void keyTable(String[][] printTable)

[Link]("Playfair Cipher Key Matrix: ");

[Link]();

//loop iterates for rows

for(int i = 0; i < 5; i++)

//loop iterates for column

for(int j = 0; j < 5; j++)

//prints the key-table in matrix form

[Link](printTable[i][j]+" ");

}
Playfair cipher, Hill cipher and
vigenere cipher
[Link]();

[Link]();

//method that prints all the results

private void printResults(String encipher, String dec)

[Link]("Encrypted Message: ");

//prints the encrypted message

[Link](encipher);

[Link]();

[Link]("Decrypted Message: ");

//prints the decryted message

[Link](dec);

OUTPUT:
Playfair cipher, Hill cipher and
vigenere cipher

[Link] CIPHER
AIM:

TO FIND THE HILL CIPHER PROGRAM USING JAVA CODE

ALGORITHM:

STEP1 : TO START THE PROGRAM


Playfair cipher, Hill cipher and
vigenere cipher
STEP2 :ENTER THE CLASS NAME

STEP3 :ENTER KEY MATRIX

STEP4 :USE FOR LOOP AND SWITCH CASE THE TABLE

STEP5 :PRINT THE ENCRYPT AND DECRYPT

STEP6 :END THE PROGRAM

PROGRAM:

import [Link];

import [Link];

public class HillCipherExample {

//method to accept key matrix

private static int[][] getKeyMatrix() {

Scanner sc = new Scanner([Link]);

[Link]("Enter key matrix:");

String key = [Link]();

//int len = [Link]();

double sq = [Link]([Link]());

if (sq != (long) sq) {

[Link]("Cannot Form a square matrix");

int len = (int) sq;

int[][] keyMatrix = new int[len][len];


Playfair cipher, Hill cipher and
vigenere cipher
int k = 0;

for (int i = 0; i < len; i++)

for (int j = 0; j < len; j++)

keyMatrix[i][j] = ((int) [Link](k)) - 97;

k++;

return keyMatrix;

// Below method checks whether the key matrix is valid (det=0)

private static void isValidMatrix(int[][] keyMatrix) {

int det = keyMatrix[0][0] * keyMatrix[1][1] - keyMatrix[0][1] * keyMatrix[1]


[0];

// If det=0, throw exception and terminate

if(det == 0) {

throw new [Link]("Det equals to zero, invalid key matrix!");

}
Playfair cipher, Hill cipher and
vigenere cipher
// This method checks if the reverse key matrix is valid (matrix mod26 =
(1,0,0,1)

private static void isValidReverseMatrix(int[][] keyMatrix, int[][]


reverseMatrix) {

int[][] product = new int[2][2];

// Find the product matrix of key matrix times reverse key matrix

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;

// Check if a=1 and b=0 and c=0 and d=1

// If not, throw exception and terminate

if(product[0][0] != 1 || product[0][1] != 0 || product[1][0] != 0 || product[1]


[1] != 1) {

throw new [Link]("Invalid reverse matrix found!");

// This method calculates the reverse key matrix

private static int[][] reverseMatrix(int[][] keyMatrix) {


Playfair cipher, Hill cipher and
vigenere cipher
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];

// Find the factor for which is true that

// factor*det = 1 mod 26

for(factor=1; factor < 26; factor++)

if((detmod26 * factor) % 26 == 1)

break;

// Calculate the reverse key matrix elements using the factor found

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;

// This method echoes the result of encrypt/decrypt


Playfair cipher, Hill cipher and
vigenere cipher
private static void echoResult(String label, int adder, ArrayList<Integer> phrase)
{

int i;

[Link](label);

// Loop for each pair

for(i=0; i < [Link](); i += 2) {

[Link]([Link]([Link](i) + (64 + adder)));

[Link]([Link]([Link](i+1) + (64 + adder)));

if(i+2 <[Link]()) {

[Link]("-");

[Link]();

// This method makes the actual encryption

public static void encrypt(String phrase, boolean alphaZero)

int i;

int adder = alphaZero ? 1 : 0; // For calclulations depending on the alphabet

int[][] keyMatrix;

ArrayList<Integer> phraseToNum = new ArrayList<>();


Playfair cipher, Hill cipher and
vigenere cipher
ArrayList<Integer> phraseEncoded = new ArrayList<>();

// Delete all non-english characters, and convert phrase to upper case

phrase = [Link]("[^a-zA-Z]","").toUpperCase();

// If phrase length is not an even number, add "Q" to make it even

if([Link]() % 2 == 1) {

phrase += "Q";

// Get the 2x2 key matrix from sc

keyMatrix = getKeyMatrix();

// Check if the matrix is valid (det != 0)

isValidMatrix(keyMatrix);

// Convert characters to numbers according to their

// place in ASCII table minus 64 positions (A=65 in ASCII table)

// If we use A=0 alphabet, subtract one more (adder)

for(i=0; i < [Link](); i++) {

[Link]([Link](i) - (64 + adder));

// Find the product per pair of the phrase with the key matrix modulo 26

// If we use A=1 alphabet and result is 0, replace it with 26 (Z)

for(i=0; i < [Link](); i += 2) {


Playfair cipher, Hill cipher and
vigenere cipher
int x = (keyMatrix[0][0] * [Link](i) + keyMatrix[0][1] *
[Link](i+1)) % 26;

int y = (keyMatrix[1][0] * [Link](i) + keyMatrix[1][1] *


[Link](i+1)) % 26;

[Link](alphaZero ? x : (x == 0 ? 26 : x ));

[Link](alphaZero ? y : (y == 0 ? 26 : y ));

// Print the result

echoResult("Encoded phrase: ", adder, phraseEncoded);

// This method makes the actual decryption

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<>();

// Delete all non-english characters, and convert phrase to upper case

phrase = [Link]("[^a-zA-Z]","").toUpperCase();

// Get the 2x2 key matrix from sc


Playfair cipher, Hill cipher and
vigenere cipher
keyMatrix = getKeyMatrix();

// Check if the matrix is valid (det != 0)

isValidMatrix(keyMatrix);

// Convert numbers to characters according to their

// place in ASCII table minus 64 positions (A=65 in ASCII table)

// If we use A=0 alphabet, subtract one more (adder)

for(i=0; i < [Link](); i++) {

[Link]([Link](i) - (64 + adder));

// Find the reverse key matrix

revKeyMatrix = reverseMatrix(keyMatrix);

// Check if the reverse key matrix is valid (product = 1,0,0,1)

isValidReverseMatrix(keyMatrix, revKeyMatrix);

// Find the product per pair of the phrase with the reverse key matrix modulo
26

for(i=0; i < [Link](); i += 2) {

[Link]((revKeyMatrix[0][0] * [Link](i) +
revKeyMatrix[0][1] * [Link](i+1)) % 26);

[Link]((revKeyMatrix[1][0] * [Link](i) +
revKeyMatrix[1][1] * [Link](i+1)) % 26);

// Print the result


Playfair cipher, Hill cipher and
vigenere cipher
echoResult("Decoded phrase: ", adder, phraseDecoded);

//main method

public static void main(String[] args) {

String opt, phrase;

byte[] p;

Scanner sc = new Scanner([Link]);

[Link]("Hill Cipher Implementation (2x2)");

[Link]("-------------------------");

[Link]("1. Encrypt text (A=0,B=1,...Z=25)");

[Link]("2. Decrypt text (A=0,B=1,...Z=25)");

[Link]("3. Encrypt text (A=1,B=2,...Z=26)");

[Link]("4. Decrypt text (A=1,B=2,...Z=26)");

[Link]();

[Link]("Type any other character to exit");

[Link]();

[Link]("Select your choice: ");

opt = [Link]();

switch (opt)

case "1":
Playfair cipher, Hill cipher and
vigenere cipher
[Link]("Enter phrase to encrypt: ");

phrase = [Link]();

encrypt(phrase, true);

break;

case "2":

[Link]("Enter phrase to decrypt: ");

phrase = [Link]();

decrypt(phrase, true);

break;

case "3":

[Link]("Enter phrase to encrypt: ");

phrase = [Link]();

encrypt(phrase, false);

break;

case "4":

[Link]("Enter phrase to decrypt: ");

phrase = [Link]();

decrypt(phrase, false);

break;

}
Playfair cipher, Hill cipher and
vigenere cipher
}

OUTPUT:
Playfair cipher, Hill cipher and
vigenere cipher
[Link] CIPHER:
AIM:

TO FIND THE VIGENERE CIPHER PROGRAM USING JAVA CODE

ALGORITHM:

STEP1 : TO START THE PROGRAM

STEP2 :ENTER THE CLASS NAME

STEP3 :ENTER PLAINTEXT AND KEYWORD

STEP4 :USE FOR LOOP FOR LENGTH

STEP5 :PRINT THE ENCRYPT AND DECRYPT MESSAGE

STEP6 :END THE PROGRAM

PROGRAM:

public class VigenereCipher

public static void main(String arg[])

String plaintext = "JAVAHUNGRYBLOG";

String keyword = "LEMON";

encryptDecrypt(plaintext,keyword);

}
Playfair cipher, Hill cipher and
vigenere cipher

public static void encryptDecrypt(String plaintext, String keyword)

//Converting plaintext to char array

char msg[] = [Link]();

int msgLen = [Link];

int i,j;

// Creating new char arrays

char key[] = new char[msgLen];

char encryptedMsg[] = new char[msgLen];

char decryptedMsg[] = new char[msgLen];

/* generate key, using keyword in cyclic

manner equal to the length of

original message i.e plaintext */

for(i = 0, j = 0; i < msgLen; ++i, ++j)

if(j == [Link]())

{
Playfair cipher, Hill cipher and
vigenere cipher
j = 0;

key[i] = [Link](j);

//encryption code

for(i = 0; i < msgLen; ++i)

encryptedMsg[i] = (char) (((msg[i] + key[i]) % 26) + 'A');

//decryption code

for(i = 0; i < msgLen; ++i)

decryptedMsg[i] = (char)((((encryptedMsg[i] - key[i]) + 26) % 26) + 'A');

[Link]("Original Message: " + plaintext);

[Link]("Keyword: " + keyword);

/* [Link]() method converts

char[] to String */

[Link]("Key: " + [Link](key));

[Link]();

[Link]("Encrypted Message: " + [Link](encryptedMsg));

[Link]();
Playfair cipher, Hill cipher and
vigenere cipher
[Link]("Decrypted Message: " + [Link](decryptedMsg));

OUTPUT:

You might also like