好库网 好库网首页 | 我的好库
好饱的专栏

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

发布者:好饱
发布日期:2011/5/5 10:17:59   更新日期:2011/5/5 10:20:35
阅读次数:4192
评分:4.80
介绍:为了加密解密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>

 

 

 


评论 [发表评论]
账号 密码 还没帐号呢,现在注册一个?

免责声明:好库网所展示的信息由买卖双方自行提供,其真实性、准确性和合法性由信息发布人负责。好库网不提供任何保证,并不承担任何法律责任。