This question is related to my query titled "Create WS security headers for REST web service in SoapUI Pro". However that one is different as I raised that because I couldn't get the script to work at all, I came up with a solution for that but it only works about 66% of the time.
I have noticed that the code that I use to hash the string sometimes produces different results when compared to a python script hashing the same input.
Below is my groovy code that hashes an input value.
MessageDigest cript2 = MessageDigest.getInstance("SHA-1");
cript2.update(nonce.getBytes("ASCII"));
PasswordDigest = new String(cript2.digest());
If I run it with the input nonce value 201703281329 it produces the below ë±ËËÐùìÓ0¼ÕM�¹,óßP‹
If I use the same input value using the Python code below then it produces ëᄆËËÐùìÓ0ᄐÕMマᄍ,óßPヒ
digest = sha.new(nonce).digest()
However if I run the groovy and python scripts with input value 201703281350 then they both produce ..
iàv詮ɹm:F Ë Â¾
Could someone tell me why I am seeing differences for some input values and not others and how I can modify my groovy code so that it produces same values as Python code?
much appreciated.
If you compare the bytes returned by the digest method of both languages, you'll find that they are indeed the same. The reason is that some combinations of bytes do not result in printable Java Strings.
To compare them:
def hexString = PasswordDigest.collect { String.format('%02x', it) }.join()
Compare to the output of sha.hexdigest()
:
def hexString = sha.new(nonce).hexdigest()
Both should produce ebb1cbcbd0f9ecd330bcd51b4d8fb92cf3df508b
Edited
Perhaps I didn't make it clear that passwordDigest should not be converted to a String. Below is the complete groovy and python code. Both programs produce the same output:
Groovy:
import java.security.*
String nonce = '201703281329'
MessageDigest digest = MessageDigest.getInstance("SHA-1")
digest.update(nonce.getBytes("ASCII"))
byte[] passwordDigest = digest.digest() // byte[], not string
String hexString = passwordDigest.collect { String.format('%02x', it) }.join()
println hexString
Python:
import sha
nonce = '201703281329'
sha.new(nonce).hexdigest()
print sha.new(nonce).hexdigest()
The output of both: ebb1cbcbd0f9ecd330bcd51b4d8fb92cf3df508b
.