SM4 加解密 python 代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| import binascii
from gmssl import sm4
def sm4_encode(key, data): """ 国密sm4加密 :param key: 密钥 :param data: 原始数据 :return: 密文hex """ sm4Alg = sm4.CryptSM4() sm4Alg.set_key(key.encode(), sm4.SM4_ENCRYPT) dateStr = str(data) print("明文:", dateStr) enRes = sm4Alg.crypt_ecb(dateStr.encode()) enHexStr = enRes.hex() print("密文:", enHexStr) return enHexStr
def sm4_decode(key, data): """ 国密sm4解密 :param key: 密钥 :param data: 密文数据 :return: 明文hex """ sm4Alg = sm4.CryptSM4() sm4Alg.set_key(key.encode(), sm4.SM4_DECRYPT) deRes = sm4Alg.crypt_ecb(bytes.fromhex(data)) deHexStr = deRes.decode() print("解密后明文:", deRes) return deRes
def test(): key = "E1A90FB64DDE12AE" strData = "1234567890abcdef"
enHexRes = sm4_encode(key,strData)
print("解密对象<", enHexRes, ">")
sm4_decode(key,enHexRes)
if __name__ == '__main__': print("加解密测试: ") test()
|
实验结果
1 2 3 4 5 6 7
| 加解密测试: 明文: 1234567890abcdef 密文: dfe55390cd4644938b94f6d6073e370ba7cba2fe75751ce0d170047b92d3ae58 解密对象< dfe55390cd4644938b94f6d6073e370ba7cba2fe75751ce0d170047b92d3ae58 > 解密后明文: b'1234567890abcdef'
Process finished with exit code 0
|
Author:
QUANQUAN
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE
Slogan:
Make the world MORE PERFECT !