如何配置.NET AES算法以生成符合FIPS 197标准的结果?
复现FIPS 197附录B的AES加密结果
你的代码无法得到预期结果主要有3个关键问题:
- 错误使用
StreamWriter写入字节数据:StreamWriter是字符流,会把字节数组按默认编码转成字符再写入,导致原始加密数据被篡改,应该直接用CryptoStream的字节写入方法。 - 未禁用填充:FIPS 197的示例输入正好是一个128位块,不需要任何填充,必须设置
PaddingMode.None。 - ECB模式不需要IV:虽然设置IV不会影响ECB的结果,但属于多余操作,ECB模式本身不使用IV。
另外,推荐使用Aes.Create()替代已过时的RijndaelManaged,这是.NET官方推荐的AES实现方式。
修正后的代码如下:
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 = Aes.Create()) { aesAlg.Key = key; aesAlg.Mode = CipherMode.ECB; aesAlg.BlockSize = 128; aesAlg.Padding = PaddingMode.None; // 关键:禁用填充 var encryptor = aesAlg.CreateEncryptor(); using (MemoryStream msEncrypt = new MemoryStream()) { using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { // 直接写入原始字节数组,避免字符编码转换 csEncrypt.Write(data, 0, data.Length); csEncrypt.FlushFinalBlock(); // 确保所有数据被处理 } var actual = msEncrypt.ToArray(); // 验证结果 Debug.Assert(actual.Length == expected.Length); for (int i = 0; i < actual.Length; i++) { Debug.Assert(actual[i] == expected[i]); } } }
运行这段代码后,actual会完全匹配FIPS 197附录B给出的预期结果。
内容的提问来源于stack exchange,提问作者Torsten
相关产品推荐
相关产品推荐

