我能够将如下所示的加密示例放在一起,但在解密期间我得到无效数据(异常)。我应该如何解密
加密方式
public static string EncryptWithAes(string plainText, byte[] key, byte[] initiationVector)
{
byte[] cryptoBytes = Encoding.UTF8.GetBytes(plainText);
using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
{
aesAlgorithm.Key = key;
aesAlgorithm.IV = initiationVector;
aesAlgorithm.Mode = CipherMode.ECB;
using (ICryptoTransform encryptoTransform = aesAlgorithm.CreateEncryptor(aesAlgorithm.Key, aesAlgorithm.IV))
{
cryptoBytes = encryptoTransform.TransformFinalBlock(cryptoBytes, 0, cryptoBytes.Length);
}
}
return Convert.ToBase64String(cryptoBytes);
}
解密方法
public static string DecryptAesCryptoString(string cipherText, byte[] key, byte[] initiationVector)
{
byte[] decryptedByte;
using (RijndaelManaged aesAlgorithm = new RijndaelManaged())
{
aesAlgorithm.Key = key;
aesAlgorithm.IV = initiationVector;
aesAlgorithm.Mode = CipherMode.ECB;
using (ICryptoTransform decryptoTransform = aesAlgorithm.CreateDecryptor(aesAlgorithm.Key, aesAlgorithm.IV))
{
byte[] cipherBytes = Convert.FromBase64String(cipherText);
decryptedByte = decryptoTransform.TransformFinalBlock(cipherBytes, 0, cipherBytes.Length);
}
}
return Encoding.UTF8.GetString(decryptedByte);
}
我认为问题在于这些方法中的所有编码
样本数据
纯文本 = 堆栈溢出
base64encoded Key = B8Y/6doxwqU870C6jzYWhsr3hKSLokAOkkLCDiy+TS4=
(应该很容易转换为字节不是吗)
base64encoded IV = NZIpD60eBmdsOFFhA2bfvw==
encryptedValue = 77+977+977+977+977+9Ce+/ve+/vQ3vv70F77+9UzHvv73vv70=
我提供相同的加密值、IV 和密钥来解密到 Stackoverflow