Vigenère Cipher helpers


Here you can generate a Vigenère cipher or solve an existing one if you have the key.


Remember that the accepted chars are ABCDEFGHIJKLMNOPQRSTUVWXYZ.


Genererate cipher



Plaintext/message:






Key:













Solve cipher



Ciphertext:






Key:












The algorithm

The Vigenère algorithm is pretty easy to understand, have a look at the Wikipedia page for an explanation.

I implemented it in Javascript for this page. Here’s source:

var Vigenere = {
    chars: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    generate: function(str, key)
    {   
        return this.runString(str, key, 'getCharDiffGenerate');
    },
    solve: function(str, key)
    {
        return this.runString(str, key, 'getCharDiffSolve');
    },
    runString: function(str, key, diff_function)
    {
        var pattern = new RegExp('^([' + this.chars + ']+)$', 'i'); 
        if(!pattern.test(str) || !pattern.test(key))
            return 'Not valid input. Valid chars are: ' + this.chars + '. No spaces.';

        var str = str.toUpperCase();    
        var key = this.padKey(str.length, key.toUpperCase());
        var out = '';

        for(var i = 0; i < str.length; i++)
        {
            var ref_char_index = this.chars.indexOf(str.charAt(i));
            var key_char_index = this.chars.indexOf(key.charAt(i));

            var result_index = this[diff_function](ref_char_index, key_char_index);
            var result_char = this.chars.charAt(result_index);
            out = out + result_char;
        }
        return out;
    },
    getCharDiffSolve: function(p_index, c_index)
    {
        if(p_index >= c_index)
            return p_index - c_index;

        return p_index - (c_index - this.chars.length);
    },
    getCharDiffGenerate: function(p_index, c_index)
    {
        return (p_index + c_index)%this.chars.length;
    },
    padKey: function(len, key)
    {
        if(len == key.length)
            return key;

        if(len < key.length)
            return key.substring(0, len);

        return this.padKey(len, key + '' + key);
    }
}