在 c 中制作简单的 XOR 密码器时出错

Error whilst making a simple XOR crypter in c

没有编译错误只是功能性问题

我试图用 c 语言制作一个简单的 XOR 密码器。我发现加密部分不是问题,因为当 XOR 函数在同一个字符串上使用两次时,它 returns 就是我发回的确切字符串。因此,我认为问题不在于加密部分,我相信写入文件时会出现问题。

函数错误在

int xorFile (char *infile, char *outfile) {
    FILE *in,
         *out;
    long lSize;
    char *buffer;

    in = fopen ( infile , "rb" );
    out = fopen(outfile, "wb");

    if( !in ) perror(infile),exit(1);

    fseek( in , 0L , SEEK_END);
    lSize = ftell( in );
    rewind( in );

    /* allocate memory for entire content */
    buffer = (char*)calloc( 1, lSize+1 );
    if( !buffer ) fclose(in),fputs("memory alloc fails",stderr),exit(1);

    /* copy the file into the buffer */
    if( 1!=fread( buffer , lSize, 1 , in) )
      fclose(in),free(buffer),fputs("entire read fails",stderr),exit(1);

    /* do your work here, buffer is a string contains the whole text */
    int i;
    for(i=0;buffer[i]!='[=10=]';i++) {
        fputc(buffer[i] ^ XOR_KEY,out);
    }
    fclose(in);
    free(buffer);
    fclose(out);
    return 0;

}

我认为导致错误的原因

int i;
for(i=0;buffer[i]!='[=11=]';i++) {
    fputc(buffer[i] ^ XOR_KEY,out);
}

完整节目

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>

#define XOR_KEY 0x6F

int xorFile (char *infile, char *outfile) {
    FILE *in,
         *out;
    long lSize;
    char *buffer;

    in = fopen ( infile , "rb" );
    out = fopen(outfile, "wb");

    if( !in ) perror("blah.txt"),exit(1);

    fseek( in , 0L , SEEK_END);
    lSize = ftell( in );
    rewind( in );

    /* allocate memory for entire content */
    buffer = (char*)calloc( 1, lSize+1 );
    if( !buffer ) fclose(in),fputs("memory alloc fails",stderr),exit(1);

    /* copy the file into the buffer */
    if( 1!=fread( buffer , lSize, 1 , in) )
      fclose(in),free(buffer),fputs("entire read fails",stderr),exit(1);

    /* do your work here, buffer is a string contains the whole text */
    int i;
    for(i=0;buffer[i]!='[=12=]';i++) {
        fputc(buffer[i] ^ XOR_KEY,out);
    }
    fclose(in);
    free(buffer);
    fclose(out);
    return 0;

}

int main (int argc, char *argv[]) {
    if (argc <= 2) {

      fprintf (stderr, "Usage: %s [IN FILE] [OUT FILE]\n" , argv[0]) ;

      exit (1);
    }

    xorFile (argv[1], argv[2]) ;
}

测试原因

附加信息 当我加密源文件的副本并将其解密时,剩下的就是 #include <std

buffer[i] ^= XOR_KEY;
fputc(buffer[i] ^ XOR_KEY,out);

首先,程序查看 buffer[i] 中的字符,对其进行异或,并将异或后的字符存储回 buffer[i]

然后,它查看 buffer[i] 中的字符(现在已异或),再次对其进行异或,并将 that 写入 out

所以写入 out 的字符已经异或两次 - 所以它只是原始字符。

您遇到的问题是由您的循环过早退出引起的。下面的测试一遇到空字节就会停止:

for(i=0;buffer[i]!='[=10=]';i++)

要加密整个文件,这需要更改为:

for(i=0;i<lSize;i++)

这不仅是非文本文件的问题,也是解密的问题,因为加密过程将为与您的 XOR_KEY 匹配的任何字符引入零字节。例如,如果您的 XOR_KEY 是 0x69,这是一个 ascii 'i',您的加密文件将包含一个零字节来代替每个 'i'。解密时,它会在第一个这样的字符处切断文件,这解释了您所看到的内容。这将纠正这一点。