我正在使用以下代码加密/解密一些纯文本。
private static string EncryptionKey = "@#$%^&*()2343";
private static byte[] Salt = Encoding.ASCII.GetBytes(EncryptionKey.Length.ToString());
public static string EncryptIt(string Input)
{
RijndaelManaged Cipher = new RijndaelManaged();
byte[] TextByteArray = Encoding.Unicode.GetBytes(Input);
PasswordDeriveBytes Key = new PasswordDeriveBytes(EncryptionKey, Salt);
using (ICryptoTransform Transform = Cipher.CreateEncryptor(Key.GetBytes(32), Key.GetBytes(16)))
{
using (MemoryStream MS = new MemoryStream())
{
using (CryptoStream CS = new CryptoStream(MS, Transform, CryptoStreamMode.Write))
{
CS.Write(TextByteArray, 0, TextByteArray.Length);
CS.FlushFinalBlock();
return Convert.ToBase64String(MS.ToArray());
}
}
}
}
public static string DecryptIt(string Input)
{
RijndaelManaged Cipher = new RijndaelManaged();
byte[] EncryptedByteArray = Convert.FromBase64String(Input);
PasswordDeriveBytes Key = new PasswordDeriveBytes(EncryptionKey, Salt);
using (ICryptoTransform Transform = Cipher.CreateDecryptor(Key.GetBytes(32), Key.GetBytes(16)))
{
using (MemoryStream MS = new MemoryStream(EncryptedByteArray))
{
using (CryptoStream cryptoStream = new CryptoStream(MS, Transform, CryptoStreamMode.Read))
{
byte[] TransformedText = new byte[EncryptedByteArray.Length];
int Count = cryptoStream.Read(TransformedText, 0, TransformedText.Length);
return Encoding.Unicode.GetString(TransformedText, 0, Count);
}
}
}
}
在大多数情况下,此代码可以正常工作。但是,在某些情况下,当我尝试解密加密文本时,byte[] EncryptedByteArray = Convert.FromBase64String(Input)
在DecryptIt
方法中调用时会出现以下异常。
输入不是有效的 Base-64 字符串,因为它包含非 base 64 字符、两个以上的填充字符或填充字符中的非空白字符。
任何想法可能导致此异常。我发现更令人费解的是,为什么这个异常并没有出现在每个案例上,而且只有少数案例。
编辑: 下面是引发异常的 DecryptIt 方法的示例输入。请注意,我在上面的示例中更改了 EncryptionKey 变量的值。
oaOQ6qWWDwWby3C04N7HJAiqQgILBifqdHq4OQ5KDDRA3F2ZlBITu31a8mJJQ8sKn4g3vODFEJbigtNZozv6ockAdsDChhHwaaLL4l8MJPKbV1EiUE3rL30y+xHz/S1a8mJJQ8sKn4g3vODFEJbigtNZozv6ockAdsDChhHwaaLL4l8MJPKbV1EiUE3rL30y+oz/eR9OzXn+3Lepo0tRqH5BsfvEtJ/IcqRu3gJiIBTMAM0TmVxa2EZSj2mn6jZlgvlOEFCWzNKS3R9OzXn+In1br14venJmpApXyt930khz35UE5BtWn3Fq7jyer6mY2l60P/cI4z