首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C語言實現文件XOR異或加密解密:高性能跨平台方案

     編輯:關於C語言

XOR 加密原理與優勢

異或(XOR)運算具有「自逆性」:A ^ B ^ B = A。同一密鑰對明文加密得密文,再次加密即還原明文。優點:算法極簡、速度極快、無需分離加解密邏輯。缺點:單次密鑰重複使用易被破解,適合簡單混淆或作為更複雜算法的基礎組件。

完整 C 實現代碼

以下代碼實現文件級 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  # 無輸出表示完全一致

性能優化要點

  • 塊讀寫:使用 8KB 緩衝區減少系統調用開銷
  • 避免頻繁取模:密鑰長度若為 2 的冪次,可用位與 & (keylen-1) 替代 % keylen
  • 向量化:現代編譯器可自動將循環優化為 SIMD 指令(需 -O2 -march=native)
  • 大文件支持:使用 off_t 統計位元組數,支持 2GB+ 文件

安全性增強建議

  1. 密鑰派生:使用 PBKDF2/Argon2 從口令派生高熵密鑰,而非直接使用字符串
  2. 隨機 IV:文件頭寫入隨機鹽值,每次加密生成不同密文
  3. 完整性校驗:添加 HMAC-SHA256 防篡改
  4. 常用替代:生產環境建議使用 AES-GCM、ChaCha20-Poly1305 等經審計的認證加密庫(如 libsodium、OpenSSL)

跨平台注意事項

Windows 下需包含 <io.h>、<fcntl.h>,使用 _open、_read、_write、_close,或改用標準 C fopen/fread/fwrite/fclose 以提高可移植性。本文代碼在 Linux/macOS/WSL 下直接編譯運行。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved