Fetch the repository succeeded.
# @Description:国密算法
from gmssl import sm2, sm3, sm4, func
from pysmx.SM2 import generate_keypair
ENCODING = "utf8"
SM2_LEN = 64
def bytes_to_hex_bytes(content: bytes) -> bytes:
"""将普通字节转换为十六进制再转换为字节"""
return bytes.fromhex(content.decode(ENCODING))
def sm2_generate_key() -> tuple[str, str]:
"""生成sm2密钥对"""
public, private = generate_keypair(SM2_LEN)
return public.hex(), private.hex()
def sm2_encrypt(content: bytes, public_key: str, private_key: str) -> bytes:
"""使用sm2算法加密"""
# 创建后端传前端SM2对象
crypt = sm2.CryptSM2(
public_key=public_key,
private_key=private_key
)
return crypt.encrypt(content)
def sm2_decrypt(content: str, public_key: str, private_key: str) -> bytes:
"""使用sm2算法解密"""
# 创建后端传前端SM2对象
crypt = sm2.CryptSM2(
public_key=public_key,
private_key=private_key
)
return bytes_to_hex_bytes(crypt.decrypt(bytes.fromhex(content)))
def sm3_encrypt(content: bytes) -> str:
"""生成sm3摘要"""
return sm3.sm3_hash(func.bytes_to_list(content))
def encode_sm4(value: bytes, key: bytes) -> bytes:
"""SM4加密"""
crypt_sm4 = sm4.CryptSM4()
crypt_sm4.set_key(key, sm4.SM4_ENCRYPT)
# 使用crypt_ecb进行加密value
encrypt_value = crypt_sm4.crypt_ecb(value)
return encrypt_value
def decode_sm4(value: str, key: bytes) -> bytes:
"""SM4解密"""
crypt_sm4 = sm4.CryptSM4()
crypt_sm4.set_key(key, sm4.SM4_DECRYPT)
# 将加密数据通过SM_KEY进行解密;
decrypt_value = crypt_sm4.crypt_ecb(bytes.fromhex(value))
return bytes_to_hex_bytes(decrypt_value)
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。