Vigenere Cipher C# Implementation 11-01-2013, 02:52 AM
#1
Here's some C# code I wrote for the Vigenere Cipher, which is essentially an extended implementation of the Ceasar Cipher algorithm.
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
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
ArkPhaze
"Object oriented way to get rich? Inheritance"
Getting Started: C/C++ | Common Mistakes
[ Assembly / C++ / .NET / Haskell / J Programmer ]
"Object oriented way to get rich? Inheritance"
Getting Started: C/C++ | Common Mistakes
[ Assembly / C++ / .NET / Haskell / J Programmer ]