Home > other >  Converting Scala hmacSHA256 encryption to Nodejs crypto
Converting Scala hmacSHA256 encryption to Nodejs crypto

Time:08-12

I've this encryption method in Scala, which I want to convert to NodeJS for a microservice:

val key = "very-secret-key"
val id1 = "1001"
val id2 = "2002"
val id3 = "3003"

val mac = Mac.getInstance("hmacSHA256")
mac.init(new SecretKeySpec(key.getBytes, "hmacSHA256"))
val digest = mac.doFinal(id1.getBytes    id2.getBytes    id3.getBytes)

new String(UrlBase64.encode(digest)).replace(".", "")

tried to do this with createHmac from crypto and converting to Bytes with Buffer but the output token is not the same as in the one I generate in Java

import { createHmac } from 'crypto';

const id1 = Buffer.from('1001', 'base64');
const id2 = Buffer.from('2002', 'base64');
const id3 = Buffer.from('3003', 'base64');

const buffer = Buffer.from("very-secret-key", 'base64');
const token = createHmac('sha256', buffer).digest('base64').replace('.', '');

I'm stuck trying to figure how to add the buffer bytes to the token mac.doFinal(id1.getBytes id2.getBytes id3.getBytes)

CodePudding user response:

The encoding of id1, id2, id3 and buffer/key differs in both codes. In the Scala code, the getBytes method is applied, which uses the default platform encoding. In the NodeJS code the same encoding must be applied instead of Base64.
E.g. assuming that the default platform encoding in the Java environment is UTF-8:

const id1 = Buffer.from('1001', 'utf8');
const id2 = Buffer.from('2002', 'utf8');
const id3 = Buffer.from('3003', 'utf8');
const buffer = Buffer.from("very-secret-key", 'utf8');

Furthermore, the NodeJS code is missing the update() calls that pass the id1, id2 and id3 data. Also, for the encoding of the HMAC Base64url must be used instead of Base64 to be compatible with the Scala code:

const token = crypto.createHmac('sha256', buffer)
  .update(id1)
  .update(id2)
  .update(id3)
  .digest('base64url');

Since the Base64url alphabet does not contain ., the replace('.', '') call is actually not necessary (neither in the Scala nor in the NodeJS code).

With these changes, both codes return the same HMAC for the same input data, e.g. for the posted inut data B5WtlMrLxvMMcDqxOls0-qxqGW2bbaOanXLE7RaXAbA (assuming UTF-8 as default platform encoding in the Java environment).

  • Related