JGleason
JGleason

Reputation: 3956

How do create a Hex encoded HmacSHA256 secure hash in JS?

I have a project with the following Java Code that works...

static String generateHashKey (String apiKey, String msg) throws GeneralSecurityException{

    Mac hmacSha256 = Mac.getInstance("HmacSHA256");
    SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes(), "HmacSHA256");
    hmacSha256.init(secretKey);
    byte[] bytes = hmacSha256.doFinal(msg.getBytes());

    return Hex.encodeHexString(bytes).replace("-","");
} 

I am trying to replace this with a js function like...

import crypto from "crypto";
...
const eMessage = crypto.createHmac("SHA256", apiKey).update(message).digest("base64");

But it looks to be producing different hashes. How do I ensure the same hash for both? What am I missing?

UPDATE

Per the comment and link I tried

import crypto from "crypto";
import fs from "fs";
import moment from "moment";
import axios from "axios";
import hmacSHA256 from 'crypto-js/hmac-sha256';
import sha256 from 'crypto-js/sha256';
import Base64 from 'crypto-js/enc-base64';
....
const eMessage = Base64.stringify(hmacSHA256(message, key));
const eMessage2 = crypto.createHmac("SHA256", key).update(message).digest("base64");
console.log(eMessage)
console.log(eMessage2)

Both of the JS libs return the same (Which is good) but it doesn't match the Java which is bad.

Upvotes: 2

Views: 8161

Answers (2)

fagiani
fagiani

Reputation: 2351

I was able to use this on node.js:

const crypto = require('crypto')
const signature = crypto
    .createHmac('sha256', key)
    .update(message)
    .digest('hex')
console.log('Signature:', signature)

Upvotes: 2

JGleason
JGleason

Reputation: 3956

So the problem I was having was that it was not in base64 and was instead in Hex...

import hmacSHA256 from 'crypto-js/hmac-sha256';
import sha256 from 'crypto-js/sha256';
import Hex from 'crypto-js/enc-hex'
const bytes = hmacSHA256(message, key);
const eMessage = bytes.toString(Hex);

Upvotes: 0

Related Questions