python function for retrieving key and encryption

Piet van Oostrum piet at cs.uu.nl
Mon Jul 27 10:23:04 EDT 2009


>>>>> jayshree <jayshree06comp at gmail.com> (j) wrote:

>j> import M2Crypto
>j> from M2Crypto import RSA,SSL
>j> def encrypt():
>j>     pk = open('my_key.public.pem', 'rb').read()
>j>     rsa = M2Crypto.RSA.load_pub_key(pk) #return a M2Crypto.RSA.RSA_pub
>j> object.
>j>     plaintext = 4545479545655576767767686688782344
>j>     msg = rsa.public_encrypt(plaintext,RSA.pkcs1_padding)
>j>     print msg;
>j>     encrypt()

>j> This is code i am refering.
>j> The Problem is coming with .pem file.

You never tell what the problem is. Which error message do you get? Why
can't you just copy the error messages in your post instead of letting
us guess what is happening?

There are indeed problems with the code above. One warning: If you are
going to write cryptographic code while you really don't understand the
subject enough there is a big chance that your programs will have
security problems.

One more question: Do you have now a valid my_key.public.pem file? And
is it in the same directory where you run this program?

Here are the problems in your code (and there may be more!)

  import M2Crypto
  from M2Crypto import RSA,SSL

You never use the imports from the line above so you can leave it out.
SSL isn't used at all, and RSA is used as M2Crypto.RSA so it uses the
first import. Cleanliness is next to godliness.

  def encrypt():
      pk = open('my_key.public.pem', 'rb').read()
      rsa = M2Crypto.RSA.load_pub_key(pk) #return a M2Crypto.RSA.RSA_pub object.

load_pub_key requires a file name, not the contents of the file.
So use rsa = M2Crypto.RSA.load_pub_key('my_key.public.pem') and leave
the open line out.

      plaintext = 4545479545655576767767686688782344

That's not text, it is a number. rsa.public_encrypt will not accept a
number. So you would have to use 
      plaintext = "4545479545655576767767686688782344"
or convert the number to a byte array.

      msg = rsa.public_encrypt(plaintext,RSA.pkcs1_padding)
      print msg;
      encrypt()

The above line should be shifted to the left. It is not part of the
function otherwise you get an endless recursion.
And to answer another question from stackoverflow.com: RSA.pkcs1_padding
is a good parameter, if the decryption side will also use it.

See also my posting on the subject `RSA cryptography between Python and Java'.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list