|
|
|
@ -1,22 +1,32 @@
|
|
|
|
|
import base64
|
|
|
|
|
import os
|
|
|
|
|
|
|
|
|
|
from gmssl import sm4
|
|
|
|
|
|
|
|
|
|
def encrypt_ecb(data, key):
|
|
|
|
|
"""
|
|
|
|
|
输入:
|
|
|
|
|
消息或者加密后消息:字符串类型
|
|
|
|
|
key:字节类型
|
|
|
|
|
输出:
|
|
|
|
|
消息或者加密后消息:base64的字符串类型
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def encrypt_ecb(data: str, key: bytes) -> str:
|
|
|
|
|
cipher = sm4.CryptSM4()
|
|
|
|
|
cipher.set_key(key.encode('utf-8'), sm4.SM4_ENCRYPT)
|
|
|
|
|
cipher.set_key(key, sm4.SM4_ENCRYPT)
|
|
|
|
|
encrypted_data = cipher.crypt_ecb(data.encode('utf-8'))
|
|
|
|
|
return encrypted_data.hex()
|
|
|
|
|
return base64.b64encode(encrypted_data).decode('utf-8')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def decrypt_ecb(encrypted_hex, key):
|
|
|
|
|
def decrypt_ecb(encrypted_hex: str, key: bytes) -> str:
|
|
|
|
|
cipher = sm4.CryptSM4()
|
|
|
|
|
cipher.set_key(key.encode('utf-8'), sm4.SM4_DECRYPT)
|
|
|
|
|
cipher.set_key(key, sm4.SM4_DECRYPT)
|
|
|
|
|
decrypted_data = cipher.crypt_ecb(bytes.fromhex(encrypted_hex))
|
|
|
|
|
return decrypted_data.decode('utf-8')
|
|
|
|
|
|
|
|
|
|
def encrypt_cbc_with_iv(data, key):
|
|
|
|
|
|
|
|
|
|
def encrypt_cbc_with_iv(data: str, key: bytes) -> str:
|
|
|
|
|
cipher = sm4.CryptSM4()
|
|
|
|
|
cipher.set_key(key.encode('utf-8'), sm4.SM4_ENCRYPT)
|
|
|
|
|
cipher.set_key(key, sm4.SM4_ENCRYPT)
|
|
|
|
|
|
|
|
|
|
# 生成随机的16字节IV
|
|
|
|
|
iv = os.urandom(16)
|
|
|
|
@ -25,11 +35,13 @@ def encrypt_cbc_with_iv(data, key):
|
|
|
|
|
encrypted_data = cipher.crypt_cbc(iv, data.encode('utf-8'))
|
|
|
|
|
|
|
|
|
|
# 将IV和加密后的数据拼接在一起
|
|
|
|
|
return iv + encrypted_data
|
|
|
|
|
return base64.b64encode(iv + encrypted_data).decode('utf-8')
|
|
|
|
|
|
|
|
|
|
def decrypt_cbc_with_iv(encrypted_bytes, key):
|
|
|
|
|
|
|
|
|
|
def decrypt_cbc_with_iv(encrypted_bytes_base64: str, key) -> str:
|
|
|
|
|
encrypted_bytes = base64.b64decode(encrypted_bytes_base64)
|
|
|
|
|
cipher = sm4.CryptSM4()
|
|
|
|
|
cipher.set_key(key.encode('utf-8'), sm4.SM4_DECRYPT)
|
|
|
|
|
cipher.set_key(key, sm4.SM4_DECRYPT)
|
|
|
|
|
|
|
|
|
|
# 提取IV
|
|
|
|
|
iv = encrypted_bytes[:16]
|
|
|
|
@ -39,12 +51,13 @@ def decrypt_cbc_with_iv(encrypted_bytes, key):
|
|
|
|
|
|
|
|
|
|
# 解密数据
|
|
|
|
|
decrypted_data = cipher.crypt_cbc(iv, encrypted_data)
|
|
|
|
|
return decrypted_data.decode('utf-8')
|
|
|
|
|
return base64.b64decode(decrypted_data).decode('utf-8')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
|
# 示例数据和密钥
|
|
|
|
|
data = "Hello, SM4!"
|
|
|
|
|
key = "1234567890abcdef"
|
|
|
|
|
key = b"1234567890abcdef"
|
|
|
|
|
|
|
|
|
|
# 加密
|
|
|
|
|
encrypted_data = encrypt_ecb(data, key)
|
|
|
|
@ -56,7 +69,7 @@ if __name__ == "__main__":
|
|
|
|
|
|
|
|
|
|
# 示例数据和密钥
|
|
|
|
|
data = "Hello, SM4 CBC with random IV!"
|
|
|
|
|
key = "1234567890abcdef"
|
|
|
|
|
key = b"1234567890abcdef"
|
|
|
|
|
|
|
|
|
|
# 加密
|
|
|
|
|
encrypted_data = encrypt_cbc_with_iv(data, key)
|
|
|
|
|