带有.Net Framework 4.0的Net应用程序。
为了加密和解密查询字符串,我使用下面的代码块。
有趣的是,例如,当我尝试解密字符串时
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”附加到我的解密值中。
我该如何预防呢?
我用于加密和解密的代码块是-
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;
}
}
}
}
}
最佳答案
更改以下行:
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可能不会一次读取整个字符串。我尚未对此进行测试(将在今天晚些时候进行测试),但是看起来不错。
关于c# - 加密和解密查询字符串会导致附加未知文本,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18851715/