XORで暗号化&複合化
最も簡単な暗号化/複合化を試してみる。
任意のデータとある定数値の排他的論理和(XOR)を2回とると元のデータに戻る性質を利用する。
例)
任意のデータ : 10101010 XORをとる定数: 11110000 1回目 10101010 XOR 11110000 ------------- 01011010 2回目 01011010 XOR 11110000 ------------- 10101010 ★
目次
ソースコード
1byte単位で暗号/複合キーとのXORをとりファイルへ書き出す。
xor.c
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <errno.h>
#define XOR_KEY 0xE5
int main(int argc, char* argv[])
{
if (argc != 3) {
printf("usage : %s <src file> <dst file> \n", argv[0]);
exit(EXIT_FAILURE);
}
FILE* srcfp = fopen(argv[1], "rb");
if (NULL == srcfp) {
perror("fopen");
exit(EXIT_FAILURE);
}
FILE* dstfp = fopen(argv[2], "w+b");
if (NULL == dstfp) {
perror("fopen");
fclose(srcfp);
exit(EXIT_FAILURE);
}
while(0 == feof(srcfp)) {
uint8_t dat = 0x00;
size_t rs = fread(&dat, sizeof(dat), 1, srcfp);
if (rs == 0) {
break;
}
/* 暗号化 or 複合化 */
dat ^= XOR_KEY;
fwrite(&dat, sizeof(dat), 1, dstfp);
}
fclose(dstfp);
fclose(srcfp);
return 0;
}
暗号化対象のデータ
file1.txt
$ cat file1.txt
abcdefghijklmnopqrstuvwxyz
$
$ hexdump -C file1.txt
00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|
00000010 71 72 73 74 75 76 77 78 79 7a 0a |qrstuvwxyz.|
0000001b
実行結果
$ gcc -o xor xor.c
$ ./xor file1.txt file2.txt
$ ./xor file2.txt file3.txt
$
$ hexdump -C file1.txt
00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|
00000010 71 72 73 74 75 76 77 78 79 7a 0a |qrstuvwxyz.|
0000001b
$ hexdump -C file2.txt
00000000 84 87 86 81 80 83 82 8d 8c 8f 8e 89 88 8b 8a 95 |................|
00000010 94 97 96 91 90 93 92 9d 9c 9f ef |...........|
0000001b
$ hexdump -C file3.txt
00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop|
00000010 71 72 73 74 75 76 77 78 79 7a 0a |qrstuvwxyz.|
0000001b
コメント