要生成RSA密钥对并保存为文件,可以使用Python中的cryptography库。

首先,确保已安装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,
)

# 将私钥保存到文件
with open("private.pem", "wb") as private_file:
    private_file.write(private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.NoEncryption()
    ))

# 获取公钥
public_key = private_key.public_key()

# 将公钥保存到文件
with open("public.pem", "wb") as public_file:
    public_file.write(public_key.public_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PublicFormat.SubjectPublicKeyInfo
    ))

这样,生成的RSA公钥和私钥将分别保存在public.pemprivate.pem文件中。

python生成RSA密钥对将公钥的base64编码形式保存在publicpem文件里私钥保存在privatepem文件里

原文地址: https://www.cveoy.top/t/topic/i10i 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录