为了进行测试,我想配置任何 .Net AES 算法来生成 FIPS 197 出版物(附录 B)中给出的结果。
我尝试了不同的参数(块大小=密钥大小=反馈大小= 128,不同的CipherModes和填充,IV,...),但我无法得到作为示例给出的结果。我还尝试了不同的实现(RijnadaelManaged、AesCryptoServiceProvider,...)。
有没有办法模仿给定的例子?
这是我当前的实现:
var data = new byte[] { 0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34 };
var key = new byte[] { 0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c };
var expected = new byte[] { 0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32 };
using (var aesAlg = new System.Security.Cryptography.RijndaelManaged())
{
aesAlg.Key = key;
aesAlg.IV = key;
aesAlg.KeySize = 128;
aesAlg.Mode = System.Security.Cryptography.CipherMode.ECB;
aesAlg.BlockSize = 128;
aesAlg.FeedbackSize = 128;
var encryptor = aesAlg.CreateEncryptor();
using (MemoryStream msEncrypt = new MemoryStream())
{
using (var csEncrypt = new System.Security.Cryptography.CryptoStream(msEncrypt, encryptor, System.Security.Cryptography.CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(data);
}
var actual = msEncrypt.ToArray();
Assert.AreEqual(expected.GetLength(0), actual.GetLength(0));
for (int i = 0; i < actual.GetLength(0); i++)
{
var expectedValue = expected[i];
var actualValue = actual[i];
Assert.AreEqual(expectedValue, actualValue);
}
}
}
}
ECB 与分组密码本身并不完全相同。它是类似于CBC或CTR的一种操作方式,但更加原始和不安全。它不是加密单个明文块,而是设法加密多个块,尽管每个块都是直接加密的。
为了确保它符合支持任何消息长度(最多一定大小)的通用密码,ECB 需要填充。否则,不能加密不是块大小倍数的消息。默认情况下,
RijndaelManaged
将使用 PKCS#7 兼容的填充进行填充。
为了避免这种情况,您仍然可以使用 ECB 实现,但随后将类的
Padding
属性设置为 PaddingMode.None
(有关更多填充模式,请参见 here)。
注意:您不应该直接使用
RijndaelManaged
。相反,请使用 Aes.Create()
在您的系统上获得 AES 的最佳实现。通常使用 AES-NI 或类似的 CPU 功能来实现更安全、更快的 AES。
来自文档:
和Rijndael
类型已过时。请使用RijndaelManaged
来代替。Aes