To get a Java SHA256 hash I use the following method:
public String getSha256(String text, String encoding){
String sha = "";
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(text.getBytes(encoding));
byte[] digest = md.digest();
sha = new String(digest);
sha = sha.replace("\n", "");
} catch (NoSuchAlgorithmException | UnsupportedEncodingException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
return sha;
}
Like so:
String testValue = getSha256("test", "UTF-8");
Then to get the HEX value out of it I do the following:
public String getHexFromString(String text){
String hex = "";
try {
byte[] myBytes = text.getBytes("UTF-8");
hex = DatatypeConverter.printHexBinary(myBytes);
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Utils.class.getName()).log(Level.SEVERE, null, ex);
}
return hex;
}
System.out.print(getHexFromString(testValue));
The result of this is:
C5B8E280A0C390EFBFBDCB864C7D65C5A12FC3AAC2A0C3855AC39015C2A3C2BF4F1B2B0BE2809A2CC3915D6C15C2B0C3B008
In javascript I do the following (using this library):
var hash = sjcl.hash.sha256.hash("test");
console.log(sjcl.codec.hex.fromBits(hash));
And the result is:
9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08
How can I get same hex in Java and Javascript?
What am I doing wrong, is it the Java or Javascript code?
sha = new String(digest);- don't do this. The digest is arbitrary binary data. You should convertdigestto hex, rather than converting it into a string and then calling yourgetHexFromStringcode. That's almost certainly part of the problem.