将文件与密钥异或

Bas*_*asj 10 command-line pipe encryption cygwin

从 bash 或标准的 linux 命令行工具,如何将文件与密钥进行异或?就像是:

cat my1GBfile | xor my1MB.key > my1GBfile.encrypted
Run Code Online (Sandbox Code Playgroud)

题外话:我知道这个例子的加密很弱,但我只是想知道这是否可以从 bash 或标准的 linux 命令行工具中获得(或者甚至更好:来自 bash 和 cygwin,因为我同时使用 Linux 和 Windows )。

Sat*_*ura 8

bash不能处理 ASCIINUL字符,所以你不会用 shell 函数来做这件事,你需要一个小程序。这几乎可以用任何语言来完成,但用 C 来完成似乎最容易,也许像这样:

#include <stdio.h>                                                                                                              
#include <stdlib.h>

int
main(int argc, char *argv[])
{
    FILE *kf;
    size_t ks, n, i;
    long pos;
    unsigned char *key, *buf;

    if (argc != 2) {
        fprintf (stderr, "Usage: %s <key>\a\n", argv[0]);
        exit(1);
    }
    if ((kf = fopen(argv[1], "rb")) == NULL) {
        perror("fopen");
        exit(1);
    }

    if (fseek(kf, 0L, SEEK_END)) {
        perror("fseek");
        exit(1);
    }
    if ((pos = ftell(kf)) < 0) {
        perror("ftell");
        exit(1);
    }
    ks = (size_t) pos;
    if (fseek(kf, 0L, SEEK_SET)) {
        perror("fseek");
        exit(1);
    }
    if ((key = (unsigned char *) malloc(ks)) == NULL) {
        fputs("out of memory", stderr);
        exit(1);
    }
    if ((buf = (unsigned char *) malloc(ks)) == NULL) {
        fputs("out of memory", stderr);
        exit(1);
    }

    if (fread(key, 1, ks, kf) != ks) {
        perror("fread");
        exit(1);
    }

    if (fclose(kf)) {
        perror("fclose");
        exit(1);
    }

    freopen(NULL, "rb", stdin);
    freopen(NULL, "wb", stdout);

    while ((n = fread(buf, 1, ks, stdin)) != 0L) {
        for (i = 0; i < n; i++)
            buf[i] ^= key[i];
        if (fwrite(buf, 1, n, stdout) != n) {
            perror("fwrite");
            exit(1);
        }
    }

    free(buf);
    free(key);

    exit(0);
}
Run Code Online (Sandbox Code Playgroud)

(这需要更多的错误检查,但是很好)。

编译上面的内容:

cc -o xor xor.c
Run Code Online (Sandbox Code Playgroud)

然后像这样运行它:

./xor my1MB.key <my1GBfile >my1GBfile.encrypted
Run Code Online (Sandbox Code Playgroud)


cwe*_*ske 7

pip-installable xortool有一个用于 xor 文件的命令行工具xortool-xor::

$ echo "foo bar baz" | xortool-xor -r secretkey --no-cycle -f - > test.enc
$ xortool-xor --no-cycle -r secretkey -f test.enc 
foo bar baz


$
Run Code Online (Sandbox Code Playgroud)


Sté*_*las 5

使用 GNU 工具,您可以:

paste <(od -An -vtu1 -w1 file) <(while :; do od -An -vtu1 -w1 key; done) |
  LC_ALL=C awk 'NF!=2{exit}; {printf "%c", xor($1, $2)}'
Run Code Online (Sandbox Code Playgroud)

您需要一个支持进程替换的 shell(如 GNU shell)、一个od支持-w选项(如 GNU od)和 GNU awkfor xor()(以及输出 NUL 字节的能力,而并非所有awks 都这样做)。