XOR a file against a key
bash
can't deal with ASCII NUL
characters, so you won't be doing this with shell functions, you need a small program for it. This can be done in just about any language, but it seems easiest to do it in C, perhaps like this:
#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);
}
(this needs some more error checking, but oh well).
Compile the above with:
cc -o xor xor.c
then run it like this:
./xor my1MB.key <my1GBfile >my1GBfile.encrypted
With GNU tools, you can do:
paste <(od -An -vtu1 -w1 file) <(while :; do od -An -vtu1 -w1 key; done) |
awk 'NF!=2{exit}; {printf "%c", xor($1, $2)}'
You need a shell (like the GNU shell) with process substitution support, a od
with support for the -w
option (like GNU od
), and GNU awk
for xor()
(and the ability to output the NUL byte which not all awk
s do).