0

I am trying to compare results of hashing in java and python. i have a snippet of code for java and python both giving same output for Encoding with UTF-8 but giving different(kind of ) results for Hash with sha256.

JAVA code:

String hash = "hello" 
byte[] test = hash.getBytes();
MessageDigest sha = MessageDigest.getInstance("SHA-256");
byte[] key = sha.digest(hash.getBytes());

output: test ==> [104, 101, 108, 108, 111] key ==> [44, -14, 77, -70, 95, -80, -93, 14, 38, -24, 59, 42, -59, -71, -30, -98, 27, 22, 30, 92, 31, -89, 66, 94, 115, 4, 51, 98, -109, -117, -104, 36]

Python code:

hash = "hello"
test = list(bytearray(text.encode()))
m = hashlib.sha256()
m.update(hash.encode("UTF-8"))
data = m.digest()
key = list(data)

output: test ==> same as Java output key ==> [44, 242, 77, 186, 95, 176, 163, 14, 38, 232, 59, 42, 197, 185, 226, 158, 27, 22, 30, 92, 31, 167, 66, 94, 115, 4, 51, 98, 147, 139, 152, 36]

1
  • Note that it almost certainly doesn't matter for your input string, but you don't actually specify the encoding in the Java code and it will end up using the platform default encoding. It's better to make it explicit in the .getBytes() call: hash.getBytes(StandardCharsets.UTF_8). Commented Oct 17, 2019 at 17:46

1 Answer 1

2

These are the same results. You're just printing them differently, in a way that uses signed bytes instead of unsigned bytes for Java.

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.