Rahul Goud
Rahul Goud

Reputation: 147

Python convert Private Key to RSA Key

I have a Private Key with the following format

-----BEGIN ENCRYPTED PRIVATE KEY-----
MIIE6TAbBgkqhki....
----END ENCRYPTED PRIVATE KEY-----

How can I convert this in a key with RSA format

-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEA28jIsb8SAhJritwO....
-----END RSA PRIVATE KEY-----

The current version of cryptography I have is 2.8. Any help is really appreciated. Thanks in advance.

Upvotes: 3

Views: 4057

Answers (1)

Topaco
Topaco

Reputation: 49425

As described in the comment by Maarten Bodewes, a conversion of a encrypted private key in PKCS#8 format to a private key in PKCS#1 format (both PEM encoded) is possible with OpenSSL. But this can also be done with the Cryptography library.

The Cryptography library supports the import of (encrypted) private keys in PKCS#8 format, PEM encoded, with the method load_pem_private_key() (since version 0.6), e.g.:

from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization

pkcs8Encrypted = b"""-----BEGIN ENCRYPTED PRIVATE KEY-----
MIICzzBJB...
-----END ENCRYPTED PRIVATE KEY-----"""

privateKey = serialization.load_pem_private_key(
    pkcs8Encrypted, 
    b'mypassword',
    default_backend()
)

The export of private keys in PKCS#1 format, PEM encoded is possible with private_bytes() (since version 0.2):

pkcs1 = privateKey.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption()
)

print(pkcs1.decode('utf-8')) # -----BEGIN RSA PRIVATE KEY-----... 

The current version of Cryptography is 3.4.7 (Mar 2021). 2.8 is from Oct 2019, s. Release history. Actually, both methods should therefore be available.

Upvotes: 6

Related Questions