Sinisterly
Vigenere Cipher C# Implementation - Printable Version

+- Sinisterly (https://sinister.ly)
+-- Forum: Coding (https://sinister.ly/Forum-Coding)
+--- Forum: Visual Basic & .NET Framework (https://sinister.ly/Forum-Visual-Basic-NET-Framework)
+--- Thread: Vigenere Cipher C# Implementation (/Thread-Vigenere-Cipher-C-Implementation)



Vigenere Cipher C# Implementation - ArkPhaze - 11-01-2013

Here's some C# code I wrote for the Vigenere Cipher, which is essentially an extended implementation of the Ceasar Cipher algorithm.

Code:
static void VigenereEncrypt(ref StringBuilder s, string key)
{
    for (int i = 0; i < s.Length; i++) s[i] = Char.ToUpper(s[i]);
    key = key.ToUpper();
    int j = 0;
    for (int i = 0; i < s.Length; i++)
    {
        if (Char.IsLetter(s[i]))
        {
            s[i] = (char)(s[i] + key[j] - 'A');
            if (s[i] > 'Z') s[i] = (char)(s[i] - 'Z' + 'A' - 1);
        }
        j = j + 1 == key.Length ? 0 : j + 1;
    }
}

static void VigenereDecrypt(ref StringBuilder s, string key)
{
    for (int i = 0; i < s.Length; i++) s[i] = Char.ToUpper(s[i]);
    key = key.ToUpper();
    int j = 0;
    for (int i = 0; i < s.Length; i++)
    {
        if (Char.IsLetter(s[i]))
        {
            s[i] = s[i] >= key[j] ?
                      (char)(s[i] - key[j] + 'A') :
                      (char)('A' + ('Z' - key[j] + s[i] - 'A') + 1);
        }
        j = j + 1 == key.Length ? 0 : j + 1;
    }
}

public static void MainMethod()
{
    StringBuilder s = new StringBuilder("ArkPhaze");
    const string key = "KeyData";
    VigenereEncrypt(ref s, key);
    Console.WriteLine(s);
    VigenereDecrypt(ref s, key);
    Console.WriteLine(s);
}

Methods and demo usage in code above.

Note: Numeric values in the key will screw up the encryption, and thus the decryption however. Only use letters. I could've thrown an exception in that case, but I'll leave it up to you as to what you want to do with that.


enjoy