python的sm3 摘要/杂凑算法。注意按照文件copy

sm3_alg.py,内如下:
from cryptography.hazmat.primitives import hashes, hmac


def get_sm3(plain_bytes):
    algorithm = hashes.SM3()
    h_digest = hashes.Hash(algorithm)
    h_digest.update(plain_bytes)
    sm3_hash_bytes = h_digest.finalize()
    return sm3_hash_bytes


def get_sm3_file(filename):
    # file_name='resource/python-3.12.6-amd64.exe'
    read_num = 4096
    algorithm = hashes.SM3()
    h_digest = hashes.Hash(algorithm)
    with open(filename, mode='rb') as file:
        data = file.read(read_num)
        while data:
            h_digest.update(data)
            data = file.read(read_num)
    sm3_hash_bytes = h_digest.finalize()
    return sm3_hash_bytes


def get_sm3_hmac(key_bytes, plain_bytes):
    algorithm = hmac.hashes.SM3()
    h_digest = hmac.HMAC(key_bytes, algorithm)
    h_digest.update(plain_bytes)
    sm3_hmac_bytes = h_digest.finalize()
    return sm3_hmac_bytes
sm3_apply.py ,内如下:

from sm3_alg import get_sm3, get_sm3_hmac
from utils.algorithm.hash.sm3_alg import get_sm3_file


def sm3(source):
    plain_bytes = source.encode()
    sm3_bytes = get_sm3(plain_bytes)
    return sm3_bytes.hex().upper()


def sm3_file(filename):
    sm3_file_bytes = get_sm3_file(filename)
    return sm3_file_bytes.hex().upper()


def sm3_hmac(key, source):
    key_bytes = key.encode()
    plain_bytes = source.encode()
    sm3_hmac_bytes = get_sm3_hmac(key_bytes, plain_bytes)
    return sm3_hmac_bytes.hex().upper()


def main():
    key = '2934412A66B7A186DC35DC40E926F9EE'
    source = '1'

    sm3_hash_value = sm3(source)
    print(f'sm3_hash_value={sm3_hash_value}')

    sm3_hmac_value = sm3_hmac(key, source)
    print(f'sm3_hmac_value={sm3_hmac_value}')

    file_name = r'D:/Python/TestTeam/resource/python-3.12.6-amd64.exe'
    sm3_file_value = sm3_file(file_name)
    print(f'sm3_file_value={sm3_file_value}')


if __name__ == '__main__':
    main()
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值