using System; namespace ninjacrypt { class Program { static void Main(string[] args) { RC4 rc4; while(true) { try { Console.Write("Key: "); rc4 = new RC4(Console.ReadLine()); Console.Write("Message: "); rc4.HexDump(rc4.Encrypt(Console.ReadLine())); } catch (RC4.NullKey) { break; } } } } class RC4 { private byte i, j; public byte[] state = new byte[256]; public char[] key; public class NullKey : Exception { } void swap(ref T i, ref T j) { T temp; temp = i; i = j; j = temp; } public RC4(string Key) { if (Key.Length == 0) throw new NullKey(); key = Key.ToCharArray(); // Generate the IV for the stream cipher for (i = 1;i != 0;++i) state[i] = i; j = (byte) key[0]; swap(ref state[0],ref state[j]); for (i = 1; i != 0; ++i) { j += (byte) (state[i] + (byte)key[i % key.Length]); swap(ref state[i],ref state[j]); } i = 0; j = 0; } byte keybyte { get { ++i; j += state[i]; swap(ref state[i],ref state[j]); return state[(state[i] + state[j]) & 255]; } } public string Encrypt(string plaintext) { string cyphertext = ""; foreach (byte m in plaintext) cyphertext += (char)(m ^ keybyte); return cyphertext; } public void HexDump(string str) { foreach (byte c in str) { Console.Write("{0:X2} ", c); } Console.Write("\n{0}\n",str); } } }