简体   繁体   中英

How can I replicate a javascript sha256 hash in Java and get the same Hex output?

I need to replicate a javascript sha256 hash in java in my groovy/java application.

The javascript version uses the hash function included in angular and I have no control over it. Given the same input strings, I need to provide the same Hex output.

In java, i'm using https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/digest/DigestUtils.html

In java:

DigestUtils.sha256(cx2 + username):

gives me a bytestring something that gets printed as:

[-114, -15, 57, -56, 81, 37, -95, 119, 102, 81, 63, 99, -3, -56, -116, -110, -114, -16, -18, 117, 118, 49, -120, 14, 68, 30, -37, 20, -70, -17, -19, -88]

In java script:

var s1 = Sha256.hash(cx2 + username)

gives me a bytestring (Javascript's type of will say it is a String though) something that gets printed as below(not sure what encoding is that):

ñ9ÈQ%¡wfQ?cýÈðîuv1DÛºïí¨

If I convert both bytestrings to Hex, I get the same result both in java and javascript :

console.log Sha256.toHexStrfromByteStr(s1)
// 478972ab3380187060494987ac7c597ac92decdac1c04dd1dcab8184995ec01b

That would be it, except that the javascript code does a second hash concatenating the bytestring to another string:

var s2 = Sha256.hash(cx1 + s1)

When I try to replicate the second hash in Java, i get a very different output(after converting both outputs to hex).

def s2 = DigestUtils.sha256(cx1 + s1)

Is there a step that i'm missing?

import org.apache.commons.codec.digest.DigestUtils

String cx2 =  'Potato'
String cx1 = 'Bread'

def s1 = DigestUtils.sha256(cx2 + 'username')  
def s2 = DigestUtils.sha256Hex(cx1 + s1)

println s2

Javascript

var s1 = Sha256.hash(cx2 + 'username');
var s2 = Sha256.hash(cx1 + s1);

console.log (Sha256.toHexStrfromByteStr(s2))

Thanks a million!

By doing

def s1 = DigestUtils.sha256(cx2 + 'username')

result s1 has type byte[] . Then, by doing

def s2 = DigestUtils.sha256Hex(cx1 + s1)

you're concatenating result of <byte []>.toString() to cx1 .

You must instead:

a) convert s1 to "normal" String - new String(s1) - and concat two strings, or
b) convert cx1 to byte[] and concat two arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM