when using the following javascript code:
var username = "TEST"; var password = "test"; var key = "6591bbcb28880da7e7b91154ec39a9d5"; var latin_parsed = CryptoJS.enc.Latin1.parse(password + username); var message = CryptoJS.SHA1(latin_parsed); var key_hex = CryptoJS.enc.Hex.parse(key); var hash_password = CryptoJS.HmacSHA1(message, key_hex) var hash_password_hex = hash_password.toString(CryptoJS.enc.Hex); // Above code gives this output: // hash_password_hex == "2f0dc5257278493636a30fe5d3eeda43f4d8d8c1"
A live example can be seen here: https://jsfiddle.net/Ld7469vh/
I have tried with the following Python code, but the hash are not similar.
https://gist.github.com/heskyji/5167567b64cb92a910a3
But the hash are not similar. It seems like CryptoJS returns WordsArray and not strings.
So my issue might rely on that difference, but I am not sure how to create a 1:1 solution in python.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Python uses bytes for most encryption/byte related operations. Conversion from hex and back is done with bytes.hex and bytes.fromhex.
You can read more on the docs about hashlib and hmac. They both follow the same general format, which is to create the object (and optionally update it with the data, or do it immediately as shown below) and get the digest of it.
# these are both built in
import hashlib
import hmac
username = "TEST"
password = "test"
string_key = "6591bbcb28880da7e7b91154ec39a9d5"
latin_parsed = (password + username).encode('utf-8') # this is now `bytes`
message = hashlib.sha1(latin_parsed).digest() # sha1 of latin_parsed
key = bytes.fromhex(string_key) # turn it into `bytes` as well
hash_password = hmac.HMAC(key, message, hashlib.sha1).digest() # do hmac of this with key key and message message
hash_password_hex = hash_password.hex()
print(hash_password_hex)
# 2f0dc5257278493636a30fe5d3eeda43f4d8d8c1
The code linked uses signature2 = base64.urlsafe_b64encode(signature1) opposed to the hex string. It also does not do what you wanted – it is supposed to combine the username and password first (warning, length extension attacks) and hashes it first before feeding it into the hmac.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0