您的位置:首页 > 编程语言 > ASP

asp.net URL参数加密解密的问题

2010-10-09 20:48 519 查看
最近我遇到一个关于asp.net
URL参数加密解密的问题,在加密时没问题,可是解密就有问题了,有些参数解密出来是空(并不是原来的数据)。下面是一个需要加密URL参数的地
址:http://www.website.aspx?username=marry&password=marry

在index.aspx页添加的代码:

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.website.aspx?username=” + Encrypt(marry) + "&password=" Encrypt(marry

));

在website.aspx网页需要的代码:

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"]);

总结:如果去除红色部分的代码就会出现上面出现所说的情况,出错或者解密出来的数据变成空值。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: