75.6. 散列消息身份验证代码(HMAC)

为了避免对加密数据进行攻击,同时在传输 CryptoDataFormat 时也可以根据可配置的 MAC 算法为加密交换内容计算消息身份验证代码。在加密后,计算的 HMAC 会附加到流中。它与解密阶段的流分离。对该 MAC 进行重新计算并验证,并根据传输中的传输中没有修改的问题。有关 Message Authentication Codes 的更多信息,请参阅 http://en.wikipedia.org/wiki/HMAC

KeyGenerator generator = KeyGenerator.getInstance("DES");

CryptoDataFormat cryptoFormat = new CryptoDataFormat("DES", generator.generateKey());
cryptoFormat.setShouldAppendHMAC(true);

from("direct:hmac")
    .marshal(cryptoFormat)
    .to("mock:encrypted")
    .unmarshal(cryptoFormat)
    .to("mock:unencrypted");

也可借助 spring。

<crypto id="hmac" algorithm="DES" keyRef="desKey" shouldAppendHMAC="true" />

默认情况下,HMAC 使用 HmacSHA1 mac 算法计算,虽然可以通过提供不同的算法名称来轻松更改。请查看这里了解如何通过配置的安全供应商提供哪些算法

KeyGenerator generator = KeyGenerator.getInstance("DES");

CryptoDataFormat cryptoFormat = new CryptoDataFormat("DES", generator.generateKey());
cryptoFormat.setShouldAppendHMAC(true);
cryptoFormat.setMacAlgorithm("HmacMD5");

from("direct:hmac-algorithm")
    .marshal(cryptoFormat)
    .to("mock:encrypted")
    .unmarshal(cryptoFormat)
    .to("mock:unencrypted");

也可借助 spring。

<crypto id="hmac-algorithm" algorithm="DES" keyRef="desKey" macAlgorithm="HmacMD5" shouldAppendHMAC="true" />