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?
-
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?Tom Elliott– Tom Elliott2011-10-26 10:08:48 +00:00Commented Oct 26, 2011 at 10:08
-
1Are 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())JackWilson– JackWilson2011-10-26 10:11:56 +00:00Commented Oct 26, 2011 at 10:11
-
1Could you please provide the code snippet you use for this calculation? Details are needed for analysis.Joël– Joël2011-10-26 10:14:03 +00:00Commented 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 differentelliott_fromcn– elliott_fromcn2011-10-26 10:20:46 +00:00Commented Oct 26, 2011 at 10:20
1 Answer
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.