python的cryptograph生成一个公钥和私钥
时间: 2023-09-25 20:15:32 浏览: 187
可以使用以下代码来生成公钥和私钥:
```python
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives import serialization
# 生成私钥
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
# 生成公钥
public_key = private_key.public_key()
# 将私钥和公钥序列化,以便保存到文件或传输
private_key_bytes = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
public_key_bytes = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# 将私钥和公钥保存到文件
with open('private_key.pem', 'wb') as f:
f.write(private_key_bytes)
with open('public_key.pem', 'wb') as f:
f.write(public_key_bytes)
```
注意:在实际使用中,私钥应该妥善保管,不要随意泄露。
阅读全文