pythonencryptionopensslpyopenssl

pyOpenSSL RSA private keys encrypted with AES 256


In pyOpenSSL i haven't been able to find a way to encrypt a RSA private key with AES 256 just yet, been looking all over the place for this but cant seem to find a way.

Before i used OpenSSL to get the key and ca/cl certificates but now im opting to make an application where i need to handle the pfx-file in certain ways.

In OpenSSL i used to do the following:

openssl pkcs12 -in file.pfx -nocerts -out key.key

after that i did:

openssl rsa -aes256 -key.key -out encrypted.key

is there anything similar in pyOpenSSL using crypto?


Solution

  • I believe I solved this. But for anyone wondering, this is what I did:

    import os
    import shutil
    from Crypto.PublicKey import RSA
    
    
    def encrypt(old_key, new_key, passphrase):
            key = RSA.importKey(open(old_key, 'rb').read())
    
            with open(new_key, 'wb') as f:
                    pem_key = key.export_key(format='PEM', passphrase=passphrase, pkcs=8, protection='PBKDF2WithHMAC-SHA1AndAES256-CBC')
    
                    f.write(pem_key)
                    f.close()
    
            if os.path.exists(old_key):
                    os.remove(old_key)
    
    
    encryptAES('path_to_old_key', 'path_to_new:key.key', 'supersecretpassword')
    

    One question still remaining is if there's anyway to output the encryption info done in python similar to OpenSSL?

    If you run openssl rsa -aes256 -in old.key -out new.key

    The key will return attributes in the beginning like such:

    -----BEGIN RSA PRIVATE KEY-----
    Proc-Type: 4,ENCRYPTED
    DEK-Info: AES-256-CBC
    Key here...
    -----END RSA PRIVATE KEY-----
    

    However when I export the private key in Python I just get:

    -----BEGIN ENCRYPTED PRIVATE KEY-----
    Key here...
    -----END ENCRYPTED PRIVATE KEY-----
    

    Is there anyway to display these attributes with pycryptodome?