简体   繁体   中英

Convert .key formatted private key into .pem format with python3

I am trying to convert .key formatted private key into .pem formatted key using python3. Before using python3 I was able to convert private key into .pem format by simply running openssl command as:

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

I would like to know how people are using python3 to convert it private keys into .pem or other formats. So far I've tried running subprocess.run() command to execute openssl command from python. It would be nice to know if there is python way of converting into .pem format.

I also tried following using pycryptodrome library https://pycryptodome.readthedocs.io/en/latest/index.html as per this thread pyOpenSSL creating a pem file which creates in pem format but wasn't successful.

 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)

This is my code. Any help would be appreciated.

From the Cryptodome library, you can use the import_key method, which supports the following formats for an RSA private key :

  • PKCS#1 RSAPrivateKey DER SEQUENCE (binary or PEM encoding)
  • PKCS#8_ PrivateKeyInfo or EncryptedPrivateKeyInfo DER SEQUENCE (binary or PEM encoding)

Here's how you could use it:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM