Fix formatting in Ciphers package (#2756)

This commit is contained in:
Yang Libin 2021-10-29 13:19:42 +08:00 committed by GitHub
parent 0503c46680
commit 794719c773
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 1269 additions and 1380 deletions

File diff suppressed because it is too large Load Diff

View File

@ -1,13 +1,8 @@
package Ciphers; package Ciphers;
import javax.crypto.*;
import java.security.InvalidKeyException; import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
/** /**
* This example program shows how AES encryption and decryption can be done in Java. Please note * This example program shows how AES encryption and decryption can be done in Java. Please note
@ -16,82 +11,83 @@ import javax.crypto.SecretKey;
*/ */
public class AESEncryption { public class AESEncryption {
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
/**
* 1. Generate a plain text for encryption 2. Get a secret key (printed in hexadecimal form). In
* actual use this must by encrypted and kept safe. The same key is required for decryption.
*/
public static void main(String[] args) throws Exception {
String plainText = "Hello World";
SecretKey secKey = getSecretEncryptionKey();
byte[] cipherText = encryptText(plainText, secKey);
String decryptedText = decryptText(cipherText, secKey);
System.out.println("Original Text:" + plainText); /**
System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded())); * 1. Generate a plain text for encryption 2. Get a secret key (printed in hexadecimal form). In
System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText)); * actual use this must by encrypted and kept safe. The same key is required for decryption.
System.out.println("Descrypted Text:" + decryptedText); */
} public static void main(String[] args) throws Exception {
String plainText = "Hello World";
SecretKey secKey = getSecretEncryptionKey();
byte[] cipherText = encryptText(plainText, secKey);
String decryptedText = decryptText(cipherText, secKey);
/** System.out.println("Original Text:" + plainText);
* gets the AES encryption key. In your actual programs, this should be safely stored. System.out.println("AES Key (Hex Form):" + bytesToHex(secKey.getEncoded()));
* System.out.println("Encrypted Text (Hex Form):" + bytesToHex(cipherText));
* @return secKey (Secret key that we encrypt using it) System.out.println("Descrypted Text:" + decryptedText);
* @throws NoSuchAlgorithmException (from KeyGenrator) }
*/
public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException { /**
KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES"); * gets the AES encryption key. In your actual programs, this should be safely stored.
aesKeyGenerator.init(128); // The AES key size in number of bits *
return aesKeyGenerator.generateKey(); * @return secKey (Secret key that we encrypt using it)
} * @throws NoSuchAlgorithmException (from KeyGenrator)
*/
/** public static SecretKey getSecretEncryptionKey() throws NoSuchAlgorithmException {
* Encrypts plainText in AES using the secret key KeyGenerator aesKeyGenerator = KeyGenerator.getInstance("AES");
* aesKeyGenerator.init(128); // The AES key size in number of bits
* @return byteCipherText (The encrypted text) return aesKeyGenerator.generateKey();
* @throws NoSuchPaddingException (from Cipher) }
* @throws NoSuchAlgorithmException (from Cipher)
* @throws InvalidKeyException (from Cipher) /**
* @throws BadPaddingException (from Cipher) * Encrypts plainText in AES using the secret key
* @throws IllegalBlockSizeException (from Cipher) *
*/ * @return byteCipherText (The encrypted text)
public static byte[] encryptText(String plainText, SecretKey secKey) * @throws NoSuchPaddingException (from Cipher)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, * @throws NoSuchAlgorithmException (from Cipher)
IllegalBlockSizeException, BadPaddingException { * @throws InvalidKeyException (from Cipher)
// AES defaults to AES/ECB/PKCS5Padding in Java 7 * @throws BadPaddingException (from Cipher)
Cipher aesCipher = Cipher.getInstance("AES"); * @throws IllegalBlockSizeException (from Cipher)
aesCipher.init(Cipher.ENCRYPT_MODE, secKey); */
return aesCipher.doFinal(plainText.getBytes()); public static byte[] encryptText(String plainText, SecretKey secKey)
} throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
IllegalBlockSizeException, BadPaddingException {
/** // AES defaults to AES/ECB/PKCS5Padding in Java 7
* Decrypts encrypted byte array using the key used for encryption. Cipher aesCipher = Cipher.getInstance("AES");
* aesCipher.init(Cipher.ENCRYPT_MODE, secKey);
* @return plainText return aesCipher.doFinal(plainText.getBytes());
*/ }
public static String decryptText(byte[] byteCipherText, SecretKey secKey)
throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, /**
IllegalBlockSizeException, BadPaddingException { * Decrypts encrypted byte array using the key used for encryption.
// AES defaults to AES/ECB/PKCS5Padding in Java 7 *
Cipher aesCipher = Cipher.getInstance("AES"); * @return plainText
aesCipher.init(Cipher.DECRYPT_MODE, secKey); */
byte[] bytePlainText = aesCipher.doFinal(byteCipherText); public static String decryptText(byte[] byteCipherText, SecretKey secKey)
return new String(bytePlainText); throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
} IllegalBlockSizeException, BadPaddingException {
// AES defaults to AES/ECB/PKCS5Padding in Java 7
/** Cipher aesCipher = Cipher.getInstance("AES");
* Convert a binary byte array into readable hex form Old library is deprecated on OpenJdk 11 and aesCipher.init(Cipher.DECRYPT_MODE, secKey);
* this is faster regarding other solution is using StringBuilder byte[] bytePlainText = aesCipher.doFinal(byteCipherText);
* return new String(bytePlainText);
* @return hexHash }
*/
public static String bytesToHex(byte[] bytes) { /**
char[] hexChars = new char[bytes.length * 2]; * Convert a binary byte array into readable hex form Old library is deprecated on OpenJdk 11 and
for (int j = 0; j < bytes.length; j++) { * this is faster regarding other solution is using StringBuilder
int v = bytes[j] & 0xFF; *
hexChars[j * 2] = HEX_ARRAY[v >>> 4]; * @return hexHash
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; */
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
} }
return new String(hexChars);
}
} }

View File

@ -1,36 +1,23 @@
//The key for the Affine cipher consists of 2 numbers, well call them a and b.
// The following discussion assumes the use of a 26 character alphabet (m = 26).
// a should be chosen to be relatively prime to m (i.e. a should have no factors in common with m).
package Ciphers; package Ciphers;
import java.util.Scanner; class AffineCipher {
class AffineCipher // Key values of a and b
{ static int a = 17;
static Scanner in = new Scanner(System.in); static int b = 20;
static String encryptMessage(char[] msg) static String encryptMessage(char[] msg) {
{ /// Cipher Text initially empty
System.out.println("Enter key value a for encryption : ");
int a = in.nextInt();
System.out.println("Enter key value b for encryption : ");
int b = in.nextInt();
/// Initially empty cipher String
String cipher = ""; String cipher = "";
for (int i = 0; i < msg.length; i++) for (int i = 0; i < msg.length; i++) {
{
// Avoid space to be encrypted // Avoid space to be encrypted
/* applying encryption formula ( a x + b ) mod m /* applying encryption formula ( a x + b ) mod m
{here x is msg[i] and m is 26} and added 'A' to {here x is msg[i] and m is 26} and added 'A' to
bring it in range of ascii alphabet[ 65-90 | A-Z ] */ bring it in range of ascii alphabet[ 65-90 | A-Z ] */
if (msg[i] != ' ') if (msg[i] != ' ') {
{
cipher = cipher cipher = cipher
+ (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A'); + (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
} else // append space character } else // else simply append space character
{ {
cipher += msg[i]; cipher += msg[i];
} }
@ -38,42 +25,30 @@ class AffineCipher
return cipher; return cipher;
} }
static String decryptCipher(String cipher) static String decryptCipher(String cipher) {
{
System.out.println("Enter key value a for decryption : ");
int a = in.nextInt();
System.out.println("Enter key value b for decryption : ");
int b = in.nextInt();
String msg = ""; String msg = "";
int a_inv = 0; int a_inv = 0;
int flag = 0; int flag = 0;
//Find a^-1 (the multiplicative inverse of a //Find a^-1 (the multiplicative inverse of a
//in the group of integers modulo m.) //in the group of integers modulo m.)
for (int i = 0; i < 26; i++) for (int i = 0; i < 26; i++) {
{
flag = (a * i) % 26; flag = (a * i) % 26;
// Check if (a*i)%26 == 1, // Check if (a*i)%26 == 1,
// if so, then i will be the multiplicative inverse of a // then i will be the multiplicative inverse of a
if (flag == 1) if (flag == 1) {
{
a_inv = i; a_inv = i;
} }
} }
for (int i = 0; i < cipher.length(); i++) for (int i = 0; i < cipher.length(); i++) {
{
/*Applying decryption formula a^-1 ( x - b ) mod m /*Applying decryption formula a^-1 ( x - b ) mod m
{here x is cipher[i] and m is 26} and added 'A' {here x is cipher[i] and m is 26} and added 'A'
to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */ to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
if (cipher.charAt(i) != ' ') if (cipher.charAt(i) != ' ') {
{
msg = msg + (char) (((a_inv * msg = msg + (char) (((a_inv *
((cipher.charAt(i) + 'A' - b)) % 26)) + 'A'); ((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
} } else //else simply append space character
else // append space character
{ {
msg += cipher.charAt(i); msg += cipher.charAt(i);
} }
@ -82,17 +57,17 @@ class AffineCipher
return msg; return msg;
} }
// Main method // Driver code
public static void main(String[] args) public static void main(String[] args) {
{
String msg = "AFFINE CIPHER"; String msg = "AFFINE CIPHER";
// Encrypting message // Calling encryption function
String cipherText = encryptMessage(msg.toCharArray()); String cipherText = encryptMessage(msg.toCharArray());
System.out.println("Encrypted Message is : " + cipherText); System.out.println("Encrypted Message is : " + cipherText);
// Decrypting message // Calling Decryption function
System.out.println("Decrypted Message is: " + decryptCipher(cipherText)); System.out.println("Decrypted Message is: " + decryptCipher(cipherText));
} }
} }

View File

@ -11,105 +11,105 @@ import java.util.Scanner;
*/ */
public class Caesar { public class Caesar {
/** /**
* Encrypt text by shifting every Latin char by add number shift for ASCII Example : A + 1 -> B * Encrypt text by shifting every Latin char by add number shift for ASCII Example : A + 1 -> B
* *
* @return Encrypted message * @return Encrypted message
*/ */
public static String encode(String message, int shift) { public static String encode(String message, int shift) {
StringBuilder encoded = new StringBuilder(); StringBuilder encoded = new StringBuilder();
shift %= 26; shift %= 26;
final int length = message.length(); final int length = message.length();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
// int current = message.charAt(i); //using char to shift characters because ascii // int current = message.charAt(i); //using char to shift characters because ascii
// is in-order latin alphabet // is in-order latin alphabet
char current = message.charAt(i); // Java law : char + int = char char current = message.charAt(i); // Java law : char + int = char
if (IsCapitalLatinLetter(current)) { if (IsCapitalLatinLetter(current)) {
current += shift; current += shift;
encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters encoded.append((char) (current > 'Z' ? current - 26 : current)); // 26 = number of latin letters
} else if (IsSmallLatinLetter(current)) { } else if (IsSmallLatinLetter(current)) {
current += shift; current += shift;
encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters encoded.append((char) (current > 'z' ? current - 26 : current)); // 26 = number of latin letters
} else { } else {
encoded.append(current); encoded.append(current);
} }
}
return encoded.toString();
} }
return encoded.toString();
}
/** /**
* Decrypt message by shifting back every Latin char to previous the ASCII Example : B - 1 -> A * Decrypt message by shifting back every Latin char to previous the ASCII Example : B - 1 -> A
* *
* @return message * @return message
*/ */
public static String decode(String encryptedMessage, int shift) { public static String decode(String encryptedMessage, int shift) {
StringBuilder decoded = new StringBuilder(); StringBuilder decoded = new StringBuilder();
shift %= 26; shift %= 26;
final int length = encryptedMessage.length(); final int length = encryptedMessage.length();
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
char current = encryptedMessage.charAt(i); char current = encryptedMessage.charAt(i);
if (IsCapitalLatinLetter(current)) { if (IsCapitalLatinLetter(current)) {
current -= shift; current -= shift;
decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters decoded.append((char) (current < 'A' ? current + 26 : current)); // 26 = number of latin letters
} else if (IsSmallLatinLetter(current)) { } else if (IsSmallLatinLetter(current)) {
current -= shift; current -= shift;
decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters decoded.append((char) (current < 'a' ? current + 26 : current)); // 26 = number of latin letters
} else { } else {
decoded.append(current); decoded.append(current);
} }
}
return decoded.toString();
} }
return decoded.toString();
}
/** /**
* @return true if character is capital Latin letter or false for others * @return true if character is capital Latin letter or false for others
*/ */
private static boolean IsCapitalLatinLetter(char c) { private static boolean IsCapitalLatinLetter(char c) {
return c >= 'A' && c <= 'Z'; return c >= 'A' && c <= 'Z';
} }
/** /**
* @return true if character is small Latin letter or false for others * @return true if character is small Latin letter or false for others
*/ */
private static boolean IsSmallLatinLetter(char c) { private static boolean IsSmallLatinLetter(char c) {
return c >= 'a' && c <= 'z'; return c >= 'a' && c <= 'z';
} }
public static void main(String[] args) { public static void main(String[] args) {
Scanner input = new Scanner(System.in); Scanner input = new Scanner(System.in);
System.out.println("Please enter the message (Latin Alphabet)"); System.out.println("Please enter the message (Latin Alphabet)");
String message = input.nextLine(); String message = input.nextLine();
System.out.println(message); System.out.println(message);
System.out.println("Please enter the shift number"); System.out.println("Please enter the shift number");
int shift = input.nextInt() % 26; int shift = input.nextInt() % 26;
System.out.println("(E)ncode or (D)ecode ?"); System.out.println("(E)ncode or (D)ecode ?");
char choice = input.next().charAt(0); char choice = input.next().charAt(0);
switch (choice) { switch (choice) {
case 'E': case 'E':
case 'e': case 'e':
System.out.println( System.out.println(
"ENCODED MESSAGE IS \n" + encode(message, shift)); // send our function to handle "ENCODED MESSAGE IS \n" + encode(message, shift)); // send our function to handle
break; break;
case 'D': case 'D':
case 'd': case 'd':
System.out.println("DECODED MESSAGE IS \n" + decode(message, shift)); System.out.println("DECODED MESSAGE IS \n" + decode(message, shift));
default: default:
System.out.println("default case"); System.out.println("default case");
}
input.close();
} }
input.close();
}
} }

View File

@ -9,191 +9,193 @@ import java.util.Objects;
*/ */
public class ColumnarTranspositionCipher { public class ColumnarTranspositionCipher {
private static String keyword; private static String keyword;
private static Object[][] table; private static Object[][] table;
private static String abecedarium; private static String abecedarium;
public static final String ABECEDARIUM = public static final String ABECEDARIUM =
"abcdefghijklmnopqrstuvwxyzABCDEFG" + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@"; "abcdefghijklmnopqrstuvwxyzABCDEFG" + "HIJKLMNOPQRSTUVWXYZ0123456789,.;:-@";
private static final String ENCRYPTION_FIELD = ""; private static final String ENCRYPTION_FIELD = "";
private static final char ENCRYPTION_FIELD_CHAR = '≈'; private static final char ENCRYPTION_FIELD_CHAR = '≈';
/** /**
* Encrypts a certain String with the Columnar Transposition Cipher Rule * Encrypts a certain String with the Columnar Transposition Cipher Rule
* *
* @param word Word being encrypted * @param word Word being encrypted
* @param keyword String with keyword being used * @param keyword String with keyword being used
* @return a String with the word encrypted by the Columnar Transposition Cipher Rule * @return a String with the word encrypted by the Columnar Transposition Cipher Rule
*/ */
public static String encrpyter(String word, String keyword) { public static String encrpyter(String word, String keyword) {
ColumnarTranspositionCipher.keyword = keyword; ColumnarTranspositionCipher.keyword = keyword;
abecedariumBuilder(500); abecedariumBuilder(500);
table = tableBuilder(word); table = tableBuilder(word);
Object[][] sortedTable = sortTable(table); Object[][] sortedTable = sortTable(table);
StringBuilder wordEncrypted = new StringBuilder(); StringBuilder wordEncrypted = new StringBuilder();
for (int i = 0; i < sortedTable[i].length; i++) { for (int i = 0; i < sortedTable[i].length; i++) {
for (int j = 1; j < sortedTable.length; j++) { for (int j = 1; j < sortedTable.length; j++) {
wordEncrypted.append(sortedTable[j][i]); wordEncrypted.append(sortedTable[j][i]);
} }
}
return wordEncrypted.toString();
} }
return wordEncrypted.toString();
}
/** /**
* Encrypts a certain String with the Columnar Transposition Cipher Rule * Encrypts a certain String with the Columnar Transposition Cipher Rule
* *
* @param word Word being encrypted * @param word Word being encrypted
* @param keyword String with keyword being used * @param keyword String with keyword being used
* @param abecedarium String with the abecedarium being used. null for default one * @param abecedarium String with the abecedarium being used. null for default one
* @return a String with the word encrypted by the Columnar Transposition Cipher Rule * @return a String with the word encrypted by the Columnar Transposition Cipher Rule
*/ */
public static String encrpyter(String word, String keyword, String abecedarium) { public static String encrpyter(String word, String keyword, String abecedarium) {
ColumnarTranspositionCipher.keyword = keyword; ColumnarTranspositionCipher.keyword = keyword;
ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM); ColumnarTranspositionCipher.abecedarium = Objects.requireNonNullElse(abecedarium, ABECEDARIUM);
table = tableBuilder(word); table = tableBuilder(word);
Object[][] sortedTable = sortTable(table); Object[][] sortedTable = sortTable(table);
StringBuilder wordEncrypted = new StringBuilder(); StringBuilder wordEncrypted = new StringBuilder();
for (int i = 0; i < sortedTable[0].length; i++) { for (int i = 0; i < sortedTable[0].length; i++) {
for (int j = 1; j < sortedTable.length; j++) { for (int j = 1; j < sortedTable.length; j++) {
wordEncrypted.append(sortedTable[j][i]); wordEncrypted.append(sortedTable[j][i]);
} }
}
return wordEncrypted.toString();
} }
return wordEncrypted.toString();
}
/** /**
* Decrypts a certain encrypted String with the Columnar Transposition Cipher Rule * Decrypts a certain encrypted String with the Columnar Transposition Cipher Rule
* *
* @return a String decrypted with the word encrypted by the Columnar Transposition Cipher Rule * @return a String decrypted with the word encrypted by the Columnar Transposition Cipher Rule
*/ */
public static String decrypter() { public static String decrypter() {
StringBuilder wordDecrypted = new StringBuilder(); StringBuilder wordDecrypted = new StringBuilder();
for (int i = 1; i < table.length; i++) { for (int i = 1; i < table.length; i++) {
for (Object item : table[i]) { for (Object item : table[i]) {
wordDecrypted.append(item); wordDecrypted.append(item);
} }
}
return wordDecrypted.toString().replaceAll(ENCRYPTION_FIELD, "");
} }
return wordDecrypted.toString().replaceAll(ENCRYPTION_FIELD, "");
}
/** /**
* Builds a table with the word to be encrypted in rows by the Columnar Transposition Cipher Rule * Builds a table with the word to be encrypted in rows by the Columnar Transposition Cipher Rule
* *
* @return An Object[][] with the word to be encrypted filled in rows and columns * @return An Object[][] with the word to be encrypted filled in rows and columns
*/ */
private static Object[][] tableBuilder(String word) { private static Object[][] tableBuilder(String word) {
Object[][] table = new Object[numberOfRows(word) + 1][keyword.length()]; Object[][] table = new Object[numberOfRows(word) + 1][keyword.length()];
char[] wordInChards = word.toCharArray(); char[] wordInChards = word.toCharArray();
// Fils in the respective numbers // Fils in the respective numbers
table[0] = findElements(); table[0] = findElements();
int charElement = 0; int charElement = 0;
for (int i = 1; i < table.length; i++) { for (int i = 1; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) { for (int j = 0; j < table[i].length; j++) {
if (charElement < wordInChards.length) { if (charElement < wordInChards.length) {
table[i][j] = wordInChards[charElement]; table[i][j] = wordInChards[charElement];
charElement++; charElement++;
} else {
table[i][j] = ENCRYPTION_FIELD_CHAR;
}
}
}
return table;
}
/**
* Determines the number of rows the table should have regarding the Columnar Transposition Cipher
* Rule
*
* @return an int with the number of rows that the table should have in order to respect the
* Columnar Transposition Cipher Rule.
*/
private static int numberOfRows(String word) {
if (word.length() / keyword.length() > word.length() / keyword.length()) {
return (word.length() / keyword.length()) + 1;
} else { } else {
table[i][j] = ENCRYPTION_FIELD_CHAR; return word.length() / keyword.length();
} }
}
} }
return table;
}
/** /**
* Determines the number of rows the table should have regarding the Columnar Transposition Cipher * @return charValues
* Rule */
* private static Object[] findElements() {
* @return an int with the number of rows that the table should have in order to respect the Object[] charValues = new Object[keyword.length()];
* Columnar Transposition Cipher Rule. for (int i = 0; i < charValues.length; i++) {
*/ int charValueIndex = abecedarium.indexOf(keyword.charAt(i));
private static int numberOfRows(String word) { charValues[i] = charValueIndex > -1 ? charValueIndex : null;
if (word.length() / keyword.length() > word.length() / keyword.length()) {
return (word.length() / keyword.length()) + 1;
} else {
return word.length() / keyword.length();
}
}
/** @return charValues */
private static Object[] findElements() {
Object[] charValues = new Object[keyword.length()];
for (int i = 0; i < charValues.length; i++) {
int charValueIndex = abecedarium.indexOf(keyword.charAt(i));
charValues[i] = charValueIndex > -1 ? charValueIndex : null;
}
return charValues;
}
/**
* @return tableSorted
*/
private static Object[][] sortTable(Object[][] table) {
Object[][] tableSorted = new Object[table.length][table[0].length];
for (int i = 0; i < tableSorted.length; i++) {
System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length);
}
for (int i = 0; i < tableSorted[0].length; i++) {
for (int j = i + 1; j < tableSorted[0].length; j++) {
if ((int) tableSorted[0][i] > (int) table[0][j]) {
Object[] column = getColumn(tableSorted, tableSorted.length, i);
switchColumns(tableSorted, j, i, column);
} }
} return charValues;
} }
return tableSorted;
}
/** /**
* @return columnArray * @return tableSorted
*/ */
private static Object[] getColumn(Object[][] table, int rows, int column) { private static Object[][] sortTable(Object[][] table) {
Object[] columnArray = new Object[rows]; Object[][] tableSorted = new Object[table.length][table[0].length];
for (int i = 0; i < rows; i++) { for (int i = 0; i < tableSorted.length; i++) {
columnArray[i] = table[i][column]; System.arraycopy(table[i], 0, tableSorted[i], 0, tableSorted[i].length);
}
for (int i = 0; i < tableSorted[0].length; i++) {
for (int j = i + 1; j < tableSorted[0].length; j++) {
if ((int) tableSorted[0][i] > (int) table[0][j]) {
Object[] column = getColumn(tableSorted, tableSorted.length, i);
switchColumns(tableSorted, j, i, column);
}
}
}
return tableSorted;
} }
return columnArray;
}
private static void switchColumns( /**
Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) { * @return columnArray
for (int i = 0; i < table.length; i++) { */
table[i][secondColumnIndex] = table[i][firstColumnIndex]; private static Object[] getColumn(Object[][] table, int rows, int column) {
table[i][firstColumnIndex] = columnToSwitch[i]; Object[] columnArray = new Object[rows];
for (int i = 0; i < rows; i++) {
columnArray[i] = table[i][column];
}
return columnArray;
} }
}
/** private static void switchColumns(
* Creates an abecedarium with a specified ascii inded Object[][] table, int firstColumnIndex, int secondColumnIndex, Object[] columnToSwitch) {
* for (int i = 0; i < table.length; i++) {
* @param value Number of characters being used based on the ASCII Table table[i][secondColumnIndex] = table[i][firstColumnIndex];
*/ table[i][firstColumnIndex] = columnToSwitch[i];
private static void abecedariumBuilder(int value) { }
StringBuilder t = new StringBuilder();
for (int i = 0; i < value; i++) {
t.append((char) i);
} }
abecedarium = t.toString();
}
private static void showTable() { /**
for (Object[] table1 : table) { * Creates an abecedarium with a specified ascii inded
for (Object item : table1) { *
System.out.print(item + " "); * @param value Number of characters being used based on the ASCII Table
} */
System.out.println(); private static void abecedariumBuilder(int value) {
StringBuilder t = new StringBuilder();
for (int i = 0; i < value; i++) {
t.append((char) i);
}
abecedarium = t.toString();
} }
}
public static void main(String[] args) { private static void showTable() {
String keywordForExample = "asd215"; for (Object[] table1 : table) {
String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher"; for (Object item : table1) {
System.out.println("### Example of Columnar Transposition Cipher ###\n"); System.out.print(item + " ");
System.out.println("Word being encryped ->>> " + wordBeingEncrypted); }
System.out.println( System.out.println();
"Word encrypted ->>> " }
+ ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample)); }
System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter());
System.out.println("\n### Encrypted Table ###"); public static void main(String[] args) {
showTable(); String keywordForExample = "asd215";
} String wordBeingEncrypted = "This is a test of the Columnar Transposition Cipher";
System.out.println("### Example of Columnar Transposition Cipher ###\n");
System.out.println("Word being encryped ->>> " + wordBeingEncrypted);
System.out.println(
"Word encrypted ->>> "
+ ColumnarTranspositionCipher.encrpyter(wordBeingEncrypted, keywordForExample));
System.out.println("Word decryped ->>> " + ColumnarTranspositionCipher.decrypter());
System.out.println("\n### Encrypted Table ###");
showTable();
}
} }

View File

@ -1,172 +1,165 @@
package Ciphers; package Ciphers;
import java.util.*; import java.util.Scanner;
/* /*
* Java Implementation of Hill Cipher * Java Implementation of Hill Cipher
* Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number belonging to the set Z26 where A=0 , B=1, ..... Z=25. * Hill cipher is a polyalphabetic substitution cipher. Each letter is represented by a number belonging to the set Z26 where A=0 , B=1, ..... Z=25.
* To encrypt a message, each block of n letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against modulus 26. * To encrypt a message, each block of n letters (since matrix size is n x n) is multiplied by an invertible n × n matrix, against modulus 26.
* To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption. * To decrypt the message, each block is multiplied by the inverse of the matrix used for encryption.
* The cipher key and plaintext/ciphertext are user inputs. * The cipher key and plaintext/ciphertext are user inputs.
* @author Ojasva Jain * @author Ojasva Jain
*/ */
public class HillCipher{ public class HillCipher {
static Scanner in = new Scanner (System.in); static Scanner in = new Scanner(System.in);
/* Following function encrypts the message /* Following function encrypts the message
*/ */
static void encrypt(String message) static void encrypt(String message) {
{ message = message.toUpperCase();
message = message.toUpperCase(); // Get key matrix
// Get key matrix System.out.println("Enter key matrix size");
System.out.println("Enter key matrix size"); int n = in.nextInt();
int n = in.nextInt(); System.out.println("Enter Key/encryptionKey matrix ");
System.out.println("Enter Key/encryptionKey matrix "); int keyMatrix[][] = new int[n][n];
int keyMatrix[][] = new int [n][n]; for (int i = 0; i < n; i++) {
for(int i=0;i<n;i++){ for (int j = 0; j < n; j++) {
for(int j=0;j<n;j++){ keyMatrix[i][j] = in.nextInt();
keyMatrix[i][j] = in.nextInt();
}
}
//check if det = 0
if(determinant(keyMatrix,n)%26 == 0)
{
System.out.println("Invalid key, as determinant = 0. Program Terminated");
return;
}
int [][]messageVector = new int[n][1];
String CipherText="";
int cipherMatrix [][] = new int [n][1];
int j = 0;
while(j<message.length()){
for (int i = 0; i < n; i++){
if(j>=message.length()){ messageVector[i][0] = 23;}
else
messageVector[i][0] = (message.charAt(j))%65;
System.out.println(messageVector[i][0]);
j++;
}
int x, i;
for (i = 0; i < n; i++)
{
cipherMatrix[i][0] = 0;
for (x = 0; x < n; x++)
{
cipherMatrix[i][0] += keyMatrix[i][x] * messageVector[x][0];
} }
System.out.println(cipherMatrix[i][0]);
cipherMatrix[i][0] = cipherMatrix[i][0] % 26;
} }
for (i = 0; i < n; i++) //check if det = 0
CipherText += (char)(cipherMatrix[i][0] + 65); if (determinant(keyMatrix, n) % 26 == 0) {
} System.out.println("Invalid key, as determinant = 0. Program Terminated");
System.out.println("Ciphertext: "+ CipherText); return;
}
//Following function decrypts a message
static void decrypt(String message)
{
message = message.toUpperCase();
// Get key matrix
System.out.println("Enter key matrix size");
int n = in.nextInt();
System.out.println("Enter inverseKey/decryptionKey matrix ");
int keyMatrix[][] = new int [n][n];
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
keyMatrix[i][j] = in.nextInt();
} }
int[][] messageVector = new int[n][1];
String CipherText = "";
int cipherMatrix[][] = new int[n][1];
int j = 0;
while (j < message.length()) {
for (int i = 0; i < n; i++) {
if (j >= message.length()) {
messageVector[i][0] = 23;
} else
messageVector[i][0] = (message.charAt(j)) % 65;
System.out.println(messageVector[i][0]);
j++;
}
int x, i;
for (i = 0; i < n; i++) {
cipherMatrix[i][0] = 0;
for (x = 0; x < n; x++) {
cipherMatrix[i][0] += keyMatrix[i][x] * messageVector[x][0];
}
System.out.println(cipherMatrix[i][0]);
cipherMatrix[i][0] = cipherMatrix[i][0] % 26;
}
for (i = 0; i < n; i++)
CipherText += (char) (cipherMatrix[i][0] + 65);
}
System.out.println("Ciphertext: " + CipherText);
} }
//check if det = 0
if(determinant(keyMatrix,n)%26 == 0) //Following function decrypts a message
{ static void decrypt(String message) {
System.out.println("Invalid key, as determinant = 0. Program Terminated"); message = message.toUpperCase();
return; // Get key matrix
} System.out.println("Enter key matrix size");
//solving for the required plaintext message int n = in.nextInt();
int [][]messageVector = new int[n][1]; System.out.println("Enter inverseKey/decryptionKey matrix ");
String PlainText=""; int keyMatrix[][] = new int[n][n];
int plainMatrix [][] = new int [n][1]; for (int i = 0; i < n; i++) {
int j = 0; for (int j = 0; j < n; j++) {
while(j<message.length()){ keyMatrix[i][j] = in.nextInt();
for (int i = 0; i < n; i++){ }
if(j>=message.length()){ messageVector[i][0] = 23;}
else
messageVector[i][0] = (message.charAt(j))%65;
System.out.println(messageVector[i][0]);
j++;
} }
int x, i; //check if det = 0
for (i = 0; i < n; i++) if (determinant(keyMatrix, n) % 26 == 0) {
{ System.out.println("Invalid key, as determinant = 0. Program Terminated");
plainMatrix[i][0] = 0; return;
}
for (x = 0; x < n; x++) //solving for the required plaintext message
{ int[][] messageVector = new int[n][1];
String PlainText = "";
int plainMatrix[][] = new int[n][1];
int j = 0;
while (j < message.length()) {
for (int i = 0; i < n; i++) {
if (j >= message.length()) {
messageVector[i][0] = 23;
} else
messageVector[i][0] = (message.charAt(j)) % 65;
System.out.println(messageVector[i][0]);
j++;
}
int x, i;
for (i = 0; i < n; i++) {
plainMatrix[i][0] = 0;
for (x = 0; x < n; x++) {
plainMatrix[i][0] += keyMatrix[i][x] * messageVector[x][0]; plainMatrix[i][0] += keyMatrix[i][x] * messageVector[x][0];
} }
plainMatrix[i][0] = plainMatrix[i][0] % 26; plainMatrix[i][0] = plainMatrix[i][0] % 26;
} }
for (i = 0; i < n; i++) for (i = 0; i < n; i++)
PlainText += (char)(plainMatrix[i][0] + 65); PlainText += (char) (plainMatrix[i][0] + 65);
}
System.out.println("Plaintext: " + PlainText);
} }
System.out.println("Plaintext: "+PlainText);
}
// Determinant calculator // Determinant calculator
public static int determinant(int a[][], int n){ public static int determinant(int a[][], int n) {
int det = 0, sign = 1, p = 0, q = 0; int det = 0, sign = 1, p = 0, q = 0;
if(n==1){ if (n == 1) {
det = a[0][0]; det = a[0][0];
} } else {
else{ int b[][] = new int[n - 1][n - 1];
int b[][] = new int[n-1][n-1]; for (int x = 0; x < n; x++) {
for(int x = 0 ; x < n ; x++){ p = 0;
p=0;q=0; q = 0;
for(int i = 1;i < n; i++){ for (int i = 1; i < n; i++) {
for(int j = 0; j < n;j++){ for (int j = 0; j < n; j++) {
if(j != x){ if (j != x) {
b[p][q++] = a[i][j]; b[p][q++] = a[i][j];
if(q % (n-1) == 0){ if (q % (n - 1) == 0) {
p++; p++;
q=0; q = 0;
}
} }
} }
} }
det = det + a[0][x] * determinant(b, n - 1) * sign;
sign = -sign;
} }
det = det + a[0][x] *determinant(b, n-1) * sign;
sign = -sign;
} }
return det;
} }
return det;
}
// Function to implement Hill Cipher // Function to implement Hill Cipher
static void hillcipher(String message) static void hillcipher(String message) {
{ message.toUpperCase();
message.toUpperCase(); System.out.println("What do you want to process from the message?");
System.out.println("What do you want to process from the message?"); System.out.println("Press 1: To Encrypt");
System.out.println("Press 1: To Encrypt"); System.out.println("Press 2: To Decrypt");
System.out.println("Press 2: To Decrypt"); short sc = in.nextShort();
short sc = in.nextShort(); if (sc == 1)
if(sc == 1) encrypt(message);
encrypt(message); else if (sc == 2)
else if(sc == 2) decrypt(message);
decrypt(message); else
else System.out.println("Invalid input, program terminated.");
System.out.println("Invalid input, program terminated."); }
}
// Driver code // Driver code
public static void main(String[] args) public static void main(String[] args) {
{ // Get the message to be encrypted
// Get the message to be encrypted System.out.println("Enter message");
System.out.println("Enter message"); String message = in.nextLine();
String message = in.nextLine(); hillcipher(message);
hillcipher(message);
} }
} }

