说一说ASP.NET web.config 加密及解密方法 (代码)
作者:佚名    ASP.NET网站开发编辑:admin   更新时间:2022-07-23
说一说asp.net web.config 加密及解密方法 (代码)
- ///<summary>
- ///保护web.config的加密和解密
- ///</summary>
- publicclassPRotectHelper
- {
- ///<summary>
- ///解密
- ///</summary>
- ///<paramname="pToDecrypt">加密连接字符串</param>
- ///<paramname="sKey">自定义密钥</param>
- ///<returns>解密字符串</returns>
- publicstaticstringUnProtectSection(stringpToDecrypt,stringsKey)
- {
- byte[]inputByteArray=Convert.FromBase64String(pToDecrypt);
- using(DESCryptoServiceProviderdes=newDESCryptoServiceProvider())
- {
- des.Key=ASCIIEncoding.ASCII.GetBytes(sKey);
- des.IV=ASCIIEncoding.ASCII.GetBytes(sKey);
- System.IO.MemoryStreamms=newSystem.IO.MemoryStream();
- using(CryptoStreamcs=newCryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write))
- {
- cs.Write(inputByteArray,0,inputByteArray.Length);
- cs.FlushFinalBlock();
- cs.Close();
- }
- stringstr=Encoding.UTF8.GetString(ms.ToArray());
- ms.Close();
- returnstr;
- }
- }
- ///<summary>
- ///加密
- ///</summary>
- ///<paramname="pToEncrypt">连接字符串</param>
- ///<paramname="sKey">自定义密钥</param>
- ///<returns>加密字符串</returns>
- publicstaticstringProtectSection(stringpToEncrypt,stringsKey)
- {
- using(DESCryptoServiceProviderdes=newDESCryptoServiceProvider())
- {
- byte[]inputByteArray=Encoding.UTF8.GetBytes(pToEncrypt);
- des.Key=ASCIIEncoding.ASCII.GetBytes(sKey);
- des.IV=ASCIIEncoding.ASCII.GetBytes(sKey);
- System.IO.MemoryStreamms=newSystem.IO.MemoryStream();
- using(CryptoStreamcs=newCryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write))
- {
- cs.Write(inputByteArray,0,inputByteArray.Length);
- cs.FlushFinalBlock();
- cs.Close();
- }
- stringstr=Convert.ToBase64String(ms.ToArray());
- ms.Close();
- returnstr;
- }
- }
- }