Home > OS >  How to perform Base64 on top of HASH in Java
How to perform Base64 on top of HASH in Java

Time:05-23

I have the following example in Javascript, I can't seem to find the equivalent in Java for it

var rapyd_signature = CryptoJS.enc.Hex.stringify(CryptoJS.HmacSHA256(data, key));
rapyd_signature = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(rapyd_signature));

What I have (which does not give the same result)

Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmacSHA256.init(secretKeySpec);
byte[] tobeEncoded =  data.getBytes(StandardCharsets.UTF_8);
String rapyd_signature = Base64.getEncoder().encodeToString(tobeEncoded);

CodePudding user response:

You initialized hmacSHA256 … and then you didn’t do anything with it.

You need to actually hash the data, by calling hmacSHA256.doFinal:

Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA256");
hmacSHA256.init(secretKeySpec);

byte[] tobeEncoded = data.getBytes(StandardCharsets.UTF_8);
toBeEncoded = hmacSHA256.doFinal(toBeEncoded);

String rapyd_signature = Base64.getEncoder().encodeToString(tobeEncoded);
  • Related