如何用DES实现CBC-MAC?
我应该在C#中实现MAC-CBC生成方法,其中包含有关加密算法的一些信息。 这就是我所拥有的:
- 我应该使用DES。
- 关键是
byte[] {11, 11, 11, 11, 11, 11, 11, 11}
- 数据(16字节)应以8字节部分加密。 前8个字节使用
Instance Vector = new byte[8]
(8个字节,0值)加密。 (CBC?) - 加密值的最后8个字节应转换为hex字符串。 这是我应该发送的结果。
有了这些信息,我实现了以下方法:
public static string Encrypt(byte[] data) { var IV = new byte[8]; var key = new byte[] { 11, 11, 11, 11, 11, 11, 11, 11 }; var result = new byte[16]; // Create DES and encrypt. var des = DES.Create(); des.Key = key; des.IV = IV; des.Padding = PaddingMode.None; des.Mode = CipherMode.CBC; ICryptoTransform cryptoTransform = des.CreateEncryptor(key, IV); cryptoTransform.TransformBlock(data, 0, 16, result, 0); // Get the last eight bytes of the encrypted data. var lastEightBytes = new byte[8]; Array.Copy(result, 8, lastEightBytes, 0, 8); // Convert to hex. var hexResult = string.Empty; foreach (byte ascii in lastEightBytes) { int n = (int)ascii; hexResult += n.ToString("X").PadLeft(2, '0'); } return hexResult; }
他们提供给我的样本原始数据是: input=byte[] {0, 6, 4, 1, 6, 4, 1, 7, E, E, F, F, F, F, B, B)
返回值的输出: A7CBFB3C730B059C
。 这意味着加密数据的最后八个字节应该是: byte[] {167, 203, 251, 60, 115, 11, 05, 156}
。
但不幸的是使用上面的方法,我得到: 32D91200D0007632
。 意味着我的加密数据不正确。 (我方法生成的加密值的最后八个字节是byte[] {50, 207, 18, 0, 208, 0, 118, 50}
。
有什么方法可以找到我应该做什么来到A7CB ……? 难道我做错了什么?
CBC-MAC需要零初始化矢量。 明确指定IV更好:
var IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 };
你说你的密钥是byte[] { 11, 11, 11, 11, 11, 11, 11, 11 }
是hex或基数为10的那些字节? 您可能想尝试:
var key = new byte[] { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 };
并看看它是否更好。
Mono项目有一个通用的MAC-CBC实现,可以在任何SymmetricAlgorithm上运行 – 即使它在内部使用,也只是为了实现MACTripleDES 。
您可以在此处找到MIT.X11许可源代码。 按原样使用它或将其与您自己的代码进行比较。