说三道四技术文摘-感悟人生的经典句子
说三道四 > 文档快照

ASP.NET如何加密/解密URL网址

HTML文档下载 WORD文档下载 PDF文档下载
为了加密解密URL网址,我写一个CryptorEngine封装类以方便使用

下载源代码

 

为了加密解密URL网址,我写一个CryptorEngine封装类以方便使用,该类用到了System.Security.Cryptography命名空间,具体请看代码?

 

包含加密解密功能的类

 

using System;using System.IO;using System.Xml;using System.Text;using System.Security.Cryptography;using System.Configuration;public class CryptorEngine{//加密数据public static string Encrypt(string toEncrypt, bool useHashing){	byte[] keyArray;	byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);	// 从web.config中读出加密密钥	System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();	string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));	if (useHashing)	{		MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();		keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));		hashmd5.Clear();	}	else		keyArray = UTF8Encoding.UTF8.GetBytes(key);	TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();	tdes.Key = keyArray;	tdes.Mode = CipherMode.ECB;	tdes.Padding = PaddingMode.PKCS7;	ICryptoTransform cTransform = tdes.CreateEncryptor();	byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);	tdes.Clear();	return Convert.ToBase64String(resultArray, 0, resultArray.Length);}// 解密字符串public static string Decrypt(string cipherString, bool useHashing){	byte[] keyArray;	cipherString = cipherString.Replace(" ", "+");	byte[] toEncryptArray = Convert.FromBase64String(cipherString);	// 取得密钥	System.Configuration.AppSettingsReader settingsReader = new AppSettingsReader();	string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));	if (useHashing)	{		MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();		keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));		hashmd5.Clear();	}	else		keyArray = UTF8Encoding.UTF8.GetBytes(key);	TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();	tdes.Key = keyArray;	tdes.Mode = CipherMode.ECB;	tdes.Padding = PaddingMode.PKCS7;	ICryptoTransform cTransform = tdes.CreateDecryptor();	byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);	tdes.Clear();	return UTF8Encoding.UTF8.GetString(resultArray);}}

在Web.config中,我们需要指定密钥,例如:

 

<appSettings>  <add key="SecurityKey" value="!#$a54?3"/></appSettings>

 

 

 

备案号:鲁ICP备13029499号-2 说三道四 www.s3d4.cn 说三道四技术文摘