Thursday, 18 October 2012

encrypt and decrypt connection string in asp.net with c#



 #region Encryption
        public string encryptPassword(string strText)
        {
            return Encrypt(strText, "&%#@?,:*");
        }
        public string decryptPassword(string str)
        {
            return Decrypt(str, "&%#@?,:*");
        }

        private string Encrypt(string strText, string strEncrypt)
        {
            byte[] byKey = new byte[20];
            byte[] dv = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
            try
            {
                byKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                byte[] inputArray = System.Text.Encoding.UTF8.GetBytes(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, dv), CryptoStreamMode.Write);

                cs.Write(inputArray, 0, inputArray.Length);
                cs.FlushFinalBlock();
                byte[] encryptedData = ms.ToArray();
                return Convert.ToBase64String(encryptedData);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }


        private string Decrypt(string strText, string strEncrypt)
        {
            byte[] bKey = new byte[40];
            byte[] IV = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
            byte[] inputByteArray;
            try
            {
                bKey = System.Text.Encoding.UTF8.GetBytes(strEncrypt.Substring(0, 8));
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                //Byte[] inputByteArray = System.Text.Encoding.UTF8.GetBytes(strText); // new Byte[strText.Length];
                strText = strText.Replace(' ', '+');
                int len = strText.Length;
                inputByteArray = new byte[len];
                inputByteArray =Convert.FromBase64String(strText);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(bKey, IV), CryptoStreamMode.Write);

                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                System.Text.Encoding encoding = System.Text.Encoding.UTF8;

                return encoding.GetString(ms.ToArray());
            }

            catch (Exception ex)
            {
                throw ex;
            }

        }
        #endregion

No comments:

Post a Comment