Converting some nodejs code to Java

QuestionsCategory: QuestionsConverting some nodejs code to Java
Brightn-n-Fresh Staff asked 3 years ago

I have been tasked with converting some existing piece of node.js code to Java. I think I'm well on my way, but I'm kind of stuck right now. The output of the methods do not seem to match.

What I'm doing is creating a SHA-1 signature based on a query string. This query string contains some query-related data (not relevant for this question) and an API key.


  • The api_secret string in node.js is equivalent to Config.API_SECRET in Java.
  • Example query string (these are equal in the node.js and Java program):

Actual code

The SHA-1 hmac is initialized as follows in nodejs:

const hmac = crypto.createHmac('sha1', api_secret);

The SHA-1 mac is initialized as follows in Java:

final SecretKeySpec secretKeySpec = new SecretKeySpec(Config.API_SECRET.getBytes("UTF-8"), "HmacSHA1");
final Mac hmac = Mac.getInstance("HmacSHA1");

Next, the node.js program updates the hmac as such (query parameter is as listed above):

hmac.update(query, 'ascii');

Which I replicated in Java like this (query parameter is equal to the node.js query parameter):


Finally, the byte string is converted to a SHA-1 hash as such in the node.js program:

const signature = hmac.digest('hex');

I couldn't find an exact translation to Java, but this was my attempt, which I think does about the same thing:

Byte array to hex function

public static String byteArrayToHex(byte[] a) {
    StringBuilder sb = new StringBuilder(a.length * 2);
    for(byte b: a)
        sb.append(String.format("%02x", b & 0xff));
    return sb.toString();

Actual usage

byte[] result = hmac.doFinal();
MessageDigest md = MessageDigest.getInstance("SHA-1");
String sha1Hash = byteArrayToHex(md.digest(result));

However, this is where I get confused. The node.js program returns this hash: 18cf4fce7bd6163c64d3b2ea8d935b0f16720fe3

But my Java program gives this hash as output: f65f8738cce89134dc73709e3353d94c83ccf1fb

I can't figure out where I went wrong and I really hope someone could shed a light on this.

Thanks in advance!