可变int键多次用作XOR操作中的一个输入后,莫名其妙地改变



我正在尝试使用输入键加密file_1.txt并将结果输出到file_2.txt。教授指定该文件必须一次以100个字节读取。

int main(int argc, char *argv[]){
int key;
key = atoi(argv[1]);
FILE *file_pointer;
file_pointer = fopen(argv[2], "rb");
char buffer[100];
char output[sizeof(int)][100];
int output_counter = 0;
int read_counter;
int read_elements;
int buffer_reset_counter;
for(buffer_reset_counter = 0; buffer_reset_counter < 100; buffer_reset_counter++){
    buffer[buffer_reset_counter] = 0;
    }
while(read_elements = fread(buffer, 1, 100, file_pointer) > 0){
    read_counter = 0;
    while(read_counter < 100){
        printf("xor'ing %d and %dn", key, buffer[read_counter]);
        output[output_counter][read_counter] = buffer[read_counter] ^ key;
        read_counter = read_counter + 1;
        }
    output_counter = output_counter + 1;
    for(buffer_reset_counter = 0; buffer_reset_counter < 100; buffer_reset_counter++){
        buffer[buffer_reset_counter] = 0;
        }
}
fclose(file_pointer);
file_pointer = fopen(argv[3], "wb");
int write_counter = 0;
while(write_counter < output_counter){
    fwrite(output[write_counter], 1, 100, file_pointer);
    write_counter = write_counter + 1;
    }
}

file_1.txt是字符串"test file for testingn"重复100次。

印刷品的输出是前几百张印刷品的预期,但是钥匙更改了:

xor'ing 111 and 115
xor'ing 111 and 116
xor'ing 111 and 105
xor'ing 111 and 110
xor'ing 111 and 103
xor'ing 111 and 10
xor'ing 111 and 116
xor'ing 111 and 101
xor'ing 111 and 115
xor'ing 111 and 116
xor'ing 111 and 32
xor'ing 111 and 102
xor'ing 111 and 105
xor'ing 111 and 108
xor'ing 111 and 101
xor'ing 111 and 32
xor'ing 111 and 102
xor'ing 111 and 111
xor'ing 111 and 114
xor'ing 111 and 32
xor'ing 111 and 116
xor'ing 111 and 101
xor'ing 111 and 115
xor'ing 111 and 116
xor'ing 111 and 105
xor'ing 6 and 110
xor'ing 26630 and 103
xor'ing 6383622 and 10
xor'ing 207710214 and 116
xor'ing 207710214 and 101
xor'ing 207710214 and 115
xor'ing 207710214 and 116
xor'ing 207710214 and 32
xor'ing 207710214 and 102
xor'ing 207710214 and 105
xor'ing 207710214 and 108
xor'ing 207710214 and 101
Segmentation fault (core dumped)

我不知道钥匙如何变化。如果相关,则printf("%d", sizeof(int));输出4。

早些时候,我提交了一个问题(stackoverflow.com/q/477732691/905902),涉及垃圾进入缓冲区阵列,因为它在使用fread()之前没有初始化。这次的问题是键正在意外改变。

在语句中:

output[output_counter][read_counter] = buffer[read_counter] ^ key;

output_counter如果循环运行超过四次,即文件中有400个字节(我认为),则可以大于sizeof(int)。发生这种情况时,Xor'ing操作覆盖了堆栈,该堆栈写入key的存储空间。

更高级别,您确实想学习使用valgrind或Clang的地址消毒剂之类的工具,因为他们会很快找到此类问题。

最新更新