Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy to use Python encryption library/wrapper?

I want to encrypt an arbitrary-length string with a password in Python. I would prefer not to deal with padding, key generation and IVs as I honestly don't know that much about cryptography yet and I'd like to avoid messing up. I'd also prefer using a well-known cypher as AES.

My ideal library (let's call it MagicCrypt) would work like this:

from MagicCrypt import AES
p = "plaintext"
k = "password"
crypt = AES(k)
c = crypt.encrypt(p)
p == crypt.decrypt(c) # True

I've checked PyCrypto, m2crypto, pycryptopp, GPGme and keyczar. Neither of them seem to offer this really easy to use mode. keyczar comes closest, but for some reason wants to use a keyset saved in a file-like object or something similar.

As far as I know I'll have to resort to calling mcrypt with Popen, which does offer a mode that works exactly like this - part of the reason I'm guessing there's really no technical reason for this not to exist.

Do you know of an easy to use, secure, crypto library for Python? If not, what's the easiest (yet secure) way of using any of the already mentioned libraries?

like image 472
Eduardo Ivanec Avatar asked Sep 03 '11 23:09

Eduardo Ivanec


3 Answers

Have a look at http://code.activestate.com/recipes/576980/

EDIT

Modified to use a user-defined password of arbitrary length. Requires pyCrypto. Thrown together in minutes without a test in sight.

EDIT 2

Updated version at https://gist.github.com/1192059

like image 41
Rob Cowie Avatar answered Oct 17 '22 23:10

Rob Cowie


you list m2crypto, but did you see m2secret? the example at http://www.heikkitoivonen.net/m2secret/ seems pretty much exactly what you want.

disclaimer: i haven't used it and it's listed on pypi as alpha quality http://pypi.python.org/pypi/m2secret/0.1.1

update - some time after answering here i wrote simple-crypt which is a simple wrapper for pycrypto. it does aes encryption for python 2.7 and 3 and is similar to Rob's answer below but also includes PBKDF2 to generate a more secure key.

like image 106
andrew cooke Avatar answered Oct 18 '22 00:10

andrew cooke


I think these two packages are currently best suited: wheezy.security and SimpleAES. Both have such simple usage documented.

like image 1
Bentley4 Avatar answered Oct 18 '22 00:10

Bentley4