View File

@ -1,74 +1,76 @@
package Ciphers; package Ciphers;
import javax.swing.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.security.SecureRandom; import java.security.SecureRandom;
import javax.swing.JOptionPane;
/** @author Nguyen Duy Tiep on 23-Oct-17. */ /**
* @author Nguyen Duy Tiep on 23-Oct-17.
*/
public final class RSA { public final class RSA {
public static void main(String[] args) { public static void main(String[] args) {
RSA rsa = new RSA(1024); RSA rsa = new RSA(1024);
String text1 = JOptionPane.showInputDialog("Enter a message to encrypt :"); String text1 = JOptionPane.showInputDialog("Enter a message to encrypt :");
String ciphertext = rsa.encrypt(text1); String ciphertext = rsa.encrypt(text1);
JOptionPane.showMessageDialog(null, "Your encrypted message : " + ciphertext); JOptionPane.showMessageDialog(null, "Your encrypted message : " + ciphertext);
JOptionPane.showMessageDialog(null, "Your message after decrypt : " + rsa.decrypt(ciphertext)); JOptionPane.showMessageDialog(null, "Your message after decrypt : " + rsa.decrypt(ciphertext));
}
private BigInteger modulus, privateKey, publicKey;
public RSA(int bits) {
generateKeys(bits);
}
/**
* @return encrypted message
*/
public synchronized String encrypt(String message) {
return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString();
}
/**
* @return encrypted message as big integer
*/
public synchronized BigInteger encrypt(BigInteger message) {
return message.modPow(publicKey, modulus);
}
/**
* @return plain message
*/
public synchronized String decrypt(String encryptedMessage) {
return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
}
/**
* @return plain message as big integer
*/
public synchronized BigInteger decrypt(BigInteger encryptedMessage) {
return encryptedMessage.modPow(privateKey, modulus);
}
/**
* Generate a new public and private key set.
*/
public synchronized void generateKeys(int bits) {
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bits / 2, 100, r);
BigInteger q = new BigInteger(bits / 2, 100, r);
modulus = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
publicKey = new BigInteger("3");
while (m.gcd(publicKey).intValue() > 1) {
publicKey = publicKey.add(new BigInteger("2"));
} }
privateKey = publicKey.modInverse(m); private BigInteger modulus, privateKey, publicKey;
}
public RSA(int bits) {
generateKeys(bits);
}
/**
* @return encrypted message
*/
public synchronized String encrypt(String message) {
return (new BigInteger(message.getBytes())).modPow(publicKey, modulus).toString();
}
/**
* @return encrypted message as big integer
*/
public synchronized BigInteger encrypt(BigInteger message) {
return message.modPow(publicKey, modulus);
}
/**
* @return plain message
*/
public synchronized String decrypt(String encryptedMessage) {
return new String((new BigInteger(encryptedMessage)).modPow(privateKey, modulus).toByteArray());
}
/**
* @return plain message as big integer
*/
public synchronized BigInteger decrypt(BigInteger encryptedMessage) {
return encryptedMessage.modPow(privateKey, modulus);
}
/**
* Generate a new public and private key set.
*/
public synchronized void generateKeys(int bits) {
SecureRandom r = new SecureRandom();
BigInteger p = new BigInteger(bits / 2, 100, r);
BigInteger q = new BigInteger(bits / 2, 100, r);
modulus = p.multiply(q);
BigInteger m = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
publicKey = new BigInteger("3");
while (m.gcd(publicKey).intValue() > 1) {
publicKey = publicKey.add(new BigInteger("2"));
}
privateKey = publicKey.modInverse(m);
}
} }

