/r/dailyprogrammer – Stream Cipher

This time around I thought the stream cipher programming challenge sounded like fun. The program encodes a character string and then decodes it back to the original text using the RC4 method. Below is an example input/output, followed by the code.

CipherOutput

class Program
{
    static void Main(string[] args)
    {
        const int KEY = 31337;
        string message = "High five, bro";

        Console.WriteLine("----Stream Cipher----\n");
        Console.WriteLine("Original Message: " + message + "\n");

        var cipherText = encrypt(message, KEY);
        Console.WriteLine("Cipher Text: " + cipherText + "\n");

        var plainText = decrypt(cipherText, KEY);
        Console.WriteLine("Plain Text: " + plainText);

        Console.ReadLine();
    }

    static string encrypt( string msg, int key )
    {
        int seed = key;
        int m = 255;
        int a = 124;
        int c = 32;
        byte[] bytes = Encoding.Default.GetBytes(msg);
        var value = ((seed * a) + c) % m;

        for (var b = 0; b < bytes.Length; ++b )
        {
            bytes[b] ^= (byte)value;
        }

        return Encoding.Default.GetString(bytes);
    }

    static string decrypt(string cipher, int key)
    {
        return encrypt(cipher, key);
    }
}
Bookmark and Share

Leave a Reply

Subscribe to RSS feed FGS5 Badge