In this section we shall provide a few examples about calculating cryptographic hash functions in Python.
在本节中,我们将提供一些有关在 Python 中使用加密哈希函数计算的示例。
在 Python 中使用加密哈希函数计算
We shall use the standard Python library hashlib. The input data for hashing should be given as bytes sequence (bytes object), so we need to encode the input string using some text encoding, e.g. utf8. The produced output data is also a bytes sequence, which can be printed as hex digits using binascii.hexlify() as shown below:
The expected output from the above example looks like this:
上述示例的预期输出如下:
Calculating Keccak-256 hashes (the hash function used in the Ethereum blockchain) requires non-standard Python functions. In the below example we use the pycryptodome package available from PyPI: https://pypi.org/project/pycryptodome.