【发布时间】:2012-02-09 11:35:40
【问题描述】:
我能够将如下所示的加密示例放在一起,但在解密期间我得到无效数据(异常)。我应该如何解密
加密方式
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);
}
我认为问题在于这些方法中的所有编码
样本数据
plainText = 堆栈溢出
base64encoded Key = B8Y/6doxwqU870C6jzYWhsr3hKSLokAOkkLCDiy+TS4=
(应该很容易转换成字节吧)
base64encoded IV = NZIpD60eBmdsOFFhA2bfvw==
encryptedValue = 77+977+977+977+977+9Ce+/ve+/vQ3vv70F77+9UzHvv73vv70=
我向 Stackoverflow 提供相同的加密值、IV 和密钥来解密
【问题讨论】:
-
也许是愚蠢的问题,但你用什么值测试它?
-
不不,我指的是我自己的问题
-
使用堆栈跟踪发布异常并标记错误行
标签: c# .net aes sample rijndael