Tutorial :Python RSA Decryption Using OpenSSL Generated Keys



Question:

Does anyone know the simplest way to import an OpenSSL RSA private/public key (using a passphrase) with a Python library and use it to decrypt a message.

I've taken a look at ezPyCrypto, but can't seem to get it to recognise an OpenSSL RSA key, I've tried importing a key with importKey as follows:

key.importKey(myKey, passphrase='PASSPHRASE')  

myKey in my case is an OpenSSL RSA public/private keypair represented as a string.

This balks with:

unbound method importKey() must be called with key instance as first argument (got str instance instead)

The API doc says:

importKey(self, keystring, **kwds)

Can somebody suggest how I read a key in using ezPyCrypto? I've also tried:

key(key, passphrase='PASSPHRASE')  

but this balks with:

ezPyCrypto.CryptoKeyError: Attempted to import invalid key, or passphrase is bad

Link to docs here:

http://www.freenet.org.nz/ezPyCrypto/detail/index.html

EDIT: Just an update on this. Successfully imported an RSA key, but had real problem decrypting because eqPyCrypto doesn't support the AES block cipher. Just so that people know. I successfully managed to do what I wanted using ncrypt (http://tachyon.in/ncrypt/). I had some compilation issues with M2Crypto because of SWIG and OpenSSL compilation problems, despite having versions installed that exceeded the minimum requirements. It would seem that the Python encryption/decryption frameworks are a bit of a minefield at the moment. Ho hum, thanks for your help.


Solution:1

The first error is telling you that importKey needs to be called on an instance of key.

k = key()  k.importKey(myKey, passphrase='PASSPHRASE')  

However, the documentation seems to suggest that this is a better way of doing what you want:

k = key(keyobj=myKey, passphrase='PASSPHRASE')  


Solution:2

It is not clear what are you trying to achieve, but you could give M2Crypto a try. From my point of view it is the best OpenSSL wrapper available for Python.

Here is a sample RSA encryption/decription code:

import M2Crypto as m2c  import textwrap  key = m2c.RSA.load_key('key.pem', lambda prompt: 'mypassword')    # encrypt something:  data = 'testing 123'  encrypted = key.public_encrypt(data, m2c.RSA.pkcs1_padding)  print "Encrypted data:"  print "\n".join(textwrap.wrap(' '.join(['%02x' % ord(b) for b in encrypted ])))    # and now decrypt it:  decrypted = key.private_decrypt(encrypted, m2c.RSA.pkcs1_padding)  print "Decrypted data:"  print decrypted  print data == decrypted  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »