C語言實現文件加密

原理

加密文本,或加密二進制文件,可以選擇的一個最小加密單元是單個字符(或者說,一個byte)。

將每個byte和31做異或運算,得到加密結果。再做一次異或則得以恢復原始數據。

加密文本 - 控制檯程序

#include <stdio.h>
#include <stdlib.h>

void encrypt(char* message)
{
    char c;
    while (*message)
    {
        *message = *message ^ 31;
        message++;
    }
}

int main()
{
    char msg[80];
    while (fgets(msg, 80, stdin))
    {
        encrypt(msg);
        printf("%s", msg);
    }
}

使用:

gcc encrypt_text.c -o encrypt_text
./encrypt_text 

加密二進制文件

加密代碼實現:

int encrypt_binary_file(const char* sourcePath, const char* destPath)
{
    unsigned char buffer[1024];  // 讀取數據的緩衝區
    size_t bytesRead;  // 實際讀取的字節數

    // 打開源文件和目標文件
    FILE* sourceFile = fopen(sourcePath, "rb");
    if (sourceFile == NULL) {
        perror("Error opening source file");
        return 1;
    }

    FILE* destFile = fopen(destPath, "wb");
    if (destFile == NULL) {
        perror("Error opening destination file");
        fclose(sourceFile);
        return 1;
    }

    // 讀取源文件,處理數據,寫入目標文件
    while ((bytesRead = fread(buffer, 1, sizeof(buffer), sourceFile)) > 0) {
        for (size_t i = 0; i < bytesRead; i++) {
            buffer[i] ^= 31;  // 對每個字節進行異或操作
        }
        fwrite(buffer, 1, bytesRead, destFile);  // 寫入處理後的數據到目標文件
    }

    // 關閉文件
    fclose(sourceFile);
    fclose(destFile);

    printf("File has been processed and saved successfully.\n");

    return 0;
}

int main(int argc, char** argv)
{
    if (argc != 3)
    {
        fprintf(stderr, "Usage: %s in_file out_file\n", argv[0]);
        return 1;
    }
    encrypt_binary_file(argv[1], argv[2]);

    return 0;
}

準備測試的二進制文件:

#include <stdio.h>
int main() { printf("hello world\n"); }
gcc hello.c -o hello

使用:

# 編譯
gcc encrypt_bin_file.c -o encrypt_bin_file
# 加密
./encrypt_bin_file  hello encrypted_hello
# 解密
./encrypt_bin_file encrypted_hello decrypted_hello
# 運行
chmod +x ./hello
./hello

Reference

"Head First C" 嗨翻C語言 中譯本 P182

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章