Simple encryption proposal. Comments ?

Paul Rubin phr-n2002b at NOSPAMnightsong.com
Thu Jan 2 07:21:00 EST 2003


richie at entrian.com (Richie Hindle) writes:
> Is your base52 code (or *any* such code) available anywhere?  Googling for
> "python base52" didn't turn anything up.

Here's one I threw together:

# ==== base52.py =======================================================

from array import array
import string

_letters = map(ord, string.ascii_letters)
_inv_letters = [0]*256
for _i in xrange(len(_letters)):
    _inv_letters[_letters[_i]] = _i

def base52_encode(str):
    def convert(a):
        for c in a:
            y.append(_letters[c / (52*52)])
            y.append(_letters[(c / 52) % 52])
            y.append(_letters[c % 52])

    y = array('B')

    if len(str) % 2 == 0:
        last, x = '', array('H', str)
    else:
        last, x = str[-1], array('H', str[:-1])

    convert(x)

    if last:
        convert((ord(last) + 65536,))

    return y.tostring()

def base52_decode(str):
    if len(str) % 3:
        raise ValueError
    x = array('B', str)
    y = array('B')
    for i in xrange(0, len(x), 3):
        k1, k2, k3 = [_inv_letters[x[i+j]] for j in range(3)]
        a = k1*52*52 + k2*52 + k3
        if a < 65536:
            y.append(a%256)
            y.append(a/256)
        elif a < 65536 + 256:
            y.append(a-65536)
            break
        else:
            raise ValueError

    return y.tostring()    

_be = base52_encode
_bd = base52_decode

def _test1():
    st = 'abcdefg'
    
    for i in range(len(st)):
        s = st[:i]
        print s, _be(s), _bd(_be(s))

def _test2():
    from secrand import secrand

    for i in range(100):
        n = secrand.getlong(1)
        s = secrand.getbytes(n)
        assert _bd(_be(s)) == s

    try:
        # test the overflow check
        _bd('zzz')
    except ValueError:
        pass
    else:
        print 'oops'

_test1()
# _test2()    # depends on secrand.py module, not included




More information about the Python-list mailing list