Asp.net blogs

Thursday 4 July 2013

Encrypt and Decrypt Password during Login Authentication in Asp.net

Encryption Method For Password :-

static String KeyEncryption = "PU$y*P*@$";
        public static string Encrypt(string stringToEncrypt)
        {

            String sEncryptionKey = KeyEncryption;
            byte[] key = { };
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
            byte[] inputByteArray; //Convert.ToByte(stringToEncrypt.Length)
            try
            {
                key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = System.Text.Encoding.UTF8.GetBytes(stringToEncrypt);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (System.Exception ex)
            {
                throw ex;
            }

        }


Decryption Method For Password :-

        public static  string Decrypt(string stringToEncrypt)
        {
            String sEncryptionKey = KeyEncryption;
            byte[] key = { };
            byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xab, 0xcd, 0xef };
            byte[] inputByteArray;//= Convert.ToByte(Convert.ToDouble((stringToEncrypt.Length));
            try
            {

                key = System.Text.Encoding.UTF8.GetBytes(sEncryptionKey.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                inputByteArray = Convert.FromBase64String(stringToEncrypt);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;
                String retval = encoding.GetString(ms.ToArray());
                return retval;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }

No comments:

Post a Comment