Tuesday, 7 April 2015

Encryption and decryption password in asp.net c#


Encrypting the password before string to the database, it’s more often that if there is plain string there is chances of hack your system by Hackers.  It will be tough for them to crack it if the password is looking like weird charter symbols.
e.g. If you store the password “test1234” to database and it will store  like; g+yC22ZOR8iB5gdYvhkZcQ==

Sharing you the simple method which is using the MD5 algorithm to encrypt the password and any provided string. MD5CryptoServiceProvider class return the hash as an array of 16 bytes.
Example computes the MD5 hash value of a string and returns the hash value in hexadecimal-formatted string. 
 MD5 is the base class and it's abstract which is using by MD5CryptoServiceProvider .

public sealed class MD5CryptoServiceProvider : MD5

You need to import the two namespace for implementing the below code;
using System.Security.Cryptography;
using System.Text;

And there usingine TripleDESCryptoServiceProvider which is using the triple des algorithm.
TripleDESCryptoServiceProvider class is used to encrypt/ decrypt keys which in turn uses 3DES (Triple Data Encryption Standard) algorithm.
public sealed class TripleDESCryptoServiceProvider : TripleDES

You need to define the passphrase which will be any string as like below;
const string passphrase = "userpassword";

C# code snippet;
public partial class encryptPassword : System.Web.UI.Page
    {
        const string passphrase = "userpassword";
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnEncrypt_Click(object sender, EventArgs e)
        {
            string encrypt = encryptPassword.EncryptPassword(txtEncypt.Text);
            lblEncrypted.Text = encrypt;
            lblPlain.Text = DecryptPassword(encrypt);
        }

       /// <summary>
        /// code for encrypt the password;
       /// </summary>
       /// <param name="Message"></param>
       /// <returns></returns>
        public static string EncryptPassword(string Message)
        {
            byte[] encryptResults;
            UTF8Encoding UTF8 = new UTF8Encoding();
            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
            byte[] DataToEncrypt = UTF8.GetBytes(Message); /// it will encrypt your message
            try
            {
                ICryptoTransform Encryptor = TDESAlgorithm.CreateEncryptor();
                encryptResults = Encryptor.TransformFinalBlock(DataToEncrypt, 0, DataToEncrypt.Length);
            }
            finally
            {
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }
            return Convert.ToBase64String(encryptResults);
        }

        /// <summary>
        /// Code for Decrypt the password
        /// </summary>
        /// <param name="Message"></param>
        /// <returns></returns>
        public static string DecryptPassword(string Message)
        {
            byte[] Results;
            UTF8Encoding UTF8 = new UTF8Encoding();
            MD5CryptoServiceProvider HashProvider = new MD5CryptoServiceProvider();
            byte[] TDESKey = HashProvider.ComputeHash(UTF8.GetBytes(passphrase));
            TripleDESCryptoServiceProvider TDESAlgorithm = new TripleDESCryptoServiceProvider();
            TDESAlgorithm.Key = TDESKey;
            TDESAlgorithm.Mode = CipherMode.ECB;
            TDESAlgorithm.Padding = PaddingMode.PKCS7;
            byte[] DataToDecrypt = Convert.FromBase64String(Message); /// it will dycrpt your message
            try
            {
                ICryptoTransform Decryptor = TDESAlgorithm.CreateDecryptor();
                Results = Decryptor.TransformFinalBlock(DataToDecrypt, 0, DataToDecrypt.Length);
            }
            finally
            {
                TDESAlgorithm.Clear();
                HashProvider.Clear();
            }
            return UTF8.GetString(Results);
        }
    }
}

Code Snippet for asp
<head runat="server">
    <title></title>

    <style type="text/css">
        .border {
            float: left;
            width: 300px;
            margin: 10px;
            padding: 10px;
            border: 1px solid #ccc;
        }

        h2 {
            margin-left: 5px;
        }

        .clearfix:after {
            content: ".";
            display: block;
            clear: both;
            visibility: hidden;
            line-height: 0;
            height: 0;
        }

        .clearfix {
            display: inline-block;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <div class="clearfix">

                <h2>Encryption Example</h2>

                <div style="float: left; width: 340px;">
                    <div class="border">
                        <h3>Password To Encrypt</h3>
                        <p>
                            <asp:TextBox ID="txtEncypt" runat="server" Width="248px"></asp:TextBox>
                        </p>
                        <p>
                            <asp:Button ID="btnEncrypt" runat="server" Text="Submit" OnClick="btnEncrypt_Click"></asp:Button>
                        </p>
                    </div>

                </div>

                <div class="border">
                    <h3>encrypted</h3>
                    <p>
                        <asp:Label ID="lblEncrypted" runat="server" />
                    </p>
                    <h3>Plain</h3>
                    <p>
                        <asp:Label ID="lblPlain" runat="server" />
                    </p>
                </div>


            </div>
        </div>
    </form>
</body>

You can see the UI as like below;
Enter the password on text character and click on the button it will convert to the encrypted text and plain text;



1 comment: