.Net framework 4.0的网络应用程序。 要加密和解密查询字符串,请使用以下代码块。 有趣的是,当我尝试解密一个字符串时,例如
string a = "username=testuser&email=testmail@yahoo.com"
解密后
string b = "username=testuser&email=testmail@yahoo.com\0\0\0\0\0\0\0\0\0\0\0"
我不确定为什么“\ 0”会附加到我的解密值。
我该如何防止这种情况?
我用于encypt和解密的代码块是 -
public string EncryptQueryString(string inputText, string key, string salt)
{
byte[] plainText = Encoding.UTF8.GetBytes(inputText);
using (RijndaelManaged rijndaelCipher = new RijndaelManaged())
{
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(key), Encoding.ASCII.GetBytes(salt));
using (ICryptoTransform encryptor = rijndaelCipher.CreateEncryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
{
cryptoStream.Write(plainText, 0, plainText.Length);
cryptoStream.FlushFinalBlock();
string base64 = Convert.ToBase64String(memoryStream.ToArray());
// Generate a string that won't get screwed up when passed as a query string.
string urlEncoded = HttpUtility.UrlEncode(base64);
return urlEncoded;
}
}
}
}
}
public string DecryptQueryString(string inputText, string key, string salt)
{
byte[] encryptedData = Convert.FromBase64String(inputText);
PasswordDeriveBytes secretKey = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(key), Encoding.ASCII.GetBytes(salt));
using (RijndaelManaged rijndaelCipher = new RijndaelManaged())
{
using (ICryptoTransform decryptor = rijndaelCipher.CreateDecryptor(secretKey.GetBytes(32), secretKey.GetBytes(16)))
{
using (MemoryStream memoryStream = new MemoryStream(encryptedData))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
{
byte[] plainText = new byte[encryptedData.Length];
cryptoStream.Read(plainText, 0, plainText.Length);
string utf8 = Encoding.UTF8.GetString(plainText);
return utf8;
}
}
}
}
}
答案 0 :(得分:2)
更改以下行:
cryptoStream.Read(plainText, 0, plainText.Length);
string utf8 = Encoding.UTF8.GetString(plainText);
return utf8;
到
StringBuilder outputValue = new StringBuilder();
byte[] buffer = new byte[1024];
int readCount = cryptoStream.Read(buffer, 0, buffer.Length);
while (readCount > 0) {
outputValue.Append(Encoding.UTF8.GetString(buffer, 0, readCount));
readCount = cryptoStream.Read(buffer, 0, buffer.Length);
}
return outputValue.ToString();
上述的另一个版本:
String outputValue = String.Empty;
using ( MemoryStream outputStream = new MemoryStream() ) {
byte[] buffer = new byte[1024];
int readCount = 0;
while ((readCount = cryptoStream.Read(buffer, 0, buffer.Length)) > 0) {
outputStream.Write(buffer, 0, readCount);
}
return Encoding.Unicode.GetString(outputStream.ToArray());
}
基本上,Read会附加空字符来填充字符串。通过将其限制为实际的解密字符数,您将获得唯一的原始字符串。
以上考虑到cryptoStream.Read可能无法一次读取整个字符串。我还没有测试过(今天晚些时候),但它看起来不错。