NO

Author Topic: Code generation bug  (Read 1451 times)

waco

  • Guest
Code generation bug
« on: July 25, 2019, 08:57:18 AM »
Hello.
After executing the function rc4(), the buffer contains garbage. The algorithm itself also works incorrectly.

Code: [Select]
#include <stdio.h>
#include <stdlib.h>


#define swap(type,a,b,c) do{type t=a[b];a[b]=a[c];a[c]=t;}while(0)

unsigned char *rc4(unsigned char *key, unsigned key_size, unsigned char *buf_in, unsigned buf_in_size, unsigned char *buf_out)
{
    unsigned char s[256];
    unsigned i, j, c;

    for (i = 0; i < 256; s[i] = i++);

    for (i = j = 0; i < 256; ++i) {
        j = (j + s[i] + key[i % key_size]) & 0xFF;

        swap(unsigned char, s, i, j);
    }

    i = j = c = 0;

    while (buf_in_size--) {
        i = (i + 1) & 0xFF;
        j = (j + s[i]) & 0xFF;

        swap(unsigned char, s, i, j);

        buf_out[c] = buf_in[c] ^ s[(s[i] + s[j]) & 0xFF];

        c++;
    }

    return buf_out;
}


int entry(void)
{
    unsigned char buf[] = "qwerty";
    unsigned char key[] = "key";

    rc4(key, 3, buf, 6, buf);
   

    for (int i = 0; i < 6; ++i)
    {
        printf("%02X ", buf[i]);
    }

    exit(0);
}

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: Code generation bug
« Reply #1 on: July 25, 2019, 03:13:50 PM »
clang:
Code: [Select]
warning: unsequenced modification and access to 'i' [-Wunsequenced]
    for (i = 0; i < 256; s[i] = i++);
so better to use
Code: [Select]
for (i = 0; i < 256; i++) s[i] = i;
May the source be with you

Offline bitcoin

  • Member
  • *
  • Posts: 179
Re: Code generation bug
« Reply #2 on: July 25, 2019, 04:03:36 PM »
Timo, why you always give an example with Clang? Is this some kind of standard C language?

Offline TimoVJL

  • Global Moderator
  • Member
  • *****
  • Posts: 2091
Re: Code generation bug
« Reply #3 on: July 25, 2019, 04:57:31 PM »
It's verbose and give some additional details, like this time ;)
May the source be with you