Skip to content

Instantly share code, notes, and snippets.

@Peiffap
Last active January 26, 2017 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Peiffap/e194fc93a8952bc8258dc408d8376c62 to your computer and use it in GitHub Desktop.
Save Peiffap/e194fc93a8952bc8258dc408d8376c62 to your computer and use it in GitHub Desktop.
My personal implementations of some common cryptography algorithms
/**
* Created by admin on 25/01/17.
* Reads input from a file, creates a random Caesar cipher encryption key, and writes the ciphered output
* to a new file.
*/
import java.util.*;
import java.io.*;
public class Caesar {
private static char[] alphabet; // Uppercase letters of the alphabet, used for shifting.
public static void main (String[] args) {
fillAlphabet();
System.out.println("Do you wish to encrypt or decrypt your file? Type e for encryption, d for decryption.");
Scanner files = new Scanner(System.in); // Reads from standard input.
String ed = files.nextLine();
char c = ed.charAt(0);
if (c == 'd') {
System.out.println("What encryption key was originally used?");
} else {
System.out.println("What encryption key do you wish to use? Type 0 for random encryption.");
}
int key = files.nextInt();
files.nextLine();
System.out.println("Which file is input to be read from?");
String inFile = files.nextLine();
System.out.println("Which file is output to be written to?");
String outFile = files.nextLine();
long s = System.nanoTime();
if (key == 0) {
key = new Encryption(inFile, outFile).getKey();
}
key %= 26;
if (c == 'e') {
encrypt(new Encryption(inFile, outFile, key)); // Encrypts the plain text.
} else {
decrypt(inFile, outFile, key); // Deciphers the ciphered text.
}
long e = System.nanoTime();
System.out.println((e-s)/1000000000.0);
}
/**
* Reads from the input file and prints ciphered text to the output file. The first line of the output file is the
* encryption used.
* @param enc the Encryption containing input/output files and a key.
* @return true if successful, false if not.
*/
public static boolean encrypt(Encryption enc) {
BufferedReader in = null;
PrintWriter writer = null;
String inFile = enc.getInFile();
String outFile = enc.getOutFile();
int key = enc.getKey();
try {
in = new BufferedReader(new FileReader(new File(inFile))); // Reads from inFile.
writer = new PrintWriter(new File(outFile)); // Writes to outFile.
String s = in.readLine(); // Input string.
System.out.println(enc); // Encryption key.
while (s != null) {
StringBuffer str = new StringBuffer(); // Frequent appends, so StringBuffer is handy.
for (int i = 0; i < s.length(); i++) { // Shifts each letter, one at a time.
if (Character.isLetter(s.charAt(i))) {
str.append(shift(key, s.charAt(i))); // Letters get shifted.
} else {
str.append(s.charAt(i)); // Other input is pasted.
}
}
writer.println(str.toString()); // Prints a string representation of the ciphered line.
s = in.readLine();
}
try {
in.close(); // Closes the input stream.
} catch (IOException u) {}
writer.close(); // Closes the output writer.
return true; // Everything went well.
} catch (Exception e) {
System.err.println(e.getMessage());
try {
in.close(); // Closes the input stream.
} catch (IOException u) {}
writer.close(); // Closes the output writer.
return false; // Something went wrong.
}
}
/**
* @param ciphered the name of the file containing ciphered text.
* @param plain the name of the file to which to write the deciphered text.
* @param encryptionKey the original encryption key.
* @return true if successful, false if not.
*/
public static boolean decrypt(String ciphered, String plain, int encryptionKey) {
return encrypt(new Encryption(ciphered, plain, 26-encryptionKey));
}
/**
* Shifts a given character by key places in the alphabet (wraps around if needed).
* @param key the number of positions to shift.
* @param c the character to be shifted.
* @return the uppercase character found by shifting c by key places in the alphabet array.
*/
public static char shift(int key, char c) {
int initPos = -1; // Initial position of c in alphabet.
for (int i = 0; i < 26 && initPos == -1; i++) {
if (alphabet[i] == Character.toUpperCase(c))
initPos = i;
}
char shifted = alphabet[(initPos + key) % 26]; // Shifted character.
if (Character.toUpperCase(c) == c) {
return shifted;
} else
return Character.toLowerCase(shifted);
}
/**
* Fills the alphabet array with uppercase letters.
*/
public static void fillAlphabet() {
char[] chars = new char[26];
for (int i = 0; i < 26; i++) {
chars[i] = Character.toUpperCase("abcdefghijklmnopqrstuvwxyz".charAt(i));
}
alphabet = chars;
}
}
/**
* Created by admin on 25/01/17.
* This class represents a Caesar cipher encryption key with an input file, output file, and randomly generated key.
*/
import java.util.Random;
public class Encryption {
private String inFile; // The file from which plain text input is to be read.
private String outFile; // The file to which ciphered output is written.
private int key; // The key.
private Random rand = new Random((int) (4669 * Math.random())); // Used to generate a key.
/**
* @param inFile the input file.
* @param outFile the output file.
* Constructs a random Encryption object.
*/
public Encryption(String inFile, String outFile) {
this.inFile = inFile;
this.outFile = outFile;
this.key = rand.nextInt(25) + 1; // Random int between 1 and 25 (both inclusive).
}
/**
* @param inFile the input file.
* @param outFile the output file.
* @param key the specified key.
* Constructs an Encryption object using the given parameters.
*/
public Encryption(String inFile, String outFile, int key) {
this.inFile = inFile;
this.outFile = outFile;
this.key = key;
}
/**
* @return the name of this Encryption's input file.
*/
public String getInFile() {
return this.inFile;
}
/**
* @return the name of this Encryption's output file.
*/
public String getOutFile() {
return this.outFile;
}
/**
* @return the key used for ciphering in this Encryption.
*/
public int getKey() {
return this.key;
}
/**
* @return a string representation of this Encryption of this form : "inFile / outFile / key".
*/
public String toString() {
return this.inFile + " / " + this.outFile + " / " + this.key;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment