國密sm4--python版

國密sm4--python版

國密sm4

sm4 算法是一個分組算法,用於無線局域網產品。該算法的分組長度爲128比特,密鑰長度爲128比特。加密算法與密鑰擴展算法都採用32輪非線性迭代結構。解密算法與加密算法的結構相同,只是輪密鑰的使用順序相反,解密輪密鑰是加密輪密鑰的逆序。python

GmSSL

GmSSL是一個開源的加密包的python實現,支持SM2/SM3/SM4等國密(國家商用密碼)算法、項目採用對商業應用友好的類BSD開源許可證,開源且能夠用於閉源的商業應用。git

python程序

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


class SM4:
    """
    國密sm4加解密
    """

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

    def str_to_hexStr(self, hex_str):
        """
        字符串轉hex
        :param hex_str: 字符串
        :return: hex
        """
        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
        :param value: 待加密的字符串
        :return: sm4加密後的hex值
        """
        crypt_sm4 = self.crypt_sm4
        crypt_sm4.set_key(encrypt_key.encode(), 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_value = crypt_sm4.crypt_ecb(bytes.fromhex(encrypt_value))  # bytes類型
        return self.str_to_hexStr(decrypt_value.hex())
 str_data = {"ffffffwsdwefewd": "fefefewfwrv", "qazqaz": "vfbfrbgtrnujy"}
 key = "3l5butlj26hvv313"
 SM4 = SM4()
 print("待加密內容:", str_data)
 encoding = SM4.encrypt(key, str_data)
 print("國密sm4加密後的結果:", encoding)
 print("國密sm4解密後的結果:", SM4.decrypt(key, encoding))

python結果

相關文章
相關標籤/搜索