Search code examples
pythonaesrsapycrypto

How to sign data with encrypted RSA private key (AES-256-CBC) in python


Partial example of private_key (this variable is a string):

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

lots_of_hidden_text..

-----END RSA PRIVATE KEY-----

When I try to do the following:

from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
rsakey = RSA.importKey(private_key, passphrase=privkey_secret_string)
signer = PKCS1_v1_5.new(rsakey)
signature = signer.sign(data)

I'm getting value error on the importKey:

Error: ValueError: Unsupport PEM encryption algorithm.

I can see that RSA.importKey doesn't support AES-256-CBC, but i can't find any way to import this private key.

The only solution i've seen in order to create an AES signer is:

signer = AES.new(privkey_secret_string, AES.MODE_CBC, IV=iv)

But this doesn't use the private key


Solution

  • You can either switch to PyCryptodome or decrypt the key with a system call to openssl prior to importing the key:

    echo PASSPHRASE | openssl rsa -in key.pem