0

I do hash from Java and Compare with Java Script Code using same SHA-256 but the result seem different. Did anyone know help me on these please. Here is the code below.

Java Code

private static final char[] hexArray = "0123456789ABCDEF".toCharArray();
private static String salt = "Apple@987";
private static byte[] saltArr = salt.getBytes();

public static String getSHA256(String data) {
    StringBuilder sb = new StringBuilder();
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(saltArr);
        byte[] byteData = md.digest(data.getBytes());
        sb.append(bytesToHex(byteData));
    } catch(Exception e) {
        e.printStackTrace();
    }
    return sb.toString();
}

private static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];
    for ( int j = 0; j < bytes.length; j++ ) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return String.valueOf(hexChars);
}

String hashed = getSHA256("SampleData");
System.out.println("hashed");

Java Script Code (In Postman)

var salt = 'Apple@987';
var data = 'SampleData';
var hash = CryptoJS.HmacSHA256(data, salt).toString(CryptoJS.enc.Hex);

Java Result:

7B2BBE6DAD962170A83A911EE7B84A382DE2F7FA0DA77C55F99F696EEFAF6C5D

Java Script Result:

1de0de12c5f22bf98f2dbae8430470cac64875a28a035191c3f783e6a2d6cb3b
Ali Bdeir
  • 4,151
  • 10
  • 57
  • 117
Khong Minh
  • 23
  • 9
  • 1
    You are using different hashing algorithms: `SHA256` with Java vs. `HMAC SHA256` with JavaScript (see https://security.stackexchange.com/questions/79577/whats-the-difference-between-hmac-sha256key-data-and-sha256key-data for the differences). You should use `CryptoJS.SHA256` with JavaScript too. – Thomas Kläger Jun 09 '20 at 06:40
  • Additionally to the SHA-256/HMAC-SHA-256 problem you don't specify the encoding. If you are hashing more that simple ASCII characters this also makes a difference. Therefore for hashing always specify the encoding when converting String to byte[]! Usually UTF-8 or UTF-16 would be a good encoding for doing so. – Robert Jun 09 '20 at 07:39
  • Okay thank you so much for your respond let me try to change to sha-256 without HMAC – Khong Minh Jun 09 '20 at 08:26

1 Answers1

1

the Javascript result(1de0de12c5f22bf98f2dbae8430470cac64875a28a035191c3f783e6a2d6cb3b) is right,check it in this link

Java Code you can refer this link

String key = "Apple@987";
Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
sha256_HMAC.init(new SecretKeySpec(key.getBytes(), "HmacSHA256"));
byte[] result = sha256_HMAC.doFinal("SampleData".getBytes());
System.out.println (DatatypeConverter.printHexBinary(result));

javascript code:

var result = crypto.createHmac('SHA256', 'Apple@987').update('SampleData').digest('hex')
console.log(result)

thanks.

Jing Jiang
  • 121
  • 5