小结
在Java程序中使用ISO9797Alg3Mac算法,返回了错误java.lang.IllegalArgumentException: params must be an instance of KeyParameter
,进行了解决。
问题
Bouncy Castle Crypto APIs提供了进行加解密的接口API,引入到工程中后,可以方便地使用其提供的接口进行加解密运算。
ISO9797 Algorithm 3 MAC
也被称为Retail MAC
,具体计算方法的示意图如下:
Bouncy Castle Crypto APIs
提供了使用方法:
Github: ISO9797Alg3Mac示例
我使用了以下代码:
public static int TDES_RetailMACWithIV(byte[] key, byte[] in, byte[] output, byte[] iv) {
ISO9797Alg3Mac triple_des = new ISO9797Alg3Mac(new DESEngine(), new ISO7816d4Padding());
ParametersWithIV keyAndIv = new ParametersWithIV(new KeyParameter(key), iv);
triple_des.init(keyAndIv);
triple_des.update(in, 0, in.length);
triple_des.doFinal(output, 0);
return triple_des.getMacSize();
}
以上程序在执行到triple_des.init(keyAndIv);
时会抛异常,内容为:java.lang.IllegalArgumentException: params must be an instance of KeyParameter
解决
经过调试,是我使用的Bouncy Castle Crypto APIs
的版本问题,现使用的版本:Release: 1.45, 升级到Release: 1.66,问题解决。
注意:在使用ISO9797 Algorithm 3 MAC
算法时,即使数据长度是8的整数倍,也需要在数据后添加填充字节再进行运算,例如:
0102030405060708需要填充为010203040506070880000000000000
参考
The Legion of the Bouncy Castle: Release Note
Github: core/src/test/java/org/bouncycastle/crypto/test/ISO9797Alg3MacTest.java
Github: core/src/main/java/org/bouncycastle/crypto/macs/ISO9797Alg3Mac.java