Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Syntax to use combination of two hash algorithm

I would like to know how to write in a single line the combination of two hash algorithms in Python. I want to use MD5 and sha256 in one line. Here is my function:

def calcHash(self):
    block_string = json.dumps({"nonce":self.nonce, "tstamp":self.tstamp, "output":self.output, "prevhash":self.prevhash}, sort_keys=True).encode()
    return hashlib.sha256(block_string).hexdigest()

I tried return md5.hashlib(hashlib.sha256(block_string).hexdigest()) but it doesn’t work.
Can someone help?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The problem could just be that .hexdigest() produces a string, not a bytes, so you need to encode it again

>>> import hashlib, json
>>> j = json.dumps({"foo":"bar","baz":2022})
>>> hashlib.sha256(j.encode()).hexdigest()
'44ce0f46288befab7f32e9acd68d36b2a9997e801fb129422ddc35610323c627'
>>> hashlib.md5(hashlib.sha256(j.encode()).hexdigest().encode()).hexdigest()
'f7c6be48b7d34bcd278257dd73038f67'

Alternatively, you could directly use .digest() to get bytes from the hash, rather than intermediately converting it to a hex string (though note the output is different)

>>> hashlib.md5(hashlib.sha256(j.encode()).digest()).hexdigest()
'12ac82f5a1c0cb3751619f6d0ae0c2ee'

If you have a great many algorithms in some order, you may find .new() useful to iteratively produce a result from some list of hashes.

BEWARE
md5 is broken from a security perspective and I cannot recommend using it unless it’s a required input to a legacy system!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading