TOC

Python 国密(sm3)

sm3 是我国设计的一种哈希算法,根据维基百科信息,大致相当于 sha256

sm3

SM3是中华人民共和国政府采用的一种密码散列函数标准,前身为SCH4杂凑算法,由国家密码管理局于2010年12月17日发布,相关标准为“GM/T 0004-2012 《SM3密码杂凑算法》”。2016年,成为中国国家密码标准(GB/T 32905-2016)。
在商用密码体系中,SM3主要用于数字签名及验证、消息认证码生成及验证、随机数生成等,其算法公开,安全性及效率与SHA-256相当。
SM3签名算法收录于ISO/IEC 10118-3:2018《信息安全技术杂凑函数第3部分:专用杂凑函数》。

Python 调用

hashlib.algorithms_available
A set containing the names of the hash algorithms that are available in the running Python interpreter. These names will be recognized when passed to new(). algorithms_guaranteed will always be a subset. The same algorithm may appear multiple times in this set under different names (thanks to OpenSSL).
New in version 3.2.

import hashlib, _hashlib
print(hashlib.algorithms_available)
{'md5', 'md5-sha1', 'shake_128', 'sha3_384', 'shake_256', 'sha512_256', 'sha512_224', 'sha3_512', 'sha3_256', 'blake2s', 'blake2b', 'sha3_224', 'sm3', 'md4', 'sha256', 'sha512', 'sha1', 'ripemd160', 'sha384', 'whirlpool', 'sha224'}
print(hashlib.algorithms_guaranteed)
{'sha3_512', 'sha3_256', 'md5', 'sha1', 'blake2s', 'sha384', 'blake2b', 'sha3_224', 'shake_128', 'sha3_384', 'sha256', 'sha224', 'sha512', 'shake_256'}
print(_hashlib.openssl_md_meth_names)
frozenset({'md5', 'md5-sha1', 'shake_128', 'sha3_384', 'shake_256', 'sha512_256', 'sha512_224', 'sha3_512', 'sha3_256', 'blake2s', 'sm3', 'md4', 'blake2b', 'sha3_224', 'sha256', 'sha512', 'ripemd160', 'sha1', 'sha384', 'whirlpool', 'sha224'})

Python hashlib.algorithm_available 中的 sm3 应该是从本地 openssl 库导入。

hashlib.new('sm3', b'hello world').hexdigest()
# '44f0061e69fa6fdfc290c494654a05dc0c053da7e5c52b84ef93a9d67d3fff88'