View File

@ -1,19 +1,18 @@
package ciphers; package ciphers;
import java.util.*; import java.util.HashMap;
import java.util.Map;
/** /**
* * The simple substitution cipher is a cipher that has been in use for many hundreds of years
* The simple substitution cipher is a cipher that has been in use for many hundreds of years * (an excellent history is given in Simon Singhs 'the Code Book').
* (an excellent history is given in Simon Singhs 'the Code Book'). * It basically consists of substituting every plaintext character for a different ciphertext character.
* It basically consists of substituting every plaintext character for a different ciphertext character.
* It differs from the Caesar cipher in that the cipher alphabet is not simply the alphabet shifted, * It differs from the Caesar cipher in that the cipher alphabet is not simply the alphabet shifted,
* it is completely jumbled. * it is completely jumbled.
*
*/ */
public class simpleSubCipher { public class SimpleSubCipher {
/** /**
* Encrypt text by replacing each element with its opposite character. * Encrypt text by replacing each element with its opposite character.
* *
@ -23,32 +22,32 @@ public class simpleSubCipher {
*/ */
public static String encode(String message, String cipherSmall) { public static String encode(String message, String cipherSmall) {
String encoded = ""; String encoded = "";
// This map is used to encode // This map is used to encode
Map<Character,Character> cipherMap = new HashMap<Character,Character>(); Map<Character, Character> cipherMap = new HashMap<>();
char beginSmallLetter = 'a'; char beginSmallLetter = 'a';
char beginCapitalLetter = 'A'; char beginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase(); cipherSmall = cipherSmall.toLowerCase();
String cipherCapital = cipherSmall.toUpperCase(); String cipherCapital = cipherSmall.toUpperCase();
// To handle Small and Capital letters // To handle Small and Capital letters
for(int i = 0; i < cipherSmall.length(); i++){ for (int i = 0; i < cipherSmall.length(); i++) {
cipherMap.put(beginSmallLetter++,cipherSmall.charAt(i)); cipherMap.put(beginSmallLetter++, cipherSmall.charAt(i));
cipherMap.put(beginCapitalLetter++,cipherCapital.charAt(i)); cipherMap.put(beginCapitalLetter++, cipherCapital.charAt(i));
} }
for(int i = 0; i < message.length(); i++){ for (int i = 0; i < message.length(); i++) {
if(Character.isAlphabetic(message.charAt(i))) if (Character.isAlphabetic(message.charAt(i)))
encoded += cipherMap.get(message.charAt(i)); encoded += cipherMap.get(message.charAt(i));
else else
encoded += message.charAt(i); encoded += message.charAt(i);
} }
return encoded; return encoded;
} }
/** /**
* Decrypt message by replacing each element with its opposite character in cipher. * Decrypt message by replacing each element with its opposite character in cipher.
* *
@ -58,35 +57,35 @@ public class simpleSubCipher {
*/ */
public static String decode(String encryptedMessage, String cipherSmall) { public static String decode(String encryptedMessage, String cipherSmall) {
String decoded = ""; String decoded = "";
Map<Character,Character> cipherMap = new HashMap<Character,Character>(); Map<Character, Character> cipherMap = new HashMap<Character, Character>();
char beginSmallLetter = 'a'; char beginSmallLetter = 'a';
char beginCapitalLetter = 'A'; char beginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase(); cipherSmall = cipherSmall.toLowerCase();
String cipherCapital = cipherSmall.toUpperCase(); String cipherCapital = cipherSmall.toUpperCase();
for(int i = 0; i < cipherSmall.length(); i++){ for (int i = 0; i < cipherSmall.length(); i++) {
cipherMap.put(cipherSmall.charAt(i),beginSmallLetter++); cipherMap.put(cipherSmall.charAt(i), beginSmallLetter++);
cipherMap.put(cipherCapital.charAt(i),beginCapitalLetter++); cipherMap.put(cipherCapital.charAt(i), beginCapitalLetter++);
} }
for(int i = 0; i < encryptedMessage.length(); i++){ for (int i = 0; i < encryptedMessage.length(); i++) {
if(Character.isAlphabetic(encryptedMessage.charAt(i))) if (Character.isAlphabetic(encryptedMessage.charAt(i)))
decoded += cipherMap.get(encryptedMessage.charAt(i)); decoded += cipherMap.get(encryptedMessage.charAt(i));
else else
decoded += encryptedMessage.charAt(i); decoded += encryptedMessage.charAt(i);
} }
return decoded; return decoded;
} }
public static void main(String[] args) { public static void main(String[] args) {
String a = encode("defend the east wall of the castle","phqgiumeaylnofdxjkrcvstzwb"); String a = encode("defend the east wall of the castle", "phqgiumeaylnofdxjkrcvstzwb");
String b = decode(a,"phqgiumeaylnofdxjkrcvstzwb"); String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb");
System.out.println(b); System.out.println(b);
} }
} }

