PDA

View Full Version : Error in C: Trying to implement Tea encryption


robertseadog
2008.03.28, 02:58 PM
Hi,
I am trying the TEA encryption algorythm, but It wont behave. I suspect the data im sending it is wrong, or somehow not formatted correctly. Either way, I get a "EXC_BAD_ACCESS" pointing to my FPTea C function.. Im notoriously bad at debugging (mostly due to me not knowing assembly, or how functions are executed :p), and not a very good C writer so I appologize if this is a trivial error.

NSString *FPCocoaTea (NSString *string, NSString *key, FPTeaOption option)
{
long *data;
[[string dataUsingEncoding: NSUTF8StringEncoding] getBytes: &data];
long *dataKey;
[[key dataUsingEncoding: NSUTF8StringEncoding] getBytes: &dataKey];

long *cryptData = FPTea (data, dataKey, option);
return [[NSString alloc] initWithBytes: cryptData
length: sizeof(cryptData) encoding: NSUTF8StringEncoding];
}

long *FPTea (long *v, long *k, FPTeaOption option)
{
// This next line sends a "EXC_BAD_ACCESS"
unsigned long v0=v[0], v1=v[1], sum=0;
unsigned long delta=0x9e3779b9;
unsigned long k0=k[0], k1=k[1], k2=k[2], k3=k[3];
if (option == FPTeaEncrypt)
{
// encrypt
for (unsigned long i=0; i < 32; i++) {
sum += delta;
v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
}
v[0]=v0; v[1]=v1;
return v;
}

// Decrypt
sum = 0xC6EF3720;
for (unsigned long i=0; i<32; i++)
{
v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
sum -= delta;
} v[0]=v0; v[1]=v1;
return v;
}

Thanks in advance!

Derek Kuhl
2008.03.28, 03:49 PM
You're messing up your references and values. Need to freshen up on some CS 101:
http://www.gamedev.net/reference/articles/article1697.asp#ch2

OneSadCookie
2008.03.28, 05:11 PM
[[string dataUsingEncoding: NSUTF8StringEncoding] getBytes: &data];


This is very wrong. You need to learn how memory and parameter passing work. For the mean time, const uint32_t *data = [[string dataUsingEncoding:NSUTF8StringEncoding] bytes]; is probably what you're after. You definitely don't want to be using "long".