Sunday, May 14, 2006

Crypto with Schneier

{

A coworker loaned me Bruce Schneier's Applied Cryptography. So far it's a very interesting book, and surprisingly readable. I may see if I can work my way through various forms of encryption but translate his samples to C#. Here's a version of a substitution cipher that uses XOR operations in C# (make sure you're using System.Text):

private static string Cipher(byte key, string plainText)
{
byte[] plain = ASCIIEncoding.ASCII.GetBytes(plainText);
byte[] ciph = new byte[plain.Length];
for (int i = 0; i < plain.Length; i++)
{
ciph[i] = (byte)(++key ^ plain[i]);
}

string cipherText = ASCIIEncoding.ASCII.GetString(ciph);
return cipherText;
}

To decrypt, if you have the key:

private static string Decipher(byte key, string cipherText)
{
byte[] ciph = ASCIIEncoding.ASCII.GetBytes(cipherText);
byte[] plain = new byte[ciph.Length];
for (int i = 0; i < ciph.Length; i++)
{
plain[i] = (byte)(++key ^ ciph[i]);
}

string plainText = ASCIIEncoding.ASCII.GetString(plain);
return plainText;
}

Back to my earlier comment on Schneier being readable, his comments on this approach are as follows:

"... the list of software vendors that tout this toy algorithm as being "almost as secure as DES" is staggering... An XOR might keep your kid sister from reading your files, but it won't stop a cryptanalyst for more than a few minutes."


}

No comments: