python实现输入十六进制字符串key和待加密的值,返回加密后的十六进制值
关键在于对十六进制字符串key的处理
from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT
import binascii
class MY_SM4(object):
"""
国密sm4加解密
"""
def __init__(self):
self.crypt_sm4 = CryptSM4()
@staticmethod
def str_to_hex_str(hex_str):
"""
字符串转hex
:param hex_str:
:return:
"""
hex_data = hex_str.encode('utf-8')
str_bin = binascii.unhexlify(hex_data)
return str_bin.decode('utf-8')
def encrypt(self, encrypt_key, value):
"""
国密sm4加密
:param encrypt_key:
:param value:
:return: sm4加密后的hex值
"""
crypt_sm4 = self.crypt_sm4
# crypt_sm4.set_key(encrypt_key.encode(), SM4_ENCRYPT) # encrypt_key: 字节类型
crypt_sm4.set_key(encrypt_key, SM4_ENCRYPT)
encrypt_value = crypt_sm4.crypt_ecb(value.encode()) # bytes类型
return encrypt_value.hex()
def decrypt(self, decrypt_key, encrypt_value):
"""
国密sm4解密
:param decrypt_key: sm4加密key
:param encrypt_value: 待解密的hex值
:return:
"""
crypt_sm4 = self.crypt_sm4
# crypt_sm4.set_key(decrypt_key.encode(), SM4_DECRYPT) # decrypt_key: 字节类型
crypt_sm4.set_key(decrypt_key, SM4_DECRYPT)
d_value = crypt_sm4.crypt_ecb(bytes.fromhex(encrypt_value)) # bytes类型
return self.str_to_hex_str(d_value.hex())
if __name__ == "__main__":
sm4_ = MY_SM4()
key = "0CC5D57BF7D4F3B4F7BB7700572C25C4"
keys = [int(key[2*i:2*i+2], 16) for i in range(16)]
print(keys)
key = bytes(b % 256 for b in keys)
# # 加密测试
encrypt_params = '13508081234'
result1 = sm4_.encrypt(key, encrypt_params)
print('result1:', result1)