SM2 加解密 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
from gmssl import sm2
from base64 import b64encode, b64decode
# sm2的公私钥
# SM2_Public_Key = 'B9C9A6E04E9C91F7BA880429273747D7EF5DDEB0BB2FF6317EB00BEF331A83081A6994B8993F3F5D6EADDDB81872266C87C018FB4162F5AF347B483E24620207'
# SM2_Private_Key = '00B9AB0B828FF68872F21A837FC303668428DEA11DCD1B24429D0C99E24EED83D5'

# sm2公私钥生成网站
# https://const.net.cn/tool/sm2/genkey/
SM2_Public_Key = '99B7A22845A59292F2841AA543C36D55FF92221EC919C67B4847571FE2256265B614F70053057908955757395AD18290BFC7B1B6111305760F8DAB5003AFA148'
SM2_Private_Key = '91EA7935FF011F08CBA52E221C52BBC6042058107DCE6D22F84D9A8D338B8075'

sm2_crypt = sm2.CryptSM2(public_key=SM2_Public_Key, private_key=SM2_Private_Key)

# 加密
def Encrypt(message):
# 使用sm2_crypt库进行加密,将明文信息转换为二进制bytes
encode_info = sm2_crypt.encrypt(message.encode(encoding="utf-8"))
# 将二进制bytes通过base64编码,以便于传输和存储
encode_info = b64encode(encode_info).decode()
# 返回加密后的字符串
return encode_info


# 解密
def Decrypt(cipher):
# 通过base64解码,将加密后的字符串转换回二进制bytes
decode_info = b64decode(cipher.encode())
# 使用sm2_crypt库进行解密,将二进制bytes转换为明文信息
decode_info = sm2_crypt.decrypt(decode_info).decode(encoding="utf-8")
# 返回解密后的明文信息
return decode_info

if __name__ == "__main__":
message = "1234567890123abc"
encode_message = Encrypt(message)
print("加密结果为: " + encode_message)
decode_cipher = Decrypt(encode_message)
print("解密结果为: " + decode_cipher)

实验结果

1
2
3
4
加密结果为: Md2B+Ipf2QnOSiS3yoCHN4qx4bAUJLj3S3Ac/7ssEdDOj00G8QePWUWCMH+ik5h9+2JY9qeiYLM2jUK0/tkNQAJMb1tF7fXeqRpr5lxg5e1tJilxUolsjEFO5j0Motn3MxzV/MvBst4dgIlorQ0ftw==
解密结果为: 1234567890123abc

Process finished with exit code 0