views:

572

answers:

3

I need to take a string in Python and encrypt it using a public key.

Can anyone give me an example or recommendation about how to go about doing this?

+3  A: 

You'll need a Python cryptography library to do this.

Have a look at ezPyCrypto: "As a reaction to some other crypto libraries, which can be painfully complex to understand and use, ezPyCrypto has been designed from the ground up for absolute ease of use, without compromising security."

It has an API:

encString(self, raw)

which looks like what you're after: "High-level func. encrypts an entire string of data, returning the encrypted string as binary."

RichieHindle
+2  A: 

PyMe provides a Python interface to the GPGME library.

You should, in theory, be able to use that to interact with GPG from Python to do whatever encrypting you need to do.

Here's a very simple code sample from the documentation:

This program is not for serious encryption, but for example purposes only!

import sys
from pyme import core, constants

# Set up our input and output buffers.

plain = core.Data('This is my message.')
cipher = core.Data()

# Initialize our context.

c = core.Context()
c.set_armor(1)

# Set up the recipients.

sys.stdout.write("Enter name of your recipient: ")
name = sys.stdin.readline().strip()
c.op_keylist_start(name, 0)
r = c.op_keylist_next()

# Do the encryption.

c.op_encrypt([r], 1, plain, cipher)
cipher.seek(0,0)
print cipher.read()
Mark Biek
A: 

I looked at the ezPyCrypto library that was recommended in another answer. Please don't use this library. It is very incomplete and in some cases incorrect and highly insecure. Public key algorithms have many pitfalls and need to be implemented carefully. For example, RSA message should use a padding scheme such as PKCS #1, OAEP etc to be secure. This library doesn't pad. DSA signatures should use the SHA1 hash function. This library uses the broken MD5 hash and there is even a bigger bug in the random number generation. Hence the DSA implementation is neither standards conform nor secure. ElGamal is also implemented incorrectly.

Following standards does make implementations somewhat more complex. But not following any is not an option. At least not if you care about security.

Accipitridae