使用python3将.key格式的私钥转换为.pem格式

问题描述

我正在尝试使用python3将.key格式的私钥转换为.pem格式的密钥。在使用python3之前,我只需将openssl命令运行为即可将私钥转换为.pem格式:

openssl rsa -in <private_key_file> -outform PEM -out <new_file>

我想知道人们如何使用python3将私钥转换为.pem或其他格式。到目前为止,我已经尝试运行subprocess.run()命令来从python执行openssl命令。很高兴知道是否存在将python转换为.pem格式的方法

我还尝试按照此线程https://pycryptodome.readthedocs.io/en/latest/index.html使用pycryptodrome库pyOpenSSL creating a pem file,该线程以pem格式创建,但未成功。

 def convert_key_to_pem_format(key_file):
     print("Converting to pem/rsa format")
     pv_key_string = key_file.exportKey()
     with open ("private.pem","w") as prv_file:
     print("{}".format(pv_key_string.decode()),file=prv_file)

这是我的代码。任何帮助将不胜感激。

解决方法

从Cryptodome库中,您可以使用import_key方法,该方法支持RSA 私钥 的以下格式:

  • PKCS#1 RSAPrivateKey DER SEQUENCE(二进制或PEM编码)
  • PKCS#8_ PrivateKeyInfoEncryptedPrivateKeyInfo DER SEQUENCE(二进制或PEM编码)

这里是使用方式:

from Cryptodome.PublicKey import RSA
key = RSA.import_key(open('private.key',"rb").read(),passphrase="(passphrase in case you have one)")

pv_key_string = key.exportKey()
with open ("private.pem","w") as prv_file:
    print("{}".format(pv_key_string.decode()),file=prv_file)