【问题标题】:How to encrypt a file buffer with XOR?如何使用 XOR 加密文件缓冲区?
【发布时间】:2021-06-23 13:51:27
【问题描述】:

我正在尝试读入一个文件以缓冲并使用我的 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。

我做错了什么?

【问题讨论】:

  • 如果lSize 是正数,buf &lt; buf + lSize - 1 永远不会是假的,出于同样的原因,数学不等式 x x + h 为正时,h 始终为真。你想要buf &lt; buffer + lSize 或只是index &lt; lSize
  • 在调用 fopen 之后,您可以简单地调用 fstat 来获取文件大小,而不是使用 fseek + ftell 来获取文件大小,然后调用 rewind 来获取文件大小。跨度>
  • 您的代码失败,因为您的变量命名很愚蠢。如果您将 buf 重命名为 current_position 或类似名称,您会发现它更容易。

标签: c segmentation-fault


【解决方案1】:

这个循环:

while (buf < buf + lSize - 1) {

永远不会结束。

也许你的意思

while (buf < buffer + lSize) {

?

附: -1 表示它不加密最后一个字符。

【讨论】:

  • 此外,segfault 正在发生,因为循环永远不会结束,buf 最终会在分配数据结束后递增。
【解决方案2】:

循环永远不会结束。

我认为循环需要一种更好的方法来仅迭代 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
    } 
    // ...

【讨论】:

    【解决方案3】:

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

    而不是这个:

    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];
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-13
      • 1970-01-01
      • 2014-03-10
      • 2015-06-12
      • 1970-01-01
      • 2019-03-11
      • 2018-11-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多