HmacSHA256 在 Java 中未返回相同的值
HmacSHA256 not returning same value in Java
我有一个回调 URL,它在其 header 中接收一个 HMAC256 和一个请求 body。
但是,当我尝试使用 HMAC256 header 验证请求 body 时。两个值不同。
public static final String SECRET = "secret_key";
public static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
@PostMapping("/callbackUrl")
public void receiveNotification(@RequestHeader("hmac-sha256") String hmac, @RequestBody Notification notification) {
SecretKeySpec sKey = new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), HMAC_SHA256_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
mac.init(sKey);
byte[] data = new ObjectMapper().writeValueAsBytes(notification);
byte[] rawHmac = mac.doFinal(data);
String result = new String(Base64.encodeBase64(rawHmac));
log.info("HMAC request calculated {}", result);
log.info("HMAC received {}", hmac);
}
我在信息日志中得到了不同的值,而我本应得到相同的值:
HMAC request calculated w5ynJTVV1H8GNgzje91BKEIYn8n9GtRU7iNcnEr/AwE=
HMAC received P5z/Ipu71qQ4ROqExL87xfhkCz5e1WpP4ypFxtikyaE=
代码的哪一部分不正确?
编辑
要检查发件人如何计算 Hmac,请检查:
https://docs.cronofy.com/developers/push-notifications/authentication/
我发布了问题。通过对代码进行微小更改解决了该问题。我没有直接将值写为字节,而是先将其更改为字符串,然后从中读取字节。
改变了这个:
byte[] data = new ObjectMapper().writeValueAsBytes(notification);
byte[] rawHmac = mac.doFinal(data);
对此:
String data = new ObjectMapper().writeValueAsString(pushNotification);
byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
感谢 Maarten Bodewes 指出正确的方向。
我有一个回调 URL,它在其 header 中接收一个 HMAC256 和一个请求 body。
但是,当我尝试使用 HMAC256 header 验证请求 body 时。两个值不同。
public static final String SECRET = "secret_key";
public static final String HMAC_SHA256_ALGORITHM = "HmacSHA256";
@PostMapping("/callbackUrl")
public void receiveNotification(@RequestHeader("hmac-sha256") String hmac, @RequestBody Notification notification) {
SecretKeySpec sKey = new SecretKeySpec(SECRET.getBytes(StandardCharsets.UTF_8), HMAC_SHA256_ALGORITHM);
Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
mac.init(sKey);
byte[] data = new ObjectMapper().writeValueAsBytes(notification);
byte[] rawHmac = mac.doFinal(data);
String result = new String(Base64.encodeBase64(rawHmac));
log.info("HMAC request calculated {}", result);
log.info("HMAC received {}", hmac);
}
我在信息日志中得到了不同的值,而我本应得到相同的值:
HMAC request calculated w5ynJTVV1H8GNgzje91BKEIYn8n9GtRU7iNcnEr/AwE=
HMAC received P5z/Ipu71qQ4ROqExL87xfhkCz5e1WpP4ypFxtikyaE=
代码的哪一部分不正确?
编辑
要检查发件人如何计算 Hmac,请检查:
https://docs.cronofy.com/developers/push-notifications/authentication/
我发布了问题。通过对代码进行微小更改解决了该问题。我没有直接将值写为字节,而是先将其更改为字符串,然后从中读取字节。
改变了这个:
byte[] data = new ObjectMapper().writeValueAsBytes(notification);
byte[] rawHmac = mac.doFinal(data);
对此:
String data = new ObjectMapper().writeValueAsString(pushNotification);
byte[] rawHmac = mac.doFinal(data.getBytes(StandardCharsets.UTF_8));
感谢 Maarten Bodewes 指出正确的方向。