用python 写一个sm2 加解密算法
时间: 2024-09-09 07:01:53 浏览: 89
国密SM2,SM3,SM4加解密的python实现
SM2是一种中国国家密码管理局发布的非对称加密算法,类似于RSA。在Python中,你可以使用第三方库`pycryptodome`来实现SM2的加解密操作。以下是一个简单的示例,展示了如何使用`pycryptodome`进行SM2的加解密:
```python
from Crypto.PublicKey import SM2
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Util.Padding import pad, unpad
# 生成SM2秘钥对
private_key = SM2.generate(2048)
public_key = private_key.publickey()
# 将私钥转换为PEM格式便于存储
private_key_pem = private_key.export_key()
with open('private.pem', 'wb') as f:
f.write(private_key_pem)
# 使用公钥加密数据
plaintext = b'This is a secret message.'
cipher_rsa = PKCS1_OAEP.new(public_key)
ciphertext = cipher_rsa.encrypt(plaintext)
# 使用私钥解密数据
with open('private.pem', 'rb') as f:
private_key_imported = SM2.import_key(f.read())
decrypted_cipher = private_key_imported.decrypt(ciphertext)
plaintext_decrypted = unpad(decrypted_cipher, SM2.block_size)
print("Original text:", plaintext.decode())
print("Decrypted text:", plaintext_decrypted.decode())
阅读全文