Avatar CS Knowledge Wiki

Hash Functions - Examples

原文链接:https://www.yuque.com/yangguangfanxing/zuyi8o/fpbq2704md3nv1ig

原文链接:https://www.yuque.com/yangguangfanxing/zuyi8o/fpbq2704md3nv1ig ↗

In this section we shall provide a few examples about calculating cryptographic hash functions in Python.

Calculating Cryptographic Hash Functions in 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:

Run the above code example: https://repl.it/@nakov/Hashes-SHA2-SHA3-BLAKE2-RIPEMD-in-Python ↗.

The expected output from the above example looks like this:

SHA-256: b'2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824'
SHA3-256: b'3338be694f50c5f338814986cdf0686453a888b84f424d792af4b9202398f392'
BLAKE2s: b'19213bacc58dee6dbde3ceb9a47cbb330b3d86f8cca8997eb00be456f140ca25'
RIPEMD-160: b'108f07b8382412612c048d07d13f814118445acd'
bash

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 ↗.

First install “pycryptodome” (https://www.pycryptodome.org ↗)

pip install pycryptodome
bash

Now write some Python code to calculate a Keccak-256 hash:

from Crypto.Hash import keccak
import binascii
keccak256 = keccak.new(data=b'hello', digest_bits=256).digest()
print("Keccak256:", binascii.hexlify(keccak256))
python

Run the above code example: https://repl.it/@nakov/Keccak256-in-Python ↗.

The output from the above examples is:

Keccak256: b'1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8'
bash

​

Knowledge map

知识图谱

当前文档、同目录指南与引用关系。

准备中 全局图谱

正在构建知识图谱...

拖动节点 · 滚动缩放 · 点击打开

帮助与支持

这篇文档有帮助吗?

请给我们反馈以改进文档质量
(点击按钮后会打开邮箱)

帮助改进文档

所有文档均开源,发现问题或不清楚的地方?提交 PR 来帮助改进。

编辑此页面 了解如何贡献 →

需要更多帮助?

加入社区或直接联系获取支持

文件管理器 /
位置 /
内容
Knowledge explorer

知识图谱

全部知识 准备图谱...
文章 文档 标签 分类

正在加载知识网络...

拖动节点 · 滚动缩放 · 单击查看详情 · 双击打开页面
标签云 / Tag Cloud