0% found this document useful (0 votes)
45 views15 pages

Css Exp 01

This Java code implements a Playfair cipher encryption and decryption algorithm. It takes a keyword as input to generate a 5x5 matrix for the cipher. It then encrypts a plaintext message by dividing it into digraphs (pairs of letters) and using the matrix to map each pair to an encrypted pair based on their positions in the matrix. It outputs both the encrypted and decrypted ciphertexts. The code prompts the user for a keyword and plaintext, generates the cipher matrix, encrypts the message, decodes it back to plaintext, and displays the results.

Uploaded by

Apurva Ankushrao
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)
45 views15 pages

Css Exp 01

This Java code implements a Playfair cipher encryption and decryption algorithm. It takes a keyword as input to generate a 5x5 matrix for the cipher. It then encrypts a plaintext message by dividing it into digraphs (pairs of letters) and using the matrix to map each pair to an encrypted pair based on their positions in the matrix. It outputs both the encrypted and decrypted ciphertexts. The code prompts the user for a keyword and plaintext, generates the cipher matrix, encrypts the message, decodes it back to plaintext, and displays the results.

Uploaded by

Apurva Ankushrao
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
You are on page 1/ 15

Code: -

import javax.swing.*;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashTutorial {

//Constructor of class, calls compare() function


HashTutorial(){
compare();
}

//Take in a String throw JOptionpane, convert to Integer and hash it, then run brute force
until a match for the
// int is found
static void compare(){
//Declared as null because assignment bellow happens in a try-catch which could
(theoretically) fail
byte[] userDefined=null;
//Same thing as above goes for the Integer
int inp=0;
try{
//Try to parse the entered String to an Integer and then hash it
inp = Integer.parseInt(JOptionPane.showInputDialog(null,"Please enter your
integer!"));
userDefined=hash(inp);
}
//Should the parsing or the hash fail, the function will call itself and start over
catch(Exception e){
compare();
}
//Check if the Integer is smaller than 0, if it is, start over
if(inp<0){
try {
//JOptionPane can throw a NullPointerException when clicking on window x, so
we use a try-catch statement
//to eliminate a potential software termination
JOptionPane.showMessageDialog(null, "The integer must be bigger than or equal
to 0!");
}
//Should an exception be thrown, the program will terminate. Replace with compare();
if you would like
//it to try again instead of stopping
catch(NullPointerException e){
System.exit(-1);
}
//if the input is smaller than 0, start over
compare();
}

//Brute force starts here. Start at int 0, and goes till the integer size limit is reached,
calculating the hash
//of each integer and comparing it to the input's hash. If a match is found, it prints out
the input in plain text.
for(int i=0;i<2147483647;i++){
//Print out the current integer, it's good to have an overview if you enter a higher
valued integer that
// takes longer
System.out.println(i);
//Check if the current integer's hash matches the input's hash
if(MessageDigest.isEqual(hash(i),userDefined)){
//if a match is found, print the integer in plain text. Again, try catch is for the
JOptionPane
try {
JOptionPane.showMessageDialog(null, "Found a match for " + i);
}
catch(Exception e){
System.out.println("Found a match for " + i);
}
//and terminate the program
System.exit(0);
break;
}
}
//This statement is only reached if no match is found
System.out.println("No match found!");
}

//Hashing function. Takes an Integer input and returns the hash as a byte array
static byte[] hash(int input){
//Because assignment is in a try-catch statement, we set the start value to null
byte[] output=null;
//Convert the integer input to a String, because the hash function uses a String
String inp=Integer.toString(input);
//try-catch because misspelling the Algorithm type will return a
NoSuchAlgorithmException
try{
//Set hash algorithm type
MessageDigest digest = MessageDigest.getInstance("SHA-256");
//Calculate the inputs hash as a byte array, and assign it to the variable output
output = digest.digest(inp.getBytes(StandardCharsets.UTF_8));
}
//Catch NoSuchAlgorithmException
catch(NoSuchAlgorithmException e){
e.printStackTrace();
}
//return the byte array
return output;
}

//Finally, the main method, obviously...


public static void main(String[] args){
new HashTutorial();
}
}
Output: -
Code: -
// import required classes and package, if any
import java.util.Scanner;
// create class CaesarCipherExample for encryption and decryption
public class Main
{
// ALPHABET string denotes alphabet from a-z
public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
// create encryptData() method for encrypting user input string with given shift key
public static String encryptData(String inputStr, int shiftKey)
{
// convert inputStr into lower case
inputStr = inputStr.toLowerCase();
// encryptStr to store encrypted data
String encryptStr = "";
// use for loop for traversing each character of the input string
for (int i = 0; i < inputStr.length(); i++)
{
// get position of each character of inputStr in ALPHABET
int pos = ALPHABET.indexOf(inputStr.charAt(i));
// get encrypted char for each char of inputStr
int encryptPos = (shiftKey + pos) % 26;
char encryptChar = ALPHABET.charAt(encryptPos);
// add encrypted char to encrypted string
encryptStr += encryptChar;
}
// return encrypted string
return encryptStr;
}
// create decryptData() method for decrypting user input string with given shift key
public static String decryptData(String inputStr, int shiftKey)
{
// convert inputStr into lower case
inputStr = inputStr.toLowerCase();
// decryptStr to store decrypted data
String decryptStr = "";
// use for loop for traversing each character of the input string
for (int i = 0; i < inputStr.length(); i++)
{
// get position of each character of inputStr in ALPHABET
int pos = ALPHABET.indexOf(inputStr.charAt(i));
// get decrypted char for each char of inputStr
int decryptPos = (pos - shiftKey) % 26;
// if decryptPos is negative
if (decryptPos < 0){
decryptPos = ALPHABET.length() + decryptPos;
}
char decryptChar = ALPHABET.charAt(decryptPos);
// add decrypted char to decrypted string
decryptStr += decryptChar;
}
// return decrypted string
return decryptStr;
}
// main() method start
public static void main(String[] args)
{
// create an instance of Scanner class
Scanner sc = new Scanner(System.in);
// take input from the user
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));
// close Scanner class object
sc.close();
}
}

Output:-
Code: -
import java.awt.Point;
import java.util.Scanner;
public class PlayfairCipher
{
//length of digraph array
private int length = 0;
//creates a matrix for Playfair 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 the user for the keyword to use for encoding & creates tables
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);
//prompts the user for the message to be encoded
System.out.print("Enter the plaintext to be enciphered: ");
//System.out.println("using the previously given keyword");
String input = parseString(sc);
while(input.equals(""))
input = parseString(sc);
//encodes and then decodes the encoded message
String output = cipher(input);
String decodedOutput = decode(output);
//output the results to a user
this.keyTable(table);
this.printResults(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 = sc.nextLine();
//converts all the letters in upper case
parse = parse.toUpperCase();
//the string to be substituted by space for each match (A to Z)
parse = parse.replaceAll("[^A-Z]", "");
//replace the letter J by I
parse = parse.replace("J", "I");
return parse;
}
//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 the empty string
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;
}
//cipher: takes input (all upper-case), encodes it, and returns the output
private String cipher(String in)
{
length = (int) in.length() / 2 + in.length() % 2;
//insert x between double-letter digraphs & redefines "length"

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;
}
}
//------------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 whether the plaintext is of even length or not
if(j == (length - 1) && in.length() / 2 == (length - 1))
//if not addends X at the end of the plaintext
in = in + "X";
digraph[j] = in.charAt(2 * j) +""+ in.charAt(2 * j + 1);
}
//encodes the digraphs and returns the output
String out = "";
String[] encDigraphs = new String[length];
encDigraphs = encodeDigraph(digraph);
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)
{
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 rows 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];
}
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 < 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
{
//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)
{
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)
{
System.out.println("Playfair Cipher Key Matrix: ");
System.out.println();
//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
System.out.print(printTable[i][j]+" ");
}
System.out.println();
}
System.out.println();
}
//method that prints all the results
private void printResults(String encipher, String dec)
{
System.out.print("Encrypted Message: ");
//prints the encrypted message
System.out.println(encipher);
System.out.println();
System.out.print("Decrypted Message: ");
//prints the decrypted message
System.out.println(dec);
}
}

Output: -
Code:
// This program calculates the Key for two persons
// using the Diffie-Hellman Key exchange algorithm
class Main{
// Power function to return value of a ^ b mod P
private static long power(long a, long b, long p)
{
if (b == 1)
return a;
else
return (((long)Math.pow(a, b)) % p);
}
// Driver code
public static void main(String[] args)
{
long P, G, x, a, y, b, ka, kb;
// Both the persons will be agreed upon the
// public keys G and P
// A prime number P is taken
P = 23;
System.out.println("The value of P:" + P);
// A primitive root for P, G is taken
G = 9;
System.out.println("The value of G:" + G);
// Alice will choose the private key a
// a is the chosen private key
a = 4;
System.out.println("The private key a for Alice:" + a);
// Gets the generated key
x = power(G, a, P);
// Bob will choose the private key b
// b is the chosen private key
b = 3;
System.out.println("The private key b for Bob:" + b);
// Gets the generated key
y = power(G, b, P);
// Generating the secret key after the exchange
// of keys
ka = power(y, a, P); // Secret key for Alice
kb = power(x, b, P); // Secret key for Bob
System.out.println("Secret key for the Alice is:" + ka);
System.out.println("Secret key for the Bob is:" + kb);
}
}
Output:

You might also like