Encrypt string in dotNet

Note: For configuration string like database connection encryption, please considering use native dotnet tool. check this:




Just want to encrypt my userId and password, then found this very helpful and basic cryptography on code project. Unfortunately, the article only provides vb code, I created my own based on author’s idea.

    public class MyCrypto

        /// <summary>
        /// Symmetric Encryption, Both the creator and the recipient of a message share
        /// a secret key that they use to encipher and decipher the message.
        /// The cipher works on blocks of a fixed length, usually 64 or 128 bits at a time,
        ///  depending on the algorithm. If the unencrypted message is greater than the
        ///  required length, the algorithm will break it down into 64 or 128-bit chunks
        ///  and XOR each chunk with the preceding chunk.
        /// There is an obvious snag to this approach. If each chunk is XORed with the
        /// previous chunk, then what will the first chunk be XORed with?
        /// IV, initialization vector, is an arbitrary chunk of bytes that is used
        // to XOR the first chunk of bytes in the unencrypted message
        /// </summary>
        private static string _rgbKeyString = "111111";
        private static string _rgbIVString = "222222";

        private static byte[] SALT_BYTES = new byte[] { 98, 1, 28, 239, 64, 30, 162, 27, 156, 102, 223 };

        public static string Encrypt(string decrypted)

            byte[] data = Encoding.ASCII.GetBytes(decrypted);
            byte[] rgbIV = Encoding.ASCII.GetBytes(_rgbIVString);

            byte[] keyStream = DerivePassword(_rgbKeyString, 8);

            DESCryptoServiceProvider desCryptoServiceProvider = new DESCryptoServiceProvider();

            // Trasnformer!
            ICryptoTransform trans = desCryptoServiceProvider.CreateEncryptor(keyStream, rgbIV);

            byte[] result = trans.TransformFinalBlock(data, 0, data.Length);

            // Clean up.

            return System.Convert.ToBase64String(result);


        public static string Decrypt(string encrypted)

            byte[] data = Convert.FromBase64String(encrypted);
            byte[] rgbIV = Encoding.ASCII.GetBytes(_rgbIVString);

            DESCryptoServiceProvider desCryptoServiceProvider = new DESCryptoServiceProvider();

            // Trasnformer!
            byte[] keyStream = DerivePassword(_rgbKeyString, 8);

            ICryptoTransform trans = desCryptoServiceProvider.CreateDecryptor(keyStream, rgbIV);

            byte[] result = null;
                result = trans.TransformFinalBlock(data, 0, data.Length);
            }catch(Exception e)
                // If the encryt data is not in the right format, this will fail.
                Debug.WriteLine("exception occurred during decryption: "+ e.Message);
                // Clean up.

            return Encoding.ASCII.GetString(result);


        private static byte[] DerivePassword( string originalPassword, int passwordLength)

            return new Rfc2898DeriveBytes(originalPassword, SALT_BYTES, 5).GetBytes(passwordLength);

    public class MyCryptoTest
        public void CanEncryptAndDescrypt()
            const string a = "test one";
            const string b = "another test";




            Assert.AreEqual(a, MyCrypto.Decrypt(MyCrypto.Encrypt(a)));
            Assert.AreEqual(b, MyCrypto.Decrypt(MyCrypto.Encrypt(b)));



Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s