View File

@ -1,6 +1,7 @@
package Ciphers; package Ciphers;
import java.util.*; import java.util.HashMap;
import java.util.Map;
/** /**
* The simple substitution cipher is a cipher that has been in use for many hundreds of years (an * The simple substitution cipher is a cipher that has been in use for many hundreds of years (an
@ -13,71 +14,73 @@ import java.util.*;
*/ */
public class SimpleSubstitutionCipher { public class SimpleSubstitutionCipher {
/** /**
* Encrypt text by replacing each element with its opposite character. * Encrypt text by replacing each element with its opposite character.
* *
* @return Encrypted message * @return Encrypted message
*/ */
public static String encode(String message, String cipherSmall) { public static String encode(String message, String cipherSmall) {
StringBuilder encoded = new StringBuilder(); StringBuilder encoded = new StringBuilder();
// This map is used to encode // This map is used to encode
Map<Character, Character> cipherMap = new HashMap<>(); Map<Character, Character> cipherMap = new HashMap<>();
char beginSmallLetter = 'a'; char beginSmallLetter = 'a';
char beginCapitalLetter = 'A'; char beginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase(); cipherSmall = cipherSmall.toLowerCase();
String cipherCapital = cipherSmall.toUpperCase(); String cipherCapital = cipherSmall.toUpperCase();
// To handle Small and Capital letters // To handle Small and Capital letters
for (int i = 0; i < cipherSmall.length(); i++) { for (int i = 0; i < cipherSmall.length(); i++) {
cipherMap.put(beginSmallLetter++, cipherSmall.charAt(i)); cipherMap.put(beginSmallLetter++, cipherSmall.charAt(i));
cipherMap.put(beginCapitalLetter++, cipherCapital.charAt(i)); cipherMap.put(beginCapitalLetter++, cipherCapital.charAt(i));
}
for (int i = 0; i < message.length(); i++) {
if (Character.isAlphabetic(message.charAt(i))) encoded.append(cipherMap.get(message.charAt(i)));
else encoded.append(message.charAt(i));
}
return encoded.toString();
} }
for (int i = 0; i < message.length(); i++) { /**
if (Character.isAlphabetic(message.charAt(i))) encoded.append(cipherMap.get(message.charAt(i))); * Decrypt message by replacing each element with its opposite character in cipher.
else encoded.append(message.charAt(i)); *
* @return message
*/
public static String decode(String encryptedMessage, String cipherSmall) {
StringBuilder decoded = new StringBuilder();
Map<Character, Character> cipherMap = new HashMap<>();
char beginSmallLetter = 'a';
char beginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase();
String cipherCapital = cipherSmall.toUpperCase();
for (int i = 0; i < cipherSmall.length(); i++) {
cipherMap.put(cipherSmall.charAt(i), beginSmallLetter++);
cipherMap.put(cipherCapital.charAt(i), beginCapitalLetter++);
}
for (int i = 0; i < encryptedMessage.length(); i++) {
if (Character.isAlphabetic(encryptedMessage.charAt(i)))
decoded.append(cipherMap.get(encryptedMessage.charAt(i)));
else decoded.append(encryptedMessage.charAt(i));
}
return decoded.toString();
} }
return encoded.toString(); /**
} * TODO remove main and make JUnit Testing
*/
/** public static void main(String[] args) {
* Decrypt message by replacing each element with its opposite character in cipher. String a = encode("defend the east wall of the castle", "phqgiumeaylnofdxjkrcvstzwb");
* String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb");
* @return message System.out.println(b);
*/
public static String decode(String encryptedMessage, String cipherSmall) {
StringBuilder decoded = new StringBuilder();
Map<Character, Character> cipherMap = new HashMap<>();
char beginSmallLetter = 'a';
char beginCapitalLetter = 'A';
cipherSmall = cipherSmall.toLowerCase();
String cipherCapital = cipherSmall.toUpperCase();
for (int i = 0; i < cipherSmall.length(); i++) {
cipherMap.put(cipherSmall.charAt(i), beginSmallLetter++);
cipherMap.put(cipherCapital.charAt(i), beginCapitalLetter++);
} }
for (int i = 0; i < encryptedMessage.length(); i++) {
if (Character.isAlphabetic(encryptedMessage.charAt(i)))
decoded.append(cipherMap.get(encryptedMessage.charAt(i)));
else decoded.append(encryptedMessage.charAt(i));
}
return decoded.toString();
}
/** TODO remove main and make JUnit Testing */
public static void main(String[] args) {
String a = encode("defend the east wall of the castle", "phqgiumeaylnofdxjkrcvstzwb");
String b = decode(a, "phqgiumeaylnofdxjkrcvstzwb");
System.out.println(b);
}
} }

