说一说ASP.NET web.config 加密及解密方法 (代码)

8/10/2015来源:ASP.NET技巧人气:1970

说一说asp.net web.config 加密及解密方法 (代码)

  1. ///<summary>
  2. ///保护web.config的加密和解密
  3. ///</summary>
  4. publicclassPRotectHelper
  5. {
  6. ///<summary>
  7. ///解密
  8. ///</summary>
  9. ///<paramname="pToDecrypt">加密连接字符串</param>
  10. ///<paramname="sKey">自定义密钥</param>
  11. ///<returns>解密字符串</returns>
  12. publicstaticstringUnProtectSection(stringpToDecrypt,stringsKey)
  13. {
  14. byte[]inputByteArray=Convert.FromBase64String(pToDecrypt);
  15. using(DESCryptoServiceProviderdes=newDESCryptoServiceProvider())
  16. {
  17. des.Key=ASCIIEncoding.ASCII.GetBytes(sKey);
  18. des.IV=ASCIIEncoding.ASCII.GetBytes(sKey);
  19. System.IO.MemoryStreamms=newSystem.IO.MemoryStream();
  20. using(CryptoStreamcs=newCryptoStream(ms,des.CreateDecryptor(),CryptoStreamMode.Write))
  21. {
  22. cs.Write(inputByteArray,0,inputByteArray.Length);
  23. cs.FlushFinalBlock();
  24. cs.Close();
  25. }
  26. stringstr=Encoding.UTF8.GetString(ms.ToArray());
  27. ms.Close();
  28. returnstr;
  29. }
  30. }
  31. ///<summary>
  32. ///加密
  33. ///</summary>
  34. ///<paramname="pToEncrypt">连接字符串</param>
  35. ///<paramname="sKey">自定义密钥</param>
  36. ///<returns>加密字符串</returns>
  37. publicstaticstringProtectSection(stringpToEncrypt,stringsKey)
  38. {
  39. using(DESCryptoServiceProviderdes=newDESCryptoServiceProvider())
  40. {
  41. byte[]inputByteArray=Encoding.UTF8.GetBytes(pToEncrypt);
  42. des.Key=ASCIIEncoding.ASCII.GetBytes(sKey);
  43. des.IV=ASCIIEncoding.ASCII.GetBytes(sKey);
  44. System.IO.MemoryStreamms=newSystem.IO.MemoryStream();
  45. using(CryptoStreamcs=newCryptoStream(ms,des.CreateEncryptor(),CryptoStreamMode.Write))
  46. {
  47. cs.Write(inputByteArray,0,inputByteArray.Length);
  48. cs.FlushFinalBlock();
  49. cs.Close();
  50. }
  51. stringstr=Convert.ToBase64String(ms.ToArray());
  52. ms.Close();
  53. returnstr;
  54. }
  55. }
  56. }