03rd September, 2017

Vigenère cipher in Java

A Vigenère cipher written in Java.

This is a small Java program that enciphers and deciphers text using the Vigenère cipher algorithm.

This program works by taking a message from a text file and enciphering / deciphering it using a custom key. Output cipher text is printed into the terminal window instead of being written to a new text file.

This jar requires 3 arguments at execution: the mode (1 for encipher, and -1 for decipher), the name of the text file containing the key, and the name of the text file containing the message you want to encipher / decipher.

Example usage

  
// to encipher
java -jar vigenere-cipher.jar 1 key.txt message.txt
// to decipher
java -jar vigenere-cipher.jar -1 key.txt message.txt
  

Source code

  
public static void main(String[] args) {
    char[] key;
    String plainText;
    int mode = Integer.parseInt(args[0]);
    char[] alphabet = "abcdefghijklmnopqrstuvwxyz".toCharArray();
    StringBuilder cipherText = new StringBuilder();
    try {
        key = new String(Files.readAllBytes(Paths.get(args[1]))).toCharArray();
        plainText = new String(Files.readAllBytes(Paths.get(args[2])));
    } catch (Exception e) {
        throw new RuntimeException(String.format("Unable to open %s or %s", args[1], args[2]));
    }
    for (int i = 0; i < plainText.length(); i++) {
        // find position of character
        int alphabetCharacterPosition = -1;
        int keyCharacterPosition = -1;
        for (int j = 0; j < alphabet.length; j++) {
            if (plainText.charAt(i) == alphabet[j]) {
                alphabetCharacterPosition = j;
                break;
            }
        }
        // if character is not in alphabet just add it to the cipher text as plain text and continue
        if (alphabetCharacterPosition < 0) {
            cipherText.append(plainText.charAt(i));
            continue;
        }
        // find position of key character
        for (int j = 0; j < alphabet.length; j++) {
            if (key[i % key.length] == alphabet[j]) {
                keyCharacterPosition = j;
                break;
            }
        }
        // cipher the character
        int pointer = alphabetCharacterPosition + keyCharacterPosition * mode;
        cipherText.append(alphabet[(((pointer % alphabet.length) + alphabet.length) % alphabet.length)]);
    }
    System.out.println(cipherText.toString());
}
  

Thank you for reading.

🍓🍓🍓


Leave a comment

Invalid or missing field(s).
Comment sent successfully, please wait for it to be approved.

This post has no comments