3

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!

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.