python生成RSA密钥对
要在Python中生成RSA密钥对,可以使用cryptography库。首先,确保已经安装了该库。可以使用以下命令安装:
pip install cryptography
接下来,可以使用以下代码生成RSA密钥对:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
# 生成RSA密钥对
private_key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048
)
# 获取私钥的PEM编码
private_pem = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
# 打印私钥
print(private_pem.decode())
# 获取公钥
public_key = private_key.public_key()
# 获取公钥的PEM编码
public_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
# 打印公钥
print(public_pem.decode())
以上代码生成了一个2048位的RSA密钥对,并打印了私钥和公钥的PEM编码
原文地址: http://www.cveoy.top/t/topic/i1PQ 著作权归作者所有。请勿转载和采集!