XOR演算は、同じ演算を行うと元の値に戻る性質があります。つまり1回目の演算で暗号化、2回目の演算で復号化できることになります。
XOR暗号では、暗号鍵と復号鍵は同じものになります。
スポンサードリンク
「test.dat」というファイルに書かれている暗号情報を読み出す方法です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | #include <stdio.h> #include <string.h> #include <sys/file.h> #define key 1234 #define PASSWORD_STR_LEN 6 int main() { char buf[PASSWORD_STR_LEN + 1]; FILE *file; // ファイルの読み込み file = fopen ( "test.dat" , "rb" ); int fd = fileno(file); if (file != NULL && flock(fd, LOCK_EX) == 0) { fread (buf, sizeof (buf),1,file); buf[PASSWORD_STR_LEN] = '\0' ; flock(fd, LOCK_UN); fclose (file); } // ファイルへ書き出し file = fopen ( "test.dat" , "wb" ); fd = fileno(file); if (file != NULL && flock(fd, LOCK_EX) == 0) { for ( int i=0; i < PASSWORD_STR_LEN; i++) { // XOR演算 fprintf (file, "%c" , ( char )(buf[i] ^ key)); } flock(fd, LOCK_UN); fclose (file); } return 0; } |
g++ -g -Wall angou.cpp
スポンサードリンク
「test.dat」に「secret」というパスワードがXOR演算で暗号化されているとします。
$ cat test.dat ?????? → 暗号化されている $ ./a.out $ cat test.dat secret → 複合化される $ ./a.out ?????? → 暗号化される
スポンサードリンク