problem with using the tea algorithm methods from wiki

i have been trying to call out the tea algorithm from wikipedia. However i keep getting a segmentation fault. May i know what is wrong with my code?
Am i calling it out the wrong way?

below are the snippets

methods taken from wikipedia
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void encrypt (uint32_t* v, uint32_t* k) {
uint32_t v0=v[0], v1=v[1], sum=0, i; /* set up */
uint32_t delta=0x9e3779b9; /* a key schedule constant */
uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */
for (i=0; i < 32; i++) { /* basic cycle start */
sum += delta;
v0 += ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
v1 += ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
} /* end cycle */
cout<<sum<<endl;

v[0]=v0; v[1]=v1;

}

void decrypt (uint32_t* v, uint32_t* k) {
uint32_t v0=v[0], v1=v[1], sum=0xC6EF3720, i; /* set up */
uint32_t delta=0x9e3779b9; /* a key schedule constant */
uint32_t k0=k[0], k1=k[1], k2=k[2], k3=k[3]; /* cache key */
for (i=0; i<32; i++) { /* basic cycle start */
v1 -= ((v0<<4) + k2) ^ (v0 + sum) ^ ((v0>>5) + k3);
v0 -= ((v1<<4) + k0) ^ (v1 + sum) ^ ((v1>>5) + k1);
sum -= delta;
} /* end cycle */
v[0]=v0; v[1]=v1;

}



main method
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int main()
{

    char* userInput;
    int strLen;
    int counter=0;
    vector<int> storeAscii;
    char key[16] = "password";
    char plaintext[24] = "hello123"; 
    char *p;
    char *end = plaintext + sizeof plaintext;
    srand(time(NULL));
    cout<<"5-bit CFB TEA algorithm program"<<endl;
    cout<<"please enter the message to be encrypted :";
    cin>>userInput;


    for(p=plaintext;p<end;p+=2)
    {
        encrypt((uint32_t*)p,(uint32_t*)key);
    }
}


i tried to encrypt a test text and casting it to the uinstd32_t type. However it always gives me a segmentation fault. Hope you guys can advice me on where i went wrong in doing this.

Thanks in advance!
Two things:
1) In line 15 of main you read into an uninitialized char* variable. Use std::string plus std::getline (if you want strings with spaces to be read) for this purpose.

2) encrypt uses and modifies the first two uint32_t which is 8 bytes. As your p in line 18 is a char* you need to move the pointer by 2 * sizeof(uint32_t), not by 2, or declare p as uint32_t in the first place (see info about pointer arithmetic - e.g. here http://www.learncpp.com/cpp-tutorial/68-pointers-arrays-and-pointer-arithmetic/ )
Last edited on
ok thanks man! I solved it, its kind of a silly error.
Thanks for your help
Topic archived. No new replies allowed.