首页 > 代码库 > asp.net字符串加密与解密
asp.net字符串加密与解密
1 using System; 2 using System.Data; 3 using System.Configuration; 4 using System.Web; 5 using System.Web.Security; 6 using System.Web.UI; 7 using System.Web.UI.WebControls; 8 using System.Web.UI.WebControls.WebParts; 9 using System.Web.UI.HtmlControls; 10 using System.Xml ; 11 using System.Data.SqlClient; 12 using System.IO; 13 using System.Net; 14 using System.Text; 15 using System.Text.RegularExpressions; 16 using System.Security.Cryptography; 17 18 19 /// <summary> 20 /// 加密 21 /// </summary> 22 /// <param name="pToEncrypt">要加密的字符串</param> 23 /// <param name="sKey">加密密匙 例:"abcdefgh"</param> 24 /// <returns></returns> 25 public string Encrypt(string pToEncrypt) 26 { 27 string sKey = "abcdefgh"; 28 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); //把字符串放到byte数组中 29 byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt); 30 //byte[] inputByteArray=Encoding.Unicode.GetBytes(pToEncrypt); 31 des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量 32 des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); //原文使用ASCIIEncoding.ASCII方法的GetBytes方法 33 MemoryStream ms = new MemoryStream(); //使得输入密码必须输入英文文本 34 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); 35 cs.Write(inputByteArray, 0, inputByteArray.Length); 36 cs.FlushFinalBlock(); 37 StringBuilder ret = new StringBuilder(); 38 foreach (byte b in ms.ToArray()) 39 { 40 ret.AppendFormat("{0:X2}", b); 41 } 42 ret.ToString(); 43 return ret.ToString(); 44 } 45 /// <summary> 46 /// 解密 47 /// </summary> 48 /// <param name="pToDecrypt">要解密字符串</param> 49 /// <param name="sKey">解密密匙 例:"abcdefgh"</param> 50 /// <returns></returns> 51 public string Decrypt(string pToDecrypt) 52 { 53 string sKey = "abcdefgh"; 54 DESCryptoServiceProvider des = new DESCryptoServiceProvider(); 55 byte[] inputByteArray = new byte[pToDecrypt.Length / 2]; 56 for (int x = 0; x < pToDecrypt.Length / 2; x++) 57 { 58 int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16)); 59 inputByteArray[x] = (byte)i; 60 } 61 des.Key = ASCIIEncoding.ASCII.GetBytes(sKey); //建立加密对象的密钥和偏移量,此值重要,不能修改 62 des.IV = ASCIIEncoding.ASCII.GetBytes(sKey); 63 MemoryStream ms = new MemoryStream(); 64 CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); 65 cs.Write(inputByteArray, 0, inputByteArray.Length); 66 cs.FlushFinalBlock(); 67 StringBuilder ret = new StringBuilder(); //建立StringBuild对象,CreateDecrypt使用的是流对象,必须把解密后的文本变成流对象 68 return System.Text.Encoding.Default.GetString(ms.ToArray()); 69 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。