lightweight encryption of text file

Nobody nobody at
Sun Jan 10 09:33:42 CET 2010

On Fri, 08 Jan 2010 20:14:51 +0100, Daniel Fetchinson wrote:

> I have a plain text file which I would like to protect in a very
> simple minded, yet for my purposes sufficient, way. I'd like to
> encrypt/convert it into a binary file in such a way that possession of
> a password allows anyone to convert it back into the original text
> file while not possessing the password one would only see the
> following with the standard linux utility 'file':

> What would be the simplest way to achieve this using preferably stock
> python without 3rd party modules? If a not too complex 3rd party
> module made it really simple that would be acceptable too.

RC4 (aka ArcFour) is quite trivial to implement, and better than inventing
your own cipher or using a Vignere:

import itertools

class arcfour:
    def __init__(self, key):
	self.s = range(256)
	self.schedule(map(ord, key))
	self.pad = self.prng()

    def swap(self, i, j):
	self.s[i], self.s[j] = self.s[j], self.s[i]

    def schedule(self, key):
	j = 0
	for i, c in zip(xrange(256), itertools.cycle(key)):
	    j = (j + self.s[i] + c) % 256
	    self.swap(i, j)

    def prng(self):
	i = j = 0
	while True:
	    i = (i + 1) % 256
	    j = (j + self.s[i]) % 256
	    self.swap(i, j)
	    yield self.s[(self.s[i] + self.s[j]) % 256]

    def crypt(self, string):
	chars = (chr(c ^ r) for c, r in zip(map(ord, string), self.pad))
	return ''.join(chars)

I suggest that you don't use the password itself as the key, unless you're
sure that a low-entropy string won't be used. Instead, create an SHA hash
(see the sha and hashlib modules) of the password and use that.

More information about the Python-list mailing list