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()