Simple encryption proposal. Comments ?

Thomas Weholt 2002 at weholt.org
Sun Dec 29 19:53:56 EST 2002


Hi,

( This is sort of a follow-up to my earlier question about encrypting
cookies in HTTP-requests, so if you have any encryption schemes suitable for
that purpose, let me know )

I've come up with a very simple One-Time-Pad encryption scheme, inspired by
the book "Applied Cryptography" by Bruce Schneier, page 15, Chapter 1.
It takes each letter in the alphabet and swaps it with a different random
letter from a different set of letters, building a dictionary of
letter->swap-letter
to base encryption on. I didn't excactly read the text very good and did the
coding after memory so there might be huge logic wholes in the thing.

Anyway, if somebody has any comments on this way of encryption, tips for
improvements etc. I'd be happy to hear it. Code follows:

import string, whrandom, cPickle, os

class PadEncryption:
    "Defines a class for pad-encryption"

    def __init__(self, root):
        self.root = root
        self.UPPER = list(string.uppercase+'0123456789')
        self.LOWER = list(string.lowercase+'0123456789')
        self.pad_in = {}
        self.pad_out = {}
        self.loadPad()

    def loadPad(self):
        if os.path.exists(os.path.join(self.root, 'pad.dat')):
            try:
                self.pad_in, self.pad_out =
cPickle.loads(open(os.path.join(self.root, 'pad.dat')).read())
            except (IOError, OSError, EOFError), e:
                self.generatePad()
        else:
            self.generatePad()

    def generatePad(self):
        self.pad_in = {}
        self.pad_out = {}

        while self.UPPER:
            c = self.UPPER.pop()
            d = self.LOWER[whrandom.randint(0, len(self.LOWER)-1)]
            self.LOWER.remove(d)
            self.pad_in[c.lower()] = d
            self.pad_out[d] = c.lower()

        try:
            open(os.path.join(self.root, 'pad.dat'),
'w').write(cPickle.dumps([self.pad_in, self.pad_out]))
        except (IOError, OSError), e:
            raise "Error saving pad to disk. %s" % e

    def encrypt(self, text):
        result = []
        for c in text:
            result.append(self.pad_in.get(c, c))
        return ''.join(result)

    def decrypt(self, text):
        result = []
        for c in text:
            result.append(self.pad_out.get(c, c))
        return ''.join(result)


if __name__ == '__main__':
    c = PadEncryption('.')
    v = 'thomas'
    s = c.encrypt(v)
    print v, s
    s = c.decrypt(s)
    print v, s

Best regards,
Thomas Weholt





More information about the Python-list mailing list