Encryption and Decryption in C#

 

Microsoft Visual Studio has several security algorithms to Encrypt the data. Today we discuss about how to encrypt and decrypt the string data in C#.

 

Open Microsoft Visual Studio => Create New Web Application and name it as CSharpEncryptDecrypt.

 

Now add EncryptDecryptString class as shown below which has two methods to encrypt and decrypt the data.

 

using System;

using System.IO;

using System.Security.Cryptography;

using System.Text;

 

namespace CSharpEncryptDecrypt

{

    public class EncryptDecryptString

    {

        private static byte[] _salt = Encoding.ASCII.GetBytes("o6806642kbM7c5");

 

        public static string EncryptString(string plainText, string sharedSecret)

        {

            if (string.IsNullOrEmpty(plainText))

                throw new ArgumentNullException("plainText");

            if (string.IsNullOrEmpty(sharedSecret))

                throw new ArgumentNullException("sharedSecret");

 

            string outStr = null;                       // Encrypted string to return

            RijndaelManaged aesAlg = null;              // RijndaelManaged object used to encrypt the data.

 

            try

            {

                // generate the key from the shared secret and the salt

                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

 

                // Create a RijndaelManaged object

                aesAlg = new RijndaelManaged();

                aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

 

                // Create a decryptor to perform the stream transform.

                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

 

                // Create the streams used for encryption.

                using (MemoryStream msEncrypt = new MemoryStream())

                {

                    // prepend the IV

                    msEncrypt.Write(BitConverter.GetBytes(aesAlg.IV.Length), 0, sizeof(int));

                    msEncrypt.Write(aesAlg.IV, 0, aesAlg.IV.Length);

                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))

                    {

                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))

                        {

                            //Write all data to the stream.

                            swEncrypt.Write(plainText);

                        }

                    }

                    outStr = Convert.ToBase64String(msEncrypt.ToArray());

                }

            }

            finally

            {

                // Clear the RijndaelManaged object.

                if (aesAlg != null)

                    aesAlg.Clear();

            }

 

            // Return the encrypted bytes from the memory stream.

            return outStr;

        }

 

        public static string DecryptString(string cipherText, string sharedSecret)

        {

            if (string.IsNullOrEmpty(cipherText))

                throw new ArgumentNullException("cipherText");

            if (string.IsNullOrEmpty(sharedSecret))

                throw new ArgumentNullException("sharedSecret");

 

            // Declare the RijndaelManaged object

            // used to decrypt the data.

            RijndaelManaged aesAlg = null;

 

            // Declare the string used to hold

            // the decrypted text.

            string plaintext = null;

 

            try

            {

                // generate the key from the shared secret and the salt

                Rfc2898DeriveBytes key = new Rfc2898DeriveBytes(sharedSecret, _salt);

 

                // Create the streams used for decryption.                

                byte[] bytes = Convert.FromBase64String(cipherText);

                using (MemoryStream msDecrypt = new MemoryStream(bytes))

                {

                    // Create a RijndaelManaged object

                    // with the specified key and IV.

                    aesAlg = new RijndaelManaged();

                    aesAlg.Key = key.GetBytes(aesAlg.KeySize / 8);

                    // Get the initialization vector from the encrypted stream

                    aesAlg.IV = ReadByteArray(msDecrypt);

                    // Create a decrytor to perform the stream transform.

                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);

                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))

                    {

                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))

 

                            // Read the decrypted bytes from the decrypting stream

                            // and place them in a string.

                            plaintext = srDecrypt.ReadToEnd();

                    }

                }

            }

            finally

            {

                // Clear the RijndaelManaged object.

                if (aesAlg != null)

                    aesAlg.Clear();

            }

 

            return plaintext;

        }

 

        private static byte[] ReadByteArray(Stream s)

        {

            byte[] rawLength = new byte[sizeof(int)];

            if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)

            {

                throw new SystemException("Stream did not contain properly formatted byte array");

            }

 

            byte[] buffer = new byte[BitConverter.ToInt32(rawLength, 0)];

            if (s.Read(buffer, 0, buffer.Length) != buffer.Length)

            {

                throw new SystemException("Did not read byte array properly");

            }

            return buffer;

        }

    }

}

 

Now call these Encrypt and Decrypt methods by passing input string t Encrypt method as shown below.

 

using System;

 

namespace CSharpEncryptDecrypt

{

    public partial class WebForm1 : System.Web.UI.Page

    {

        protected void Page_Load(object sender, EventArgs e)

        {

            string sEncryptString = EncryptDecryptString.EncryptString("This is String Before Encryption", "ES");

 

            string sDecryptString = EncryptDecryptString.DecryptString(sEncryptString, "ES");

        }

    }

}

 

Here "ES" is the security key to encrypt and decrypt the string data. After decrypting the sEncryptString variable, the variable sDecryptString contains the data as "This is String Before Encryption".

                                                                                                           

                                                                                                              CSharpEncryptDecrypt.zip (13.49 kb)