Simple encryption and decryption of a string in c#

Here are some routines which are designed for simple use of Rijndael in C#. I’ve combined a test function in the class for simplicity of showing it’s use.

        private static byte[] salt = Encoding.ASCII.GetBytes("somerandomstuff");

        public static string Encrypt(string plainText, string keyString)
        {
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(keyString, salt);

            MemoryStream ms = new MemoryStream();
            StreamWriter sw = new StreamWriter(new CryptoStream(ms, new RijndaelManaged().CreateEncryptor(key.GetBytes(32), key.GetBytes(16)), CryptoStreamMode.Write));
            sw.Write(plainText);
            sw.Close();
            ms.Close();
            return Convert.ToBase64String(ms.ToArray());
        }

        public static string Decrypt(string base64Text, string keyString)
        {
            Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(keyString, salt);

            ICryptoTransform d = new RijndaelManaged().CreateDecryptor(key.GetBytes(32), key.GetBytes(16));
            byte[] bytes = Convert.FromBase64String(base64Text);
            return new StreamReader(new CryptoStream(new MemoryStream(bytes), d, CryptoStreamMode.Read)).ReadToEnd();
        }

        public static void Main(string[] args)
        {
            string key = "a text phrase";

            string encrypted = Encrypt("test", key);
            string decrypted = Decrypt(encrypted, key);

            Console.WriteLine("Encrypted: {0}\r\nDecrypted: {1}\r\n", encrypted,decrypted);
            Console.ReadLine();  //Just to keep the CMD console window from closing before you see the results.
        }

Here is the output of the program above:

Encrypted: +Ya4VL06hYVU7T4uAHJG2A==
Decrypted: test

Leave a Reply