在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"]);
总结:如果去除红色部分的代码就会出现上面出现所说的情况,出错或者解密出来的数据变成空值。