[Python-au] python number handling - tiny encryption algorithm

John Machin sjmachin at lexicon.net
Wed Nov 30 01:39:01 CET 2005


Kinsley Turner wrote:
> 
> Hey-ho,
> 
> I'm getting a bit out of my depth porting the 'tiny encryption algorithm' 
> from C to python.
> 
> Ref: 
> http://en.wikipedia.org/wiki/Tiny_Encryption_Algorithm
> http://www.simonshepherd.supanet.com/source.htm#new_ansi
> 
> Specifically I don;t know how to handle a C-long block and perform the
> mathmatical manipulations in python syntax.  I played with pack and unpack
> (from struct module) but that didn't seem to buy me anything.
> 
> In my version, I end up with hugely long integers, which have obviously
> not be constrained into the 4-byte unsigned longs that TEA is expecting.
> 
> This is the C function:
> 
> /* v is 64-bits input, w is 64-bits output, k is the 128-bit key */
> void decipher(const unsigned long *const v,unsigned long *const w, const 
> unsigned long * const k)
> {
>    register unsigned long 
> y=v[0],z=v[1],sum=0xC6EF3720,delta=0x9E3779B9,n=32;
> 
>    while(n-->0)
>   {
>       z -= (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3];
>       sum -= delta;
>       y -= (z << 4 ^ z >> 5) + z ^ sum + k[sum&3];
>   }
>    w[0]=y; w[1]=z;
> }
> 
> 
> Which gives me a (broken) python version:
> 
> def  teaDecipher(input,key):
>     y = input[0]
>     z = input[1]
>     n = 32
>     sum = 0xC6EF3720
>     delta=0x9E3779B9 
> 
>     while (n > 0):
>         n -= 1
>         z -= (y << 4 ^ y >> 5) + y ^ sum + key[sum>>11 & 3];
>         sum -= delta;
>         y -= (z << 4 ^ z >> 5) + z ^ sum + key[sum&3];
>       return y,z


Try this:

return y & 0xFFFFFFFF, z & 0xFFFFFFFF

If that doesn't work, you'll have to analyse the algorithm to
see exactly where the overflow of 32 bits is giving you grief,
and insert more instances of & 0xFFFFFFFF as appropriate.


> 
> That seems to return hugely-long integers (around 30? digits),
Seems or does?

  whereas I'd
> expect
> them to max-out at 2^32.

On what are you basing that expectation? E.g. Read the manual on subject 
of the << operator.

[snip]
> 
> 
> Anyway, that's about it.
> Any help much appreciated.
> 
> 
> thanks,
> -kt
> 
> (non-removable disclaimer below... *sigh*)
[snip]
Post to comp.lang.python via a news client -- two benefits: wider 
audience than python-au and no disclaimer.



More information about the python-au mailing list