views:

470

answers:

3

I'm making an encryption function in Python and I want to encrypt a random number using a public key.

I wish to know that if I use Crypto package (Crypto.publicKey.pubkey) than how can I use the method like...

def encrypt(self,plaintext,k)

Here the k is itself a random number, is this mean the key. Can somebody help me with somewhat related?

A: 

hi you can try Pycrypto.

ghostdog74
+2  A: 

Are you trying to encrypt a session/message key for symmetric encryption using the public key of the recipient? It might be more straightforward to use, say, SSH or TLS in those cases.

Back to your question:

Me Too Crypto (M2Crypto) is a nice wrapper around openssl.

First, you need to get the public key of the recipient:

recip = M2Crypto.RSA.load_pub_key(open('recipient_public_key.pem','rb').read())

Now you can encrypt your message:

plaintext = random_integer_you_want_to_encrypt
msg = recip.public_encrypt(plaintext,RSA.pkcs1_padding)

Now only someone with the private key of the recipient can decrypt it.

Will
A: 

The value k that you pass to encrypt is not part of the key. k is a random value that is used to randomize the encryption. It should be a different random number every time you encrypt a message.

Unfortunately, depending on what public key algorithm you use this k needs to satisfy more or less strict conditions. I.e., your encryption may be completely insecure if k does not contain enough entropy. This makes using pycrypto difficult, because you need to know more about the cryptosystem you use than the developer of the library. In my opinion this is a serious flaw of pycrypto and I'd recommend that you use a more high level crypto library that doesn't require that you know any such details. (i.e. something like M2Crypto)

Accipitridae