如何将Node JS HMAC签名创建更改为Java

时间:2018-01-11 06:37:35

标签: java node.js rest cryptography hmacsha1

我很少使用Java,我需要转换Node.js中的函数,该函数为REST POST调用构建HMAC签名到Java

节点JS功能:

function buildSignature(buf, secret) {
    const hmac = crypto.createHmac('sha256', Buffer.from(secret, 'utf8'));
    hmac.update(buf);
    return hmac.digest('hex');
}

我目前所做的是:

Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
     SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
     sha256_HMAC.init(secret_key);

     String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
     System.out.println(hash);

这不是一成不变的。

2 个答案:

答案 0 :(得分:1)

我怀疑hmac.digest('hex');不是64位编码的。我尝试将sha256_HMAC.doFinal(message.getBytes())的响应转换为十六进制。

How to convert a byte array to a hex string in Java?'

我更喜欢那里的答案(因为我在许多项目中使用Guava)是

  

final String hex = BaseEncoding.base16()。lowerCase()。encode(bytes);

适应您的问题

final String hash = BaseEncoding.base16().lowerCase().encode(sha256_HMAC.doFinal(message.getBytes()));

答案 1 :(得分:0)

  Mac sha256_HMAC;
  sha256_HMAC = Mac.getInstance("HmacSHA256");
  SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
  sha256_HMAC.init(secret_key);
  byte[] hash = sha256_HMAC.doFinal(payload.getBytes());
  return new String(Hex.encodeHex(hash));