using System; using System.Text; using Cyfer; class Test { private static byte[] String2Bytes(string s) { char[] tmp = s.ToCharArray(); byte[] res = new byte[tmp.Length]; for (int i = 0; i < tmp.Length; i++) res[i] = (byte) tmp[i]; return res; } private static string Bytes2String(byte[] data) { char[] tmp = new char[data.Length]; for (int i = 0; i < data.Length; i++) tmp[i] = (char) data[i]; return new string(tmp); } private static string Bytes2Hex(byte[] data) { StringBuilder sb = new StringBuilder(data.Length * 2); for (int i = 0; i < data.Length; i++) { string s = data[i].ToString("x"); if (s.Length < 2) s = "0" + s; sb.Append(s); } return sb.ToString(); } private static bool HashTest() { Hash h = new Hash("MD5"); h.Update(String2Bytes("Hello World")); string md = Bytes2Hex(h.Finish()); if (md.Equals("b10a8db164e0754105b7a99be72e3fe5")) return true; return false; } private static bool BlockCipherTest() { BlockCipher b = new BlockCipher("Blowfish", String2Bytes("Forty-two")); byte[] plaintext = String2Bytes("01234567"); byte[] ciphertext = b.Encrypt(plaintext); byte[] result = b.Decrypt(ciphertext); if (Bytes2String(result).Equals(Bytes2String(plaintext))) return true; return false; } private static bool BlockModeTest() { byte[] plaintext = String2Bytes("A quick brown fox jumps over the lazy dog."); byte[] ciphertext = new byte[plaintext.Length]; byte[] result = new byte[plaintext.Length]; BlockCipher b = new BlockCipher("Blowfish", String2Bytes("Forty-two"), "OFB", null); for (int i = 0; i < plaintext.Length; i++) { byte[] x = new byte[1]; x[0] = plaintext[i]; x = b.Encrypt(x); ciphertext[i] = x[0]; } BlockCipher c = new BlockCipher("Blowfish", String2Bytes("Forty-two"), "OFB", null); for (int i = 0; i < plaintext.Length; i++) { byte[] x = new byte[1]; x[0] = ciphertext[i]; x = c.Decrypt(x); result[i] = x[0]; } if (Bytes2String(result).Equals(Bytes2String(plaintext))) return true; return false; } private static bool StreamCipherTest() { StreamCipher s = new StreamCipher("RC4", String2Bytes("Forty-two")); byte[] plaintext = String2Bytes("A quick brown fox jumps over the lazy dog."); byte[] ciphertext = s.Encrypt(plaintext); StreamCipher t = new StreamCipher("RC4", String2Bytes("Forty-two")); byte[] result = t.Decrypt(ciphertext); if (Bytes2String(result).Equals(Bytes2String(plaintext))) return true; return false; } public static void Main(string[] args) { Console.Write("Testing hash .. "); if (HashTest()) Console.WriteLine("passed"); else Console.WriteLine("failed"); Console.Write("Testing block cipher .. "); if (BlockCipherTest()) Console.WriteLine("passed"); else Console.WriteLine("failed"); Console.Write("Testing block mode .. "); if (BlockModeTest()) Console.WriteLine("passed"); else Console.WriteLine("failed"); Console.Write("Testing stream cipher .. "); if (StreamCipherTest()) Console.WriteLine("passed"); else Console.WriteLine("failed"); } }