View File

@ -8,55 +8,55 @@ package Ciphers;
*/ */
public class Vigenere { public class Vigenere {
public static String encrypt(final String message, final String key) { public static String encrypt(final String message, final String key) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
for (int i = 0, j = 0; i < message.length(); i++) { for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i); char c = message.charAt(i);
if (Character.isLetter(c)) { if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) { if (Character.isUpperCase(c)) {
result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A')); result.append((char) ((c + key.toUpperCase().charAt(j) - 2 * 'A') % 26 + 'A'));
} else { } else {
result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a')); result.append((char) ((c + key.toLowerCase().charAt(j) - 2 * 'a') % 26 + 'a'));
}
} else {
result.append(c);
}
j = ++j % key.length();
} }
} else { return result.toString();
result.append(c);
}
j = ++j % key.length();
} }
return result.toString();
}
public static String decrypt(final String message, final String key) { public static String decrypt(final String message, final String key) {
StringBuilder result = new StringBuilder(); StringBuilder result = new StringBuilder();
for (int i = 0, j = 0; i < message.length(); i++) { for (int i = 0, j = 0; i < message.length(); i++) {
char c = message.charAt(i); char c = message.charAt(i);
if (Character.isLetter(c)) { if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) { if (Character.isUpperCase(c)) {
result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26)); result.append((char) ('Z' - (25 - (c - key.toUpperCase().charAt(j))) % 26));
} else { } else {
result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26)); result.append((char) ('z' - (25 - (c - key.toLowerCase().charAt(j))) % 26));
}
} else {
result.append(c);
}
j = ++j % key.length();
} }
} else { return result.toString();
result.append(c);
}
j = ++j % key.length();
} }
return result.toString();
}
public static void main(String[] args) { public static void main(String[] args) {
String text = "Hello World!"; String text = "Hello World!";
String key = "itsakey"; String key = "itsakey";
System.out.println(text); System.out.println(text);
String ciphertext = encrypt(text, key); String ciphertext = encrypt(text, key);
System.out.println(ciphertext); System.out.println(ciphertext);
System.out.println(decrypt(ciphertext, key)); System.out.println(decrypt(ciphertext, key));
} }
} }

View File

@ -1,83 +0,0 @@
package Ciphers;
class affineCipher
{
// Key values of a and b
static int a = 17;
static int b = 20;
static String encryptMessage(char[] msg)
{
/// Cipher Text initially empty
String cipher = "";
for (int i = 0; i < msg.length; i++)
{
// Avoid space to be encrypted
/* applying encryption formula ( a x + b ) mod m
{here x is msg[i] and m is 26} and added 'A' to
bring it in range of ascii alphabet[ 65-90 | A-Z ] */
if (msg[i] != ' ')
{
cipher = cipher
+ (char) ((((a * (msg[i] - 'A')) + b) % 26) + 'A');
} else // else simply append space character
{
cipher += msg[i];
}
}
return cipher;
}
static String decryptCipher(String cipher)
{
String msg = "";
int a_inv = 0;
int flag = 0;
//Find a^-1 (the multiplicative inverse of a
//in the group of integers modulo m.)
for (int i = 0; i < 26; i++)
{
flag = (a * i) % 26;
// Check if (a*i)%26 == 1,
// then i will be the multiplicative inverse of a
if (flag == 1)
{
a_inv = i;
}
}
for (int i = 0; i < cipher.length(); i++)
{
/*Applying decryption formula a^-1 ( x - b ) mod m
{here x is cipher[i] and m is 26} and added 'A'
to bring it in range of ASCII alphabet[ 65-90 | A-Z ] */
if (cipher.charAt(i) != ' ')
{
msg = msg + (char) (((a_inv *
((cipher.charAt(i) + 'A' - b)) % 26)) + 'A');
}
else //else simply append space character
{
msg += cipher.charAt(i);
}
}
return msg;
}
// Driver code
public static void main(String[] args)
{
String msg = "AFFINE CIPHER";
// Calling encryption function
String cipherText = encryptMessage(msg.toCharArray());
System.out.println("Encrypted Message is : " + cipherText);
// Calling Decryption function
System.out.println("Decrypted Message is: " + decryptCipher(cipherText));
}
}