Java: Vigenere Cipher Short Code


Home / Java: Vigenere Cipher Short Code

vigenere Source: Google Images, Wikipedia

Hey folks! for those who are searching for vigenere cipher in java implementation here is a short code.

public static String vigenere(String str, String key) 
{

    String pattern = "abcdefghijklmnopqrstuvwxyz";
    //lowercase
    str = str.toLowerCase();
    key = key.toLowerCase();

    char char_key,char_str;

    int key_index=0;
    int str_index=0;

    int j=0;

    String cyphertext="";

    for(int i=0;i<=str.length()-1;i++) 
    {

        //character position of key
        char_key = key.charAt(i);
        key_index = pattern.indexOf(char_key);

        //character position of str
        char_str = str.charAt(i);
        str_index = pattern.indexOf(char_str);


        if(Character.isLetter(char_str)) 
        {       
            j = (Math.abs(key_index+str_index))%26;
            cyphertext+=pattern.charAt(j);
        }
        else 
        {
            cyphertext = cyphertext+char_str;
        }
    }

    return "Cypher text: " + cyphertext;
} 

Basic usage

System.out.println(vigenere(str,key));

Vigenere cipher works like caesars cipher but unlike ceasar, this cipher rotate each letter by an alphabetical input not by number

e.g ceasar cipher works like this

caesar text = a

ceasar rotate number = 2

ceasar output = c

the output becomes c, because letter a has been incremented by 2 (a+2 = ..b..c)

On vigenere cipher, it works like this

vigenere text = f

vigenere key = b

vigenere output = g

the output becomes g because the vigenere key is letter b. and on my code, b is positioned as number 1 (a=0 or zero) therefore (f+1 = ..g)

btw, vigenere cipher has been named after Blaise de Vigenère, but actually wikipedia said that Giovan Battista Bellaso is the one who invented it. poor guy.

okay that''s it. :)