1

An application, i need sha1 encryption,but the results are different between python and java, java is correct. Because there is no byte object in python, and java byte is used for hash calculation. How to get the correct results with python?

4
  • How are you currently performing the encryption? What libraries (if any) are you using for Java and Python? Are you trying to combine both in your application? Commented Oct 26, 2011 at 10:08
  • 1
    Are you saying this doesn't work? - import hashlib m = hashlib.sha1() m.update("The quick brown fox jumps over the lazy dog") print(m.hexdigest()) Commented Oct 26, 2011 at 10:11
  • 1
    Could you please provide the code snippet you use for this calculation? Details are needed for analysis. Commented Oct 26, 2011 at 10:14
  • In python i wrote like this : import hashlib m = hashlib.sha1() m.update("123456") print(m.digest()) In JAVA i wrote like this:import java.security.MessageDigest MessageDigest md = MessageDigest.getInstance('SHA') md.update('123456'.getBytes('UTF-8')) println new String(md.digest()) the resaults are different Commented Oct 26, 2011 at 10:20

1 Answer 1

3

As usual, the difference is not in the digest implementation (those are well-documented and implemented correctly in all major libraries). The difference is in how you represent the resulting data.

md.digest() returns a byte[] with the binary data produced by the digest.

new String(md.digest()) tries to interpret those bytes as text in the platform default encoding which is almost certainly not what you want.

You probably want the digest to be represented in a hex- or Base64 encoding.

Try this (make sure to import javax.xml.bind.DatatypeConverter):

String result = DatatypeConverter.printHexBinary(md.digest());

Alternatively, if you need Base64, use printBase65Binary() instead.

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

1 Comment

In python i do this for i in bytearray(m.digest()):print i then,i got [124,74,141,9,202,55,98,175,97,229,149,32,148,61,194,100,148,248,148,27] but in java i got [124,74,-17,-65,-67,9,-17,-65,-67,55,98,-17,-65,-67,97,-17,-65,-67,32,-17,-65,-67,61,-17,-65,-67,100,-17,-65,-67,-17,-65,-67] both m.update is (bytearray('123456'.encode('utf8'))) is it affect the results

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.