Reputation: 442
I have implemented TEA in C++. Following is the code:
#include <stdio.h>
#include <iostream>
#include <iostream>
using namespace std;
int main()
{
unsigned long y=24,z=32, sum=0,
delta=0x9e3779b9, n=16 ;
int k[4] = { 0x28, 0xc0, 0x20, 0xd0 };
unsigned long v[2] = {0,0};
cout<<"original y is "<< y<<". original z is "<<z<<endl;
while (n-->0)
{
sum += delta ;
y += ((z<<4)+k[0]) ^ (z+sum) ^ ((z>>5)+k[1]) ;
z += ((y<<4)+k[2]) ^ (y+sum) ^ ((y>>5)+k[3]) ;
}
v[0]=y ; v[1]=z ;
cout<<"encrypted y is "<< v[0]<<". encrypted z is "<<v[1]<<endl;
n=16;
y=v[0];
z=v[1];
delta=0x9e3779b9 ;
sum=delta<<5 ;
/* start cycle */
while (n-->0)
{
z-= ((y<<4)+k[2]) ^ (y+sum) ^ ((y>>5)+k[3]) ;
y-= ((z<<4)+k[0]) ^ (z+sum) ^ ((z>>5)+k[1]) ;
sum-=delta ;
}
v[0]=y ; v[1]=z ;
cout<<"decrypted y is "<< v[0]<<". decrypted z is "<<v[1]<<endl;
getchar();
return 0;
}
But in the end, the results are not same i.e. the decrypted value is different than the original inputs (y
and z
).
Please point out the mistake which I am unable to see.
Upvotes: 0
Views: 550
Reputation: 108820
sum = n * delta
You compute sum
as delta << 5
which corresponds to delta * 32
. That works for the default value of n = 32
but you reduced n
to 16
without fixing the computation of sum
. Replace sum=delta<<5;
by sum = delta * n
.
Also note that reducing the number of rounds weakens the resistance against cryptoanalysis.
Upvotes: 3
Reputation: 4850
You set n
to 16, while the example implementation on Wikipedia runs the loop 32 times.
If I change n
to 32 in your code, it works: See it live on Coliru
Upvotes: 4