AES单发API解密如果没有加密的话
我正在尝试使用新的.NET 6 AES一次性API。
以下示例按预期工作:
using System.Security.Cryptography;
string key = "1234567890123456";
byte[] keyBytes = Encoding.ASCII.GetBytes(key);
string dec = "Hello One-Shot API!";
byte[] decBytes = Encoding.ASCII.GetBytes(dec);
// Encrypt
using Aes aes = Aes.Create();
byte[] encBytes = aes.EncryptCbc(decBytes, keyBytes);
// Decrypt again
byte[] recBytes = aes.DecryptCbc(encBytes, keyBytes);
string rec = Encoding.ASCII.GetString(recBytes);
Debug.Assert(rec == dec);
但是,如果我创建一个新 Aes
实例来调用 DecryptCbc
,它会抛出 System.Security .Cryptography.CryptographicException:填充无效且无法删除。
异常:
...
// Encrypt
using Aes aes = Aes.Create();
byte[] encBytes = aes.EncryptCbc(decBytes, keyBytes);
// Decrypt again - this time with new instance
using Aes aes2 = Aes.Create();
byte[] recBytes = aes2.DecryptCbc(encBytes, keyBytes); // <- throws
...
我在这里遗漏了什么吗?调用 EncryptCbc
时,Aes
实例中是否设置了仅用于解密时不存在的状态?我是否必须保留 Aes
实例,如果我之前没有使用它进行加密,那么最初如何使用它进行解密?
I'm attempting to roundtrip crypting some data with the new .NET 6 AES one-shot APIs.
The following example works as expected:
using System.Security.Cryptography;
string key = "1234567890123456";
byte[] keyBytes = Encoding.ASCII.GetBytes(key);
string dec = "Hello One-Shot API!";
byte[] decBytes = Encoding.ASCII.GetBytes(dec);
// Encrypt
using Aes aes = Aes.Create();
byte[] encBytes = aes.EncryptCbc(decBytes, keyBytes);
// Decrypt again
byte[] recBytes = aes.DecryptCbc(encBytes, keyBytes);
string rec = Encoding.ASCII.GetString(recBytes);
Debug.Assert(rec == dec);
But if I create a new Aes
instance to call DecryptCbc
on, it throws a System.Security.Cryptography.CryptographicException: Padding is invalid and cannot be removed.
exception:
...
// Encrypt
using Aes aes = Aes.Create();
byte[] encBytes = aes.EncryptCbc(decBytes, keyBytes);
// Decrypt again - this time with new instance
using Aes aes2 = Aes.Create();
byte[] recBytes = aes2.DecryptCbc(encBytes, keyBytes); // <- throws
...
Am I missing something here? Is there state set up in an Aes
instance when calling EncryptCbc
that doesn't exist when only using it for decryption? Do I have to keep the Aes
instance around, and then how would I use it for decryption initially if I haven't encrypted with it before?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如评论中提到的,我将 IV 参数误认为是密钥,因为我正在移植不使用任何 IV 的旧代码。
在
Aes.Key
属性中设置密钥并使用空 IV(或者更好的是,修复旧代码并使用正确的 IV)后,它对每个新实例都按预期工作。As mentioned in the comments, I mistook the IV parameter for the key, as I was porting old code not using any IV.
Once setting the key in the
Aes.Key
property, and using an empty IV (or even better, fixing the old code and using a proper IV), it worked as expected with every new instance.对我有用的:
What worked for me: