简体   繁体   中英

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.

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), eg:

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.

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