MFC: 文件加解密(单元测试模块)

背景:

  1. 对敏感配置文件(如 XML 格式的配置文件、用户信息等)进行加密,防止被人以文本形式直接查看。
  2. 软件启动前加载加密的配置或资源文件,运行时再进行解密使用,提高逆向破解门槛。
  3. 在传输 XML 文件(如通过网络发送)前进行加密,保障数据在传输过程中的安全性。
cpp 复制代码
#include <openssl/aes.h>
#include <stdio.h>
#include <stdlib.h>

void AESEncrypt(const unsigned char *inputData, size_t dataSize, unsigned char *outputData, const unsigned char *key) {
    AES_KEY aesKey;
    AES_set_encrypt_key(key, 256, &aesKey);

    size_t numBlocks = dataSize / 16;

    for (size_t i = 0; i < numBlocks; ++i) {
        AES_ecb_encrypt(inputData + i * 16, outputData + i * 16, &aesKey, AES_ENCRYPT);
    }
}

void AESDecrypt(const unsigned char *inputData, size_t dataSize, unsigned char *outputData, const unsigned char *key) {
    AES_KEY aesKey;
    AES_set_decrypt_key(key, 256, &aesKey);

    size_t numBlocks = dataSize / 16;

    for (size_t i = 0; i < numBlocks; ++i) {
        AES_ecb_encrypt(inputData + i * 16, outputData + i * 16, &aesKey, AES_DECRYPT);
    }
}

int main() {
   unsigned char key[32] = "1234567890abcdef1234567890abcdef";  // 32 字节

    // Read the XML file
    const char *filePath = "path_to_your_xml_file.xml";
    FILE *file = fopen(filePath, "rb");
    if (!file) {
        perror("File open error");
        return 1;
    }

    fseek(file, 0, SEEK_END);
    long fileSize = ftell(file);
    fseek(file, 0, SEEK_SET);

    unsigned char *originalData = (unsigned char *)malloc(fileSize);
    fread(originalData, 1, fileSize, file);
    fclose(file);

    // Allocate memory for encrypted data
    unsigned char *encryptedData = (unsigned char *)malloc(fileSize);

    AESEncrypt(originalData, fileSize, encryptedData, key);

    // Write encrypted data back to the file
    file = fopen(filePath, "wb");
    if (!file) {
        perror("File open error");
        return 1;
    }
    fwrite(encryptedData, 1, fileSize, file);
    fclose(file);

    // Clean up
    free(originalData);
    free(encryptedData);

    return 0;
}
相关推荐
朝朝辞暮i44 分钟前
C++ 第 10 课:函数 Function
开发语言·c++
Zootopia6261 小时前
快递无人车与无人机各自进入配送网络后,路线能否一起算?
c++·人工智能·机器学习·matlab·ai·机器人·无人机
朝朝辞暮i1 小时前
C++ 第7课 while 循环
开发语言·c++·算法
huanbailu3 小时前
Qt 跨线程信号槽:connect 返回 true 但槽函数不执行的坑
开发语言·c++·qt·信号槽·跨线程·元类型
HEJOO93 小时前
C++ 虚函数表(vtable)深度解析
开发语言·c++
xailorliu4 小时前
矩阵定性-正定负定不定半正定半负定
c++·opencv·线性代数·计算机视觉·矩阵
个 人 练 习 生4 小时前
C++-----string基本使用详解
开发语言·c++·学习
朝朝辞暮i4 小时前
C++ 第 5 课:else if + 多条件判断 + && / || / !
开发语言·c++
千谦阙听4 小时前
【C++篇】:string类——常用接口、底层原理与深浅拷贝
开发语言·c++·学习·visual studio
特立独行的猫A5 小时前
c++的`std::future` 与 `std::promise` 简明教程(5分钟读完)
c++