java hash hmac sha1_HMAC-SHA1:如何在Java中正确执行它?

我使用HMAC-SHA1散列一些值,在Java中使用以下代码:

public static String hmacSha1(String value, String key) {

try {

// Get an hmac_sha1 key from the raw key bytes

byte[] keyBytes = key.getBytes();

SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

// Get an hmac_sha1 Mac instance and initialize with the signing key

Mac mac = Mac.getInstance("HmacSHA1");

mac.init(signingKey);

// Compute the hmac on input data bytes

byte[] rawHmac = mac.doFinal(value.getBytes());

// Convert raw bytes to Hex

byte[] hexBytes = new Hex().encode(rawHmac);

// Covert array of Hex bytes to a String

return new String(hexBytes, "UTF-8");

} catch (Exception e) {

throw new RuntimeException(e);

}

}Hex()属于org.apache.commons.codec

在PHP中,有一个类似的函数hash_hmac(algorithm, data, key),用于比较我的Java实现返回的值。

所以第一次尝试是:

hash_hmac("sha1", "helloworld", "mykey") // PHP返回:74ae5a4a3d9996d5918defc2c3d475471bbf59ac

我的Java函数也返回74ae5a4a3d9996d5918defc2c3d475471bbf59ac。

好的,它似乎工作。然后我尝试使用更复杂的键:

hash_hmac("sha1", "helloworld", "PRIE7$oG2uS-Yf17kEnUEpi5hvW/#AFo") // PHP返回:e98bcc5c5be6f11dc582ae55f520d1ec4ae29f7a

而这次我的Java impl返回:c19fccf57c613f1868dd22d586f9571cf6412cd0

我的PHP代码返回的散列不等于我的Java函数返回的值,我找不到原因。

有小费吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值