Python使用gmssl实现SM4加解密
from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT
from gmssl.sm2 import CryptSM2
import string
import base64
class SM4Utils:
secret_key = b''
def __init__(self, secret_key):
self.secret_key = secret_key
# 加密方法
def encryptData_ECB(self, plain_text):
# 创建 SM4对象
crypt_sm4 = CryptSM4()
# 定义key值
# secret_key = b"nXVeb/hgPKFLPA=="
# 设置key
crypt_sm4.set_key(self.secret_key, SM4_ENCRYPT)
# 调用加密方法加密(十六进制的bytes类型)
encrypt_value = crypt_sm4.crypt_ecb(plain_text)
# 用base64.b64encode转码(编码后的bytes)
cipher_text = base64.b64encode(encrypt_value)
# 返回加密后的字符串
return cipher_text.decode('utf-8', 'ignore')
def decryptData_ECB(self, cipher_text):
crypt_sm4 = CryptSM4()
# secret_key = b"K0qBoObS8kmfjemG"
print(self.secret_key)
crypt_sm4.set_key(self.secret_key, SM4_DECRYPT)
# 将转入参数base64.b64decode解码成十六进制的bytes类型
byt_cipher_text = base64.b64decode(cipher_text)
# 调用加密方法解密,解密后为bytes类型
decrypt_value = crypt_sm4.crypt_ecb(byt_cipher_text)
return decrypt_value.decode('utf-8', 'ignore')
def encryptData_CBC(self, iv, key, plain_text):
# 创建 SM4对象
crypt_sm4 = CryptSM4()
# 校验key值
iv = check_type(iv)
key = check_type(key)
# 设置key
crypt_sm4.set_key(key, SM4_ENCRYPT)
# 调用加密方法加密(十六进制的bytes类型)
encrypt_value = crypt_sm4.crypt_cbc(iv,plain_text)
# 用base64.b64encode转码(编码后的bytes)
cipher_text = base64.b64encode(encrypt_value)
# 返回加密后的字符串
return cipher_text.decode('utf-8', 'ignore')
def decryptData_CBC(self,iv, key, cipher_text):
crypt_sm4 = CryptSM4()
# secret_key = b"K0qBoObS8kmfjemG"
crypt_sm4.set_key(self.secret_key, SM4_DECRYPT)
# 将转入参数base64.b64decode解码成十六进制的bytes类型
byt_cipher_text = base64.b64decode(cipher_text)
# 调用加密方法解密,解密后为bytes类型
decrypt_value = crypt_sm4.crypt_cbc(iv, byt_cipher_text)
return decrypt_value.decode('utf-8', 'ignore')
if __name__ == '__main__':
key = b'EBVLDDG5Zs0iE0SO'
SM4_Utils = SM4Utils(key)
plain_text = b'{"t":1625451188275,"userToken":"c49bdd6a558948ec86c957c8bd07c1c8"}'
# # plain_text = "aaa"
cipher_text = SM4_Utils.encryptData_ECB(plain_text)
print("加密后%s" %cipher_text)
print("解密后%s" %SM4_Utils.decryptData_ECB(cipher_text))