Python SM4 加密&解密


# SM4加密/解密

# CryptSM4中的crypt_ecb,crypt_ecb加解密,完成后,均為十六進制的bytes類型,用base64.b64encode,base64.b64decode 去轉碼成接口常用的類型

# 因為是剛學習不久,對封裝的處理不盡人意,后續再來優化,注釋中涉及的轉碼的解釋,也比較不准確,大概是那么個意思,好在加密/解密已經實現


import json

from gmssl.sm4 import CryptSM4, SM4_ENCRYPT, SM4_DECRYPT
import base64

class SM4Utils:


def __init__(self, ):
pass

# 加密方法
def encryptData_ECB(self, plain_text):
# 創建 SM4對象
crypt_sm4 = CryptSM4()
# 定義key值
secret_key = b"JeF38U9wT9wlMfs2"
# print("key: ", secret_key)

# 設置key
crypt_sm4.set_key(secret_key, SM4_ENCRYPT)

# 調用加密方法加密(十六進制的bytes類型)
encrypt_value = crypt_sm4.crypt_ecb(plain_text)
# print("encrypt_value: ", encrypt_value)

# 用base64.b64encode轉碼(編碼后的bytes)
cipher_text = base64.b64encode(encrypt_value)

# print("加密后:", cipher_text)
# print(cipher_text.decode('utf-8', 'ignore'))
# 返回加密后的字符串
return cipher_text.decode('utf-8', 'ignore')

def decryptData_ECB(self, cipher_text):
crypt_sm4 = CryptSM4()
secret_key = b"JeF38U9wT9wlMfs2"
print(secret_key)
crypt_sm4.set_key(secret_key, SM4_DECRYPT)
# 將轉入參數base64.b64decode解碼成十六進制的bytes類型
byt_cipher_text = base64.b64decode(cipher_text)
# 調用加密方法解密,解密后為bytes類型
decrypt_value = crypt_sm4.crypt_ecb(byt_cipher_text)
print(decrypt_value)
print(decrypt_value.decode('utf-8', 'ignore'))
print(json.dumps(decrypt_value.decode('utf-8', 'ignore')))

return decrypt_value.decode('utf-8', 'ignore')



if __name__ == '__main__':
SM4_Utils = SM4Utils()

plain_text = b'{"t":1625451188275,"userToken":"c49bdd6a558948ec86c957c8bd07c1c8"}'
# plain_text = "aaa"
SM4_Utils.encryptData_ECB(plain_text)

cipher_text = r"vk2cLOFpUU9fpOs5p9+Mjdl2Ik3s/XXS/BJE1Sgbt8jPFh1kmV2Gf0UUO4ak/Xq4NVARIeK73Q9w7G4MOnRdvxnS4XCWYl7huV2GNew6MEo="
SM4_Utils.decryptData_ECB(cipher_text)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM