国产加密算法:SM4 python3版本

# -*- coding:utf-8 -*-

from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT
import binascii
from heapq import heappush, heappop
from collections import OrderedDict
import time
import requests


class MY_SM4:

    '''
    国密sm4加解密
    '''

    def __init__(self):
        self.crypt_sm4 = CryptSM4()

    def str_to_hexStr(self, 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: sm4加密key
        :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_hexStr(d_value.hex())


if __name__ == "__main__":
    sm4_ = MY_SM4()
    keys = [-30, -128, 69, 101, 38, 0, -111, 57, -71, -24, -45, -105, 1, -34, -20, 52]  # key 经过fromhexString 得到的数组
    key = bytes(b % 256 for b in keys)
    # value = '718bac1c035df6113da34cfb8ede22ad1c16ccd17c1bb930f76a46684d62edb9ac7365d6a7282c50fe640ab64cb7fe60'
    value = '718bac1c035df6113da34cfb8ede22ad1c16ccd17c1bb930f76a46684d62edb9788a0f6ed4d7ea64ec99185318378876'
    # 解密测试
    result = sm4_.decrypt(key, value)
    print('result:', result)
    # 加密测试
    encrypt_params = 'E280456526009139B9E8D39701DEEC34' + str(int(time.time() * 1000))
    result1 = sm4_.encrypt(key, encrypt_params)
    print('result1:', result1)

参考资料:https://blog.csdn.net/jihezhixin/article/details/89513537

https://blog.csdn.net/boblee12qq/article/details/109293334

 

 

  • 0
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 7
    评论
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值