multiformats/py-multihash

Example of using this with Python's hashlib

Closed this issue · 3 comments

Just a request in the README.md to show how to use this library with hashlib? Because atm, it's not entirely clear how to make use of this library to create multihashes when you still need hashlib's hashing functions.

sg495 commented

Yeah, I also think this would be useful (see #3 as well).

In my project I use hashlib to calculate the hash, then encode the hash/digest value with multihash and finnaly do base encoding. I was also a little puzzled before realizing multihash did not do any hash calculations itself.

>>> import hashlib
>>> from multihash import multihash
>>> some_data=str.encode("foobar", 'utf-8')
>>> hash = hashlib.sha256(some_data)
<sha256 HASH object @ 0x7fcd544e89f0>
>>> mhash = multihash.encode(hash.digest(), 'sha2-256')
b'\x12 \xc3\xab\x8f\xf17 \xe8\xad\x90G\xdd9Fk<\x89t\xe5\x92\xc2\xfa8=J9`qL\xae\xf0\xc4\xf2'
>>> mhash_base58 = multihash.to_b58_string(mhash)
'QmbWTwYGcmdyK9CYfNBcfs9nhZs17a6FQ4Y8oea278xx41'

# or use multibase, because who wants to remember how the hash is encoded?
>>> from multibase import multibase
>>> mhash_base64 = multibase.encode('base64', mhash)
b'mEiDDq4/xNyDorZBH3TlGazyJdOWSwvo4PUo5YHFMrvDE8g'

On a certain level I agree with this issue. But should there be hard dependency on hashlib when using multihash?
Something that would already improve usability is if hashlib had a dict of hash functions, using the same keys as in multihash.constants.HASH_CODES. At the moment the key names in multihash.constants and the function names in hashlib are not exactly the same and manual translation is needed, which can be error prone.

rvagg commented

closing due to inactivity, archiving repo