最近我遇到一個(gè)關(guān)于asp.net URL參數(shù)加密解密的問(wèn)題,在加密時(shí)沒(méi)問(wèn)題,可是解密就有問(wèn)題了,有些參數(shù)解密出來(lái)是空(并不是原來(lái)的數(shù)據(jù))。下面是一個(gè)需要加密URL參數(shù)的地 址:http://www.px?username=marry&password=marry
在index.aspx頁(yè)添加的代碼:
private static byte[] key = { };
private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
private static string EncryptionKey = "!5623a#de";
public static string Encrypt(string Input)
{
try
{
key = System.Text.Encoding.UTF8.GetBytes(EncryptionKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
Byte[] inputByteArray = Encoding.UTF8.GetBytes(Input);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch (Exception ex)
{
return "";
}
}
Response.Redirect(“http://www.px?username=” + Encrypt(marry) + "&password=" Encrypt(marry
));
在px網(wǎng)頁(yè)需要的代碼:
private static byte[] key = { };
private static byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
private static string EncryptionKey = "!5623a#de";
public static string Decrypt(string Input)
{
if (!string.IsNullOrEmpty(Input))
{
Input = Input.Replace(" ", "+");
Byte[] inputByteArray = new Byte[Input.Length];
try
{
key = System.Text.Encoding.UTF8.GetBytes(EncryptionKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(Input);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception ex)
{
return "";
}
}
else
{
return "";
}
}
在Page_Load事件中要添加的代碼:
Decrypt(Request.QueryString["username"]);
Decrypt(Request.QueryString["password"]);
總結(jié):如果去除紅色部分的代碼就會(huì)出現(xiàn)上面出現(xiàn)所說(shuō)的情況,出錯(cuò)或者解密出來(lái)的數(shù)據(jù)變成空值。
|