3 Star 2 Fork 0

孔垂闽/man-k电子公文系统

Create your Gitee Account
Explore and code with more than 13.5 million developers,Free private repositories !:)
Sign up
文件
Clone or Download
commercial_cryptography.py 1.75 KB
Copy Edit Raw Blame History
# @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)
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C
1
https://gitee.com/kcf03/man-k.git
git@gitee.com:kcf03/man-k.git
kcf03
man-k
man-k电子公文系统
0d9851e308a40770bd47ef9f0c2847d586c9ff59

Search