Is there a simple way to encrypt/decrypt a string with a key?

Something like:

key = '1234'
string =  'hello world'
encrypted_string = encrypt(key, string)
decrypt(key, encrypted_string)

I couldn’t find anything simple to do that.

pyDES is a DES and Triple-DES implementation completely written in python.

Here’s a simple and portable example that should be secure enough for basic string encryption needs. Just put the pyDES module in the same folder as your program and try it out:

Sender’s computer

>>> from pyDES import *  # pyDes if installed from pip
>>> ciphertext = triple_des('a 16 or 24 byte password').encrypt("secret message", padmode=2)  #plain-text usually needs padding, but padmode = 2 handles that automatically
>>> ciphertext
')\xd8\xbfFn#EY\xcbiH\xfa\x18\xb4\xf7\xa2'  #gibberish

Recipient’s computer

>>> from pyDES import *
>>> plain_text = triple_des('a 16 or 24 byte password').decrypt(')\xd8\xbfFn#EY\xcbiH\xfa\x18\xb4\xf7\xa2', padmode=2)
>>> plain_text
"secret message"

You might get an error in Python3 from code of Recipient’s computer

ValueError: pyDes can only work with encoded strings, not Unicode.

from pyDes import *

a = b')\xd8\xbfFn#EY\xcbiH\xfa\x18\xb4\xf7\xa2'
plain_text = triple_des('a 16 or 24 byte password').decrypt(a, padmode=2)
print(plain_text)

Just Add b at the beginning of the encrypted text. For clearer code, assign it to a new variable (in this case, it’s a, and decrypt a in a normal way).

http://www.dlitz.net/software/pycrypto/ should do what you want.

Taken from their docs page.

>>> from Crypto.Cipher import DES
>>> obj=DES.new('abcdefgh', DES.MODE_ECB)
>>> plain="Guido van Rossum is a space alien."
>>> len(plain)
34
>>> obj.encrypt(plain)
Traceback (innermost last):
  File "<stdin>", line 1, in ?
ValueError: Strings for DES must be a multiple of 8 in length
>>> ciph=obj.encrypt(plain+'XXXXXX')
>>> ciph
'\021,\343Nq\214DY\337T\342pA\372\255\311s\210\363,\300j\330\250\312\347\342I\3215w\03561\303dgb/\006'
>>> obj.decrypt(ciph)
'Guido van Rossum is a space alien.XXXXXX'

for python 2, you should use keyczar http://www.keyczar.org/

for python 3, until keyczar is available, i have written simple-crypt http://pypi.python.org/pypi/simple-crypt

i’m answering this two years late as things have changed since the question was asked.

note that the previous answers to this question use weak ciphers (by today’s standards) and don’t have any key strengthening. the two recommendations here are likely more secure.

To expand on dsamersoff’s answer.. This is simple and insecure, but for certain tasks may be useful. here’s some code:

import crypt
import getpass
import os.path

def auth_func():
    return (raw_input('Username:'), getpass.getpass('Password:'))

def xor(a,b):
    assert len(b) >= len(a)
    return "".join([chr( ord(a[i]) ^ ord(b[i])) for i in range(len(a))])

# create a new credentials file if needed
if not os.path.exists('cred'):
    with open('cred', 'w') as f:
        user, pwd =  auth_func()
        f.write ("{}\n".format(user))               
        f.write ("{}\n".format(xor(pwd, crypt.crypt('secret', 'words'))))
        f.close()

# read credentials and print user/password
with open('cred', 'r') as f:
    user, pwd = f.read().split('\n')[:2]
    print user
    print xor(pwd, crypt.crypt('secret', 'words'))

The simplest and fastest way to encrypt short text fragment with preshaired key is use one of cryptohash functions (md5, sha etc).

i.e. calc md5 of your key, then xor your string fragment with this md5 hash. if you need to encode text fragmen longer than length of md5 – do md5(md5 hash) and encrypt next fragment.

Security of this solution is worse than with 3-DES but enough in average case (i.e. to store not very secure password in config file) and it doesn’t requre anything besides base python distro.

If you need better security – look for one of AES, Blowfish etc implementation, but to really benefit AES you need to do some additional work to mix your data with random ones.