运行 字符串通过 hashlib

Run string through hashlib

假设我有一个像这样的字符串:

string = '456878921'

我想 运行 这个字符串通过每个散列类型 python 可以从一些包(假设是 hashlib)提供,所以理想情况下,这个问题的解决方案是这样的:

hashes = ['md5', 'sha256']

for n in hashes:
    print(str(n) + ": " + str(hashlib.n(string).hexdigest())

这在 python 中甚至可能吗?

import hashlib
hash_obj = hashlib.sha256(b'456878921')
hexing= hash_obj.hexdigest()
print(hexing)

您可以使用 getattr:

bytes = string.encode('utf-8') # hashlib algorithms require bytes!

for h in hashes:
    hash = getattr(hashlib, h)
    print(f'{h}: {hash(bytes).hexdigest()}')