異或(XOR)運算具有「自逆性」:A ^ B ^ B = A。同一密鑰對明文加密得密文,再次加密即還原明文。優點:算法極簡、速度極快、無需分離加解密邏輯。缺點:單次密鑰重複使用易被破解,適合簡單混淆或作為更複雜算法的基礎組件。
以下代碼實現文件級 XOR 加密/解密,包含參數校驗、錯誤處理、進度提示:
/** XOR 加密/解密文件 - xor_encrypt.c */
#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <errno.h>
#define BUF_SIZE 8192
void msg_log(const char *str) {
fprintf(stderr, "%s\n", str);
}
int file_exists(const char *filename) {
return access(filename, F_OK) == 0;
}
void usage(const char *prog) {
fprintf(stderr, "用法: %s <輸入文件> <輸出文件> <密鑰字符串>\n", prog);
fprintf(stderr, "示例: %s plain.txt cipher.bin mysecretkey\n", prog);
}
int main(int argc, char *argv[]) {
if (argc != 4) {
usage(argv[0]);
return 1;
}
const char *infile = argv[1];
const char *outfile = argv[2];
const char *key = argv[3];
size_t keylen = strlen(key);
if (keylen == 0) {
msg_log("錯誤:密鑰不能為空");
return 1;
}
if (!file_exists(infile)) {
msg_log("錯誤:輸入文件不存在");
return 1;
}
int fd_in = open(infile, O_RDONLY);
if (fd_in < 0) {
perror("打開輸入文件失敗");
return 1;
}
int fd_out = open(outfile, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (fd_out < 0) {
perror("創建輸出文件失敗");
close(fd_in);
return 1;
}
unsigned char buf[BUF_SIZE];
ssize_t bytes_read;
size_t key_pos = 0;
off_t total = 0;
while ((bytes_read = read(fd_in, buf, BUF_SIZE)) > 0) {
for (ssize_t i = 0; i < bytes_read; i++) {
buf[i] ^= key[key_pos];
key_pos = (key_pos + 1) % keylen;
}
ssize_t written = write(fd_out, buf, bytes_read);
if (written != bytes_read) {
perror("寫入輸出文件失敗");
close(fd_in);
close(fd_out);
return 1;
}
total += bytes_read;
}
if (bytes_read < 0) {
perror("讀取輸入文件失敗");
close(fd_in);
close(fd_out);
return 1;
}
close(fd_in);
close(fd_out);
msg_log("處理完成");
printf("總計處理 %lld 位元組\n", (long long)total);
return 0;
}
# 編譯
gcc -O2 -Wall -o xor_encrypt xor_encrypt.c
# 加密
./xor_encrypt plain.txt encrypted.dat "MySecretKey123"
# 解密(同一命令)
./xor_encrypt encrypted.dat decrypted.txt "MySecretKey123"
# 驗證
diff plain.txt decrypted.txt # 無輸出表示完全一致
& (keylen-1) 替代 % keylen-O2 -march=native)off_t 統計位元組數,支持 2GB+ 文件Windows 下需包含 <io.h>、<fcntl.h>,使用 _open、_read、_write、_close,或改用標準 C fopen/fread/fwrite/fclose 以提高可移植性。本文代碼在 Linux/macOS/WSL 下直接編譯運行。