gpt4 book ai didi

python - pyOpenSSL 创建一个 pem 文件

转载 作者:太空狗 更新时间:2023-10-30 02:32:11 31 4
gpt4 key购买 nike

我在 python 中使用以下代码和 pyOpenSSL 创建了一个 key 对:

from OpenSSL import crypto
k = crypto.PKey()
k.generate_key(crypto.TYPE_RSA, 2048)
  1. 现在如何从 key 对象创建私钥和公钥 .pem 文件?
  2. 如果有可用的教程,请告诉我。我没有找到。从手册中很难知道,因为我是 OpenSSL 的新手。
  3. 如果 RSA 中没有使用特定的唯一 key ,相同代码创建两个相同 key 对的可能性有多大?

最佳答案

我知道这是一个老问题 - 但正如我刚刚发现的那样,我想我应该添加一个答案。

使用 Python 3.x 执行此操作的最简单方法是使用 PyCryptodome .

Python 中的(对于 2048 位 key ):

from Cryptodome.PublicKey import RSA
key = RSA.generate(2048)
pv_key_string = key.exportKey()
with open ("private.pem", "w") as prv_file:
print("{}".format(pv_key_string.decode()), file=prv_file)

pb_key_string = key.publickey().exportKey()
with open ("public.pem", "w") as pub_file:
print("{}".format(pb_key_string.decode()), file=pub_file)

如果您想在 (Linux) 命令行上检查私钥,请使用:

$ openssl rsa -check -inform pem -noout -in private.pem 
RSA key ok
...

关于python - pyOpenSSL 创建一个 pem 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19651587/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com