0

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.

Script_Junkie
  • 277
  • 2
  • 6
  • 17
  • It's not clear to me what you mean by _.key_ formatted. Possibly PKCS#8, since the posted statement can convert a PKCS#8 to a PKCS#1 key (PEM encoded). Please post an example of your keys (or the respective headers in case of PEM encoding). – Topaco Sep 21 '20 at 06:54
  • It's a mistake to assume that the file extension uniquely identifies the format of cryptographic keys. Unfortunately, neither `.pem` nor `.key` does so. When I create files for my crypto experiments I always try to use a unique suffix, like `.pk8` for PKCS#8 private keys. – President James K. Polk Sep 21 '20 at 20:49

1 Answers1

0

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)
lab9
  • 596
  • 2
  • 8
  • According to the description of [`openssl rsa`](https://www.openssl.org/docs/man1.1.1/man1/openssl-rsa.html) `PEM` is the default regarding `-inform` / `-outform`. – Topaco Sep 21 '20 at 08:37
  • @Topaco, you're right, I've edited my answer accordingly. – lab9 Sep 21 '20 at 10:03