Home > front end >  Not able to get similar result in Java as CryptoJS.HmacSHA256 produce the result in JavaScript
Not able to get similar result in Java as CryptoJS.HmacSHA256 produce the result in JavaScript

Time:11-23

I am trying to write the Java code to produce the similar result as the below java script produce for result1...

var dataToSign = "message";
var secret = "secret";
var orgId = "abcd";
var secureKey = "tZvFPMrVkgQ5m5jj";
var result1 = orgId  CryptoJS.HmacSHA256(dataToSign, secret);
console.log( result1)

value of result1 is: abcd8b5f48702995c1598c573db1e21866a9b825d4a794d169d7060a03605796360b

Now i want to generate the same result using java code..

String  orgId = "abcd";
        String key="secret";
        String dataToSign = "message";
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        String result2=orgId java.util.Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(dataToSign.getBytes("UTF-8")));
System.out.println(result2);

I am getting value of result2 is : abcd[B@39538f9e i19IcCmVwVmMVz2x4hhmqbgl1KeU0WnXBgoDYFeWNgs=

but I want result2 similar to result1;

CodePudding user response:

You should print the hex numbers, not the base64 encoded string.

Have a look at this, then use bytesToHex:

byte[] result2 = sha256_HMAC.doFinal(dataToSign.getBytes("UTF-8"));
System.out.println(orgId   bytesToHex(result2));
  • Related