C RC4超级奇怪的行为

时间:2015-04-14 23:25:18

标签: c encryption rc4-cipher stream-cipher

所以我在纯C中找到了RC4的实现,我在我的网站上使用了它。除非我输入6个字符的字符串,否则它工作得非常好。然后我得到内部错误页面。弄清楚只有这个长度会导致问题。

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) {
for (i = 0; i < 256; i++)
    S[i] = i;

for (i = j = 0; i < 256; i++) {
    j = (j + key[i % key_length] + S[i]) & 255;
    swap(S, i, j);
}

i = j = 0;
}

/* PRGA */
unsigned char rc4_output() {
i = (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;
    for (y = 0; y < strlen((char*)vector[1]); y++)
       ptr += sprintf(ptr,"%02X",vector[1][y] ^ rc4_output());
*(ptr + 1) = '\0';
return out;
}

2,主要

#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))); 

非常欢迎任何建议或想法。只想知道函数本身是坏的还是我的C代码的其余部分。 谢谢!

1 个答案:

答案 0 :(得分:2)

此行存在问题:

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

您忘记在字符串末尾为终止'\0'添加额外字节。所以在下一行:

strcpy(dup,text);

您在数组dup中提交越界访问,导致未定义的行为。