I have gone thru all the questions and answers about different hash values for same string on different platforms.But none resolved my issue.It would be helpful if I get some idea on why the below case is failing
My code:
import hashlib
import binascii
params = "{'name':'xyz-3113','sur_name':'karuna_karan_3113' ,'init_range':'500','power_down_range':'0','power_high_range':'1000'}"
name = 'xyz'
def generateHash(name,paramsDict={}):
paramsDict = eval(paramsDict)
key = hashlib.md5(str(name)+str(paramsDict))
bin_key = key.digest()
return bin_key
hash_key = generateHash(name, params)
print binascii.hexlify(hash_key)
Output in Windows: ea94e618b69f10d55dcd27562fb06378
Output in Linux: 6d1a40ae190c63f687456a46321165e9
As others have observed, the problem most likely relates to the ordering of the dict items. This is one way to address it:
def generate_hash(name, paramsDict):
strd = ''.join([str(k) + str(v) for k, v in sorted(paramsDict.items())])
key = hashlib.md5(str(name) + strd)
bin_key = key.digest()
return bin_key
As well as explicitly sorting the dict items, I've removed the default value of the paramsDict argument, as this can lead to unexpected behaviour.
If the raw digest value is not used outside the function I'd suggest returning key.hexdigest()
to avoid the need for importing binascii
.