Python TEA implementation

Posted by Gaks on Stack Overflow See other posts from Stack Overflow or by Gaks
Published on 2010-04-06T21:10:29Z Indexed on 2010/04/06 21:13 UTC
Read the original article Hit count: 470

Filed under:
|
|
|

Anybody knows proper python implementation of TEA (Tiny Encryption Algorithm)? I tried the one I've found here: http://sysadminco.com/code/python-tea/ - but it does not seem to work properly.

It returns different results than other implementations in C or Java. I guess it's caused by completely different data types in python (or no data types in fact).

Here's the code and an example:

def encipher(v, k):
    y=v[0];z=v[1];sum=0;delta=0x9E3779B9;n=32
    w=[0,0]
    while(n>0):
        y += (z << 4 ^ z >> 5) + z ^ sum + k[sum & 3]
        y &= 4294967295L # maxsize of 32-bit integer
        sum += delta
        z += (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3]
        z &= 4294967295L
        n -= 1

    w[0]=y; w[1]=z
    return w

def decipher(v, k):
    y=v[0]
    z=v[1]
    sum=0xC6EF3720
    delta=0x9E3779B9
    n=32
    w=[0,0]
    # sum = delta<<5, in general sum = delta * n

    while(n>0):
        z -= (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3]
        z &= 4294967295L
        sum -= delta
        y -= (z << 4 ^ z >> 5) + z ^ sum + k[sum&3]
        y &= 4294967295L
        n -= 1

    w[0]=y; w[1]=z
    return w

Python example:

>>> import tea
>>> key = [0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805]
>>> v = [0xe15034c8, 0x260fd6d5]
>>> res = tea.encipher(v, key)
>>> "%X %X" % (res[0], res[1])
**'70D16811 F935148F'**

C example:

#include <unistd.h>
#include <stdio.h>

void encipher(unsigned long *const v,unsigned long *const w,
   const unsigned long *const k)
{
   register unsigned long       y=v[0],z=v[1],sum=0,delta=0x9E3779B9,
                                a=k[0],b=k[1],c=k[2],d=k[3],n=32;

   while(n-->0)
      {
      sum += delta;
      y += (z << 4)+a ^ z+sum ^ (z >> 5)+b;
      z += (y << 4)+c ^ y+sum ^ (y >> 5)+d;
      }

   w[0]=y; w[1]=z;
}

int main()
{
        unsigned long v[] = {0xe15034c8, 0x260fd6d5};
        unsigned long key[] = {0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805};

        unsigned long res[2];

        encipher(v, res, key);

        printf("%X %X\n", res[0], res[1]);

        return 0;
}

$ ./tea
**D6942D68 6F87870D**

Please note, that both examples were run with the same input data (v and key), but results were different. I'm pretty sure C implementation is correct - it comes from a site referenced by wikipedia (I couldn't post a link to it because I don't have enough reputation points yet - some antispam thing)

© Stack Overflow or respective owner

Related posts about python

Related posts about tea