encryption - C RC4 super weird behavior -


so found implementation of rc4 in pure c, using on website. working super except when input 6 characters string. internal error page. figured out length causes problem.

1.crypt.c

unsigned char s[256]; unsigned int i, j; void swap(unsigned char *s, unsigned int i, unsigned int j) { unsigned char temp = s[i]; s[i] = s[j]; s[j] = temp; }  /* ksa */ void rc4_init(unsigned char *key, unsigned int key_length) { (i = 0; < 256; i++)     s[i] = i;  (i = j = 0; < 256; i++) {     j = (j + key[i % key_length] + s[i]) & 255;     swap(s, i, j); }  = j = 0; }  /* prga */ unsigned char rc4_output() { = (i + 1) & 255; j = (j + s[i]) & 255;  swap(s, i, j);  return s[(s[i] + s[j]) & 255]; }  char *rc4_e(char *text, size_t text_length) { char *dup=(char *)malloc(text_length * sizeof(char)); strcpy(dup,text); unsigned char *vector[2] = {"key", dup};      int y;     rc4_init(vector[0], strlen((char*)vector[0])); char *out=(char *)malloc(text_length * sizeof(char) ); char *ptr=out;     (y = 0; y < strlen((char*)vector[1]); y++)        ptr += sprintf(ptr,"%02x",vector[1][y] ^ rc4_output()); *(ptr + 1) = '\0'; return out; } 

2.main

#define size 1000 char* pass=(char*)malloc(size * sizeof(char)); char *rc4_pass=(char*)malloc(getsize(pass) * sizeof(char));   strcpy(rc4_pass,rc4_e(pass,sizeof(pass)));  

any advice or thoughts extremely welcome. want know whether function bad or rest of c code. thank!

there problem line:

char *dup=(char *)malloc(text_length * sizeof(char)); 

you forgot add byte terminating '\0' @ end of string. @ next line:

strcpy(dup,text); 

you're committing out-of-bounds access in array dup, causing undefined behaviour.


Comments

Popular posts from this blog

css - SVG using textPath a symbol not rendering in Firefox -

Java 8 + Maven Javadoc plugin: Error fetching URL -

order - Notification for user in user account opencart -