如何使用 XOR 加密文件缓冲区?

How to encrypt a file buffer with XOR?

我正在尝试读入文件以使用我的 XOR 加密密钥缓冲和加密每个字节。我已经像下面这样实现了它,但由于某种原因它会出现段错误。

int main(char argc, char *argv[]) {
    fileIn = fopen("data.bin", "rb"); // open input file (binary)
    if (fileIn==NULL) {
        puts("Error opening input file");
        exit (1);
    }

    // obtain file size.
    fseek(fileIn , 0 , SEEK_END);
    lSize = ftell(fileIn);
    rewind(fileIn);
    printf("Filesize: %d bytes.\n", lSize);

    // allocate memory to contain the whole file.
    buffer = (unsigned char*) malloc (lSize);
    if (buffer == NULL) {
        puts("malloc for input file buffer failed (not enough memory?)");
        exit (2);
    }

    // copy the file into the buffer.
    fread (buffer, 1, lSize, fileIn);

    char *enckey = "enckey123";

    unsigned char *buf = buffer;
    int index = 0;
    while (buf < buf + lSize - 1) {
        *buf++ ^= enckey[index++ % 9]; // 9 is the length of the encryption key
    }
}

*buf++ ^= enckey[index++ % 9];这样的段错误。

用gdb调试,我可以看到lSize类似于2000,但是index的值为128585。

我做错了什么?

这个循环:

while (buf < buf + lSize - 1) {

永远不会完成。

也许你的意思是

while (buf < buffer + lSize) {

?

P.S。 -1 表示它不加密最后一个字符。

循环永远不会结束。

我认为循环需要一种更好的方法来迭代仅 lSize 个字节。 我通过将最后几行更改为:

    // ...
    // Calculate where to stop the iteration
    const unsigned char *buf_end = buf + lSize - 1;
    // Walk over lSize bytes in the buffer
    while (buf < buf_end) {
        *buf++ ^= enckey[index++ % 9]; // 9 is the length of the encryption key
    } 
    // ...

与其他答案类似,但我认为这更具可读性:

而不是这个:

while (buf < buf + lSize - 1) {
    *buf++ ^= enckey[index++ % 9]; // 9 is the length of the encryption key
}

这个:

for (size_t i = 0; i < lSize; i++) {
   buf[i] = enckey[i % 9];
}