简体   繁体   中英

hashlib.md5 python2 vs python3 (string vs bytes)

I generate hash with hashlib.md5 in both: python2 and python3. python2 outputs string while python3 outputs bytes. I have to use "latin1" encoding on string in python3 to match default python2 encoding.

I want to be sure python3 outputs same result as python2 and use string for further processing.

Question: How to ensure / convert md5 output string?

The reason is my python2 is valid output and I am migrating script from py2 to py3 so would like to validate the output but at the moment I can not compare bytes with string.

python2:

import hashlib


s = "fred"
hashlib.md5("fred").digest()

out: 'W\n\x90\xbf\xbf\x8c~\xab]\xc5\xd4\xe2h2\xd5\xb1'

python3:

import hashlib


s = "fred"
hashlib.md5("fred".encode("latin1")).digest()

out: b'W\n\x90\xbf\xbf\x8c~\xab]\xc5\xd4\xe2h2\xd5\xb1'

You can get around this by using md5.hexdigest() , this will return a string in both Python 2 and Python 3.


from hashlib import md5

hash_ = md5()
hash_.update(b"test")
print(hash_.hexdigest())

Python 3 result:

'098f6bcd4621d373cade4e832627b4f6'

Python 2 result:

'098f6bcd4621d373cade4e832627b4f6'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM