我在解密和加密字符串时遇到错误:
5duOH + Tlg5deIrWZiHoNaQ == wVxXSl9pFu6A8h14 / nLdyBkDzO4xmec7PQ0cB7MHjCDqhSRum3C7I1OfqL1rEWbNonU / ayCaJS18zV7ivQQU7A == MBJzKMrrrbmc2 / vBZSPDkQ == I09Kj25UO + LcmRzgoqTT2g == + Fkm9VCGplEK6eEyHyEtuEodKSbckC07M2FShu2ukCg =
错误如下:
输入不是有效的Base-64字符串,因为它包含非基本64个字符,两个以上的填充字符或填充字符中的非法字符。
我的加密代码是: 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)
Base64填充由=
或==
组成,因此它看起来像多个Base64字符串,以某种方式附加在一起。你必须找到它们最初结束的地方,将它们分开,然后再试一次。
请注意,Base64字符串总是只有在需要时才会有填充,所以甚至可能需要在这里看不到的地方中断。