PyCrypto: Generate RSA key protected with DES3 password
Asked Answered
S

1

7

I have been able to create a RSA key protected by password with DES3 (well... I think because I'm very new to this encryption world) by using the command:

openssl genrsa -out "/tmp/myKey.pem" -passout pass:"f00bar" -des3 2048

Now, I would like to do that inside a Python script, using PyCrypto, if possible. I have seen this message, which seems to discourage the use of PyCrypto to do that. Is it still like that?

Of course I can always call os.execute, and execute the above command, but I'd consider that "cheating" :-). I'm pretty much doing this to learn PyCrypto.

Thank you in advance.

Smudge answered 2/4, 2012 at 15:39 Comment(0)
A
6

Starting from PyCrypto 2.5 you can export an RSA private key and have it protected under a passphrase. A Triple DES key is internally derived from the passphrase and used to perform the actual encryption.

For instance:

from Crypto import RSA
from Crypto import Random

random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
exportedKey = key.exportKey('PEM', 'my secret', pkcs=1)

The variable exportedKey contains an ASCII version (PEM) of the key, encoded according to PKCS#1 (a cryptographic standard. Another option is pkcs=8 for - guess what - PKCS#8). Since the result is standard, you can use it with several other programs, including openssl. And of course, you can also re-import it back into python via PyCrypto!

The exportKey method is documented here.

Apex answered 2/4, 2012 at 19:46 Comment(3)
Working like a charm! I got almost the same output than with the openssl command: Proc-Type: 4,ENCRYPTED DEK-Info: DES-EDE3-CBC,F7149C8E62E0854B 4fUV/FmaMmL7qZH83+ocigFy [...]Smudge
Just to make I understand, that means that the command exportedKey = key.exportKey('PEM', 'my secret', pkcs=1), generates RSA keys from the password 'my secret'? Does 'PEM' and pkcs have security implications?Valle
The RSA key is created when the method generate is called. The method export takes it and encodes it in PEM format. PEM and PKCS formats don't have evident (to me) security weaknesses. The interesting bit is how the 3DES key is derived from the password: that mimics openssl, which uses a quite outdated algorithm.Apex

© 2022 - 2024 — McMap. All rights reserved.