Java program to encipher and decipher text using Vigenère Cipher.

Text: ATTACKATDAWN
Key: LEMONLEMONLE
Enciphered: LXFOPVEFRNHR
Deciphered: ATTACKATDAWN
// © 2019 TheFlyingKeyboard and released under MIT License
// theflyingkeyboard.net
public class Main {
    public static void main(String[] args) {
        String text = "ATTACKATDAWN";
        String key = "LEMONLEMONLE";

        System.out.println("Text: " + text);
        System.out.println("Key: " + key);

        String ciphertext = encipher(text, key);
        System.out.println("Enciphered: " + ciphertext);
        System.out.println("Deciphered: " + decipher(ciphertext, key));
    }

    private static String encipher(String text, String key) {
        String result = "";
        text = text.toUpperCase();

        for (int i = 0; i < text.length(); ++i) {
            result += (char) ((((text.charAt(i) - 'A') + (key.charAt(i) - 'A')) % 26) + 'A');
        }

        return result;
    }

    private static String decipher(String text, String key) {
        String subtractedKey = "";

        for (int i = 0; i < key.length(); ++i) {
            subtractedKey += (char) (('Z' - key.charAt(i) + 1) + 'A');
        }

        return encipher(text, subtractedKey);
    }
}

 



Java Vigenère Cipher
Tagged on:             

Leave a Reply

Your email address will not be published. Required fields are marked *

By continuing to use the site, you agree to the use of cookies. You can read more about it the Cookies&Privacy Policy Section Above. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this. You can read more about it the Cookies&Privacy Policy Section.

Close