Search code examples
pythonopensslpyopensslpython-cryptography

Encrypting private key in Python


I have a private key in DER format. I am trying to convert it to PEM and simultaneously encrypt the private key with a passphrase.

Here is the openssl command that I am using to convert and encrypt:

> openssl rsa -aes256 -inform der -in temp_key.der -outform pem -passout pass:<password>

I am trying to implement a similar logic in Python where I have the data for the key in-memory in DER format. I want to change it to PEM, encrypt it and then store to a file.

I am not very well versed with Python's Crypto libraries and I am having a hard time to figure out the right way to convert and encrypt my key data.


Solution

  • You can load a DER key and dump it as a password protected PEM key with help of cryptography module as follows:

    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives.asymmetric import rsa
    from cryptography.hazmat.primitives import serialization
    
    private_key = serialization.load_der_private_key(
        der_data, # assuming that "der_data" variable contains your DER key
        password=None,
        backend=default_backend()
    )
    
    pem_encrypted = private_key.private_bytes(
        encoding=serialization.Encoding.PEM,
        format=serialization.PrivateFormat.PKCS8,
        encryption_algorithm=serialization.BestAvailableEncryption(b'mypassword')
    )
    
    print(pem_encrypted.decode()) # -----BEGIN ENCRYPTED PRIVATE KEY-----...