Ajit Kumar Singh
Ajit Kumar Singh

Reputation: 378

Not able to get similar result in Java as CryptoJS.HmacSHA256 produce the result in JavaScript

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;

Upvotes: 0

Views: 892

Answers (2)

Viettel Solutions
Viettel Solutions

Reputation: 1489

Solution 1: You should this line

String result2=orgId+java.util.Base64.getEncoder().encodeToString(sha256_HMAC.doFinal(dataToSign.getBytes("UTF-8")));

To

String result2 = orgId + getHex(sha256_HMAC.doFinal(dataToSign.getBytes("UTF-8")));

Function getHex as below

static final String HEXES = "0123456789ABCDEF";
public static String getHex(byte[] raw) {
    if (raw == null) {
        return null;
    }
    final StringBuilder hex = new StringBuilder(2 * raw.length);
    for (final byte b : raw) {
        hex.append(HEXES.charAt((b & 0xF0) >> 4))
                .append(HEXES.charAt((b & 0x0F)));
    }
    return hex.toString();
}

Solution 2: You should this line

var result1 = orgId+ CryptoJS.HmacSHA256(dataToSign, secret);

To

var result1 = orgId+ CryptoJS.HmacSHA256(dataToSign, secret);
var result2  = CryptoJS.enc.Base64.stringify(result1)

Upvotes: 0

zhh
zhh

Reputation: 2406

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

Upvotes: 1

Related Questions