每当我尝试在DB中调用存储密码的Decrypt函数时,我收到 Base-64字符数组或字符串的无效长度。解密代码:
public static string Decrypt(string encryptedText)
{
// byte[] cipherTextBytes = Convert.FromBase64String(encryptedText)); OLD ONE
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText.Replace(' ', '+')); //NEW
byte[] keyBytes = new Rfc2898DeriveBytes(PasswordHash, Encoding.ASCII.GetBytes(SaltKey)).GetBytes(256 / 8);
var symmetricKey = new RijndaelManaged() { Mode = CipherMode.CBC, Padding = PaddingMode.None };
var decryptor = symmetricKey.CreateDecryptor(keyBytes, Encoding.ASCII.GetBytes(VIKey));
var memoryStream = new MemoryStream(cipherTextBytes);
var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
byte[] plainTextBytes = new byte[cipherTextBytes.Length];
int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
memoryStream.Close();
cryptoStream.Close();
return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount).TrimEnd("\0".ToCharArray());
}
我发现像这样转换字符串会导致此错误:
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText)); OLD ONE
因此,应该这样做:
byte[] cipherTextBytes = Convert.FromBase64String(encryptedText.Replace(' ', '+'));
但我仍然得到相同的错误,基本上我在谷歌上找到的所有解决方案都指向这种解决方案,这对我没有帮助。任何人都可以解释它有什么问题吗?感谢。