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

#导入国密算法sm4包
from gmssl import sm4

def sm4_encode(key, data):
"""
国密sm4加密
:param key: 密钥
:param data: 原始数据
:return: 密文hex
"""
sm4Alg = sm4.CryptSM4() # 实例化sm4
sm4Alg.set_key(key.encode(), sm4.SM4_ENCRYPT) # 设置密钥
dateStr = str(data)
print("明文:", dateStr)
enRes = sm4Alg.crypt_ecb(dateStr.encode()) # 开始加密,bytes类型,ecb模式
enHexStr = enRes.hex()
print("密文:", enHexStr)
return enHexStr # 返回十六进制值
# return encrypt_value.hex()

def sm4_decode(key, data):
"""
国密sm4解密
:param key: 密钥
:param data: 密文数据
:return: 明文hex
"""
sm4Alg = sm4.CryptSM4() # 实例化sm4
sm4Alg.set_key(key.encode(), sm4.SM4_DECRYPT) # 设置密钥
deRes = sm4Alg.crypt_ecb(bytes.fromhex(data)) # 开始解密。十六进制类型,ecb模式
deHexStr = deRes.decode()
print("解密后明文:", deRes)
return deRes

#测试函数
def test():
key = "E1A90FB64DDE12AE"
strData = "1234567890abcdef"

enHexRes = sm4_encode(key,strData)

print("解密对象<", enHexRes, ">")

sm4_decode(key,enHexRes)

# main
if __name__ == '__main__':
print("加解密测试: ")
test()

实验结果

1
2
3
4
5
6
7
加解密测试: 
明文: 1234567890abcdef
密文: dfe55390cd4644938b94f6d6073e370ba7cba2fe75751ce0d170047b92d3ae58
解密对象< dfe55390cd4644938b94f6d6073e370ba7cba2fe75751ce0d170047b92d3ae58 >
解密后明文: b'1234567890abcdef'

Process finished with exit code 0