以下是一个用于文件加密和解密的C语言算法源码示例,该示例提供命令行使用方式,并可自定义密钥。

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

// 自定义的密钥字符串
#define KEY 'myencryptionkey'

// 加密函数
void encryptFile(FILE* inputFile, FILE* outputFile, const char* key) {
    char ch;
    int i = 0;
    int keyLength = strlen(key);
    
    while ((ch = fgetc(inputFile)) != EOF) {
        ch = ch ^ key[i % keyLength]; // 使用异或操作加密
        
        fputc(ch, outputFile);
        i++;
    }
}

// 解密函数
void decryptFile(FILE* inputFile, FILE* outputFile, const char* key) {
    char ch;
    int i = 0;
    int keyLength = strlen(key);
    
    while ((ch = fgetc(inputFile)) != EOF) {
        ch = ch ^ key[i % keyLength]; // 使用异或操作解密
        
        fputc(ch, outputFile);
        i++;
    }
}

int main(int argc, char** argv) {
    if (argc < 4) {
        printf("Usage: %s <encrypt/decrypt> <input_file> <output_file>
", argv[0]);
        return 1;
    }
    
    const char* mode = argv[1];
    const char* inputFile = argv[2];
    const char* outputFile = argv[3];
    
    FILE* input = fopen(inputFile, "rb");
    FILE* output = fopen(outputFile, "wb");
    
    if (!input || !output) {
        printf("Failed to open files!
");
        return 1;
    }
    
    if (strcmp(mode, "encrypt") == 0) {
        encryptFile(input, output, KEY);
        printf("File encrypted successfully!
");
    } else if (strcmp(mode, "decrypt") == 0) {
        decryptFile(input, output, KEY);
        printf("File decrypted successfully!
");
    } else {
        printf("Invalid mode! Use 'encrypt' or 'decrypt'.
");
    }
    
    fclose(input);
    fclose(output);
    
    return 0;
}

在上述代码中,有一个名为KEY的宏定义,用于自定义密钥字符串。你可以将其修改为你想要的任何字符串。请确保密钥字符串足够长和复杂,以提高加密的安全性。

该程序提供命令行使用方式,使用方法如下:

./程序名 encrypt 输入文件 输出文件 进行加密

./程序名 decrypt 输入文件 输出文件 进行解密

C语言文件加密解密:命令行工具、算法源码和自定义密钥

原文地址: https://www.cveoy.top/t/topic/paCa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录