2

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.

2
  • 1
    Potentially: jokecamp.com/blog/… Commented Jun 21, 2019 at 13:55
  • Thanks added update Commented Jun 21, 2019 at 14:08

2 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.