Tuesday, March 19, 2013

Encryption Decryption in .NET

       Yo can do encryption decryption using various available algorithms.
       Here i have explained encryption & decryption of a string using classes in namespace System.Security.Cryptography (available in System.Security.dll). 

       You can use it in your application to encrypt user password(or any secret information) and store it in database in encrypted form so that no one can see/hack it. 
Then while using you can retrieve this encrypted password and decrypt it to get original password.

To implement it use following steps:


   1.       Add Reference to assembly : System.Security.dll
   2.       Import namespace  System.Security.Cryptography to use cryptographic classes in it.
   3.       Add the following class in your project (if required you can name it different. i have named it as Crypto)


public static class Crypto
    {
        const string secretKey = "secretKey";
      
        /// <summary>
        /// Encrypts given string using 3DES algorithm.
        /// </summary>
        /// <param name="source">string to be encrypted.</param>
        /// <returns>encrypted string</returns>
        public static string EncryptData(string source)
        {
            try
            {
                byte[] encryptedResults;
                System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
                MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
                byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(secretKey));
                TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
                TDESAlgorithm.Key = TDESKey;
                TDESAlgorithm.Mode = CipherMode.ECB;
                TDESAlgorithm.Padding = PaddingMode.PKCS7;
                byte[] DataToEncrypt = UTF8.GetBytes(source);
                try
                {
                    ICryptoTransform encryptor = TDESAlgorithm.CreateEncryptor();
                    encryptedResults = encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
                }
                finally
                {
                    TDESAlgorithm.Clear();
                    HashProvider.Clear();
                }
                return Convert.ToBase64String(encryptedResults);
            }
            catch (Exception ex)
            {
                throw;
            }
        }


        /// <summary>
        /// Decrypts given string(in encrypted format) using 3DES algorithm.
        /// </summary>
        /// <param name="encryptedString">string to be decrypted</param>
        /// <returns>decrypted string</returns>
        public static string DecryptData(string encryptedString)
        {
            try
            {
                byte[] encryptedResults;
                System.Text.UTF8Encoding UTF8 = new System.Text.UTF8Encoding();
                MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
                byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(secretKey));
                TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
                TDESAlgorithm.Key = TDESKey;
                TDESAlgorithm.Mode = CipherMode.ECB;
                TDESAlgorithm.Padding = PaddingMode.PKCS7;
                byte[] DataToDecrypt = Convert.FromBase64String(encryptedString);
                try
                {
                    ICryptoTransform decryptor = TDESAlgorithm.CreateDecryptor();
                    encryptedResults = decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
                }
                finally
                {
                    TDESAlgorithm.Clear();
                    HashProvider.Clear();
                }
                return UTF8.GetString(encryptedResults);
            }
            catch (Exception ex)
            {
                throw;
            }
        }
    }





   E.g. You can use above functions to encrypt decrypt data as follows:
         string encryptedString = Crypto.EncryptData("sourceString");
       ð  This gives encryptedString = EZfn3ur/R9kspFDMGbDZwg==
         string decryptedString = Crypto.DecryptData(encryptedString);
       ð  This gives decryptedString = sourceString





No comments:

Post a Comment