SHA256 string and bytes conversion

Python 2.7
import binascii
import hashlib

b = hashlib.sha256("hello").digest()
s = hashlib.sha256("hello").hexdigest()
print("String", s)
print("Bytes", b)
print("s2b binascii.a2b_hex(b)", binascii.a2b_hex(s))
print("b2s binascii.hexlify(b)", binascii.hexlify(b))

Result:
('String', '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824')
('Bytes', ',\xf2M\xba_\xb0\xa3\x0e&\xe8;*\xc5\xb9\xe2\x9e\x1b\x16\x1e\\\x1f\xa7B^s\x043b\x93\x8b\x98$')
('s2b binascii.a2b_hex(b)', ',\xf2M\xba_\xb0\xa3\x0e&\xe8;*\xc5\xb9\xe2\x9e\x1b\x16\x1e\\\x1f\xa7B^s\x043b\x93\x8b\x98$')
('b2s binascii.hexlify(b)', '2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824')
Python 3.7
import binascii
import hashlib
s = hashlib.sha256("hello".encode()).hexdigest()
b = hashlib.sha256("hello".encode()).digest()
print("String", s)
print("Bytes", b)
print("s2b bytes.fromhex()", bytes.fromhex(str(s).lower()))
print("s2b binascii", binascii.a2b_hex(s))

print("b2s binascii.hexlify(b)", binascii.hexlify(b))
print("b2s binascii", binascii.b2a_hex(b))
print("b2s join", "".join("%02x" % z for z in b))

Result:
String 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
Bytes b',\xf2M\xba_\xb0\xa3\x0e&\xe8;*\xc5\xb9\xe2\x9e\x1b\x16\x1e\\\x1f\xa7B^s\x043b\x93\x8b\x98$'
s2b bytes.fromhex() b',\xf2M\xba_\xb0\xa3\x0e&\xe8;*\xc5\xb9\xe2\x9e\x1b\x16\x1e\\\x1f\xa7B^s\x043b\x93\x8b\x98$'
s2b binascii b',\xf2M\xba_\xb0\xa3\x0e&\xe8;*\xc5\xb9\xe2\x9e\x1b\x16\x1e\\\x1f\xa7B^s\x043b\x93\x8b\x98$'
b2s binascii.hexlify(b) b'2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
b2s binascii b'2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
b2s join 2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824

Leave a Reply

Your email address will not be published. Required fields are marked *