sm2加解密 python
时间: 2023-10-29 20:06:47 浏览: 185
国密sm2、3、4前后端联调加解密.docx
好的,关于sm2加解密,你可以使用Python的cryptography库来实现。具体步骤如下:
1. 安装cryptography库:在命令行中输入`pip install cryptography`即可安装。
2. 生成密钥对:使用cryptography库中的`generate_key_pair()`函数生成密钥对。示例代码如下:
```python
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import utils
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.hazmat.primitives.serialization import PrivateFormat
from cryptography.hazmat.primitives.serialization import PublicFormat
private_key = ec.generate_private_key(ec.SECP256R1())
public_key = private_key.public_key()
# 将私钥和公钥分别保存到文件中
with open('private_key.pem', 'wb') as f:
f.write(private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, utils.NoEncryption()))
with open('public_key.pem', 'wb') as f:
f.write(public_key.public_bytes(Encoding.PEM, PublicFormat.SubjectPublicKeyInfo))
```
3. 加密数据:使用cryptography库中的`SM2.encrypt()`函数加密数据。示例代码如下:
```python
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import utils
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.hazmat.primitives.serialization import PublicFormat
from cryptography.hazmat.primitives.asymmetric import padding
# 读取公钥
with open('public_key.pem', 'rb') as f:
public_key = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), f.read())
# 加密数据
plaintext = b'Hello, world!'
ciphertext = public_key.encrypt(plaintext, padding.OAEP(padding.MGF1(algorithm=utils.Prehashed(ec.ECDSA(utils.PrehashedSHA256()))), algorithm=utils.Prehashed(ec.ECDSA(utils.PrehashedSHA256()))))
```
4. 解密数据:使用cryptography库中的`SM2.decrypt()`函数解密数据。示例代码如下:
```python
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.asymmetric import utils
from cryptography.hazmat.primitives.serialization import Encoding
from cryptography.hazmat.primitives.serialization import PrivateFormat
from cryptography.hazmat.primitives.asymmetric import padding
# 读取私钥
with open('private_key.pem', 'rb') as f:
private_key = ec.EllipticCurvePrivateKey.from_private_bytes(f.read())
# 解密数据
plaintext = private_key.decrypt(ciphertext, padding.OAEP(padding.MGF1(algorithm=utils.Prehashed(ec.ECDSA(utils.PrehashedSHA256()))), algorithm=utils.Prehashed(ec.ECDSA(utils.PrehashedSHA256()))))
print(plaintext)
```
阅读全文