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;
}
相关推荐
Darkwanderor12 分钟前
三分算法的简单应用
c++·算法·三分法·三分算法
2401_8319207429 分钟前
分布式系统安全通信
开发语言·c++·算法
2401_877274241 小时前
从匿名管道到 Master-Slave 进程池:Linux 进程间通信深度实践
linux·服务器·c++
汉克老师1 小时前
GESP5级C++考试语法知识(八、链表(三)循环链表)
c++·约瑟夫问题·循环链表·gesp5级·gesp五级
阿贵---1 小时前
C++中的RAII技术深入
开发语言·c++·算法
PiKaMouse.2 小时前
navigation2-humble从零带读笔记第一篇:nav2_core
c++·算法·机器人
lightqjx2 小时前
【算法】二分算法
c++·算法·leetcode·二分算法·二分模板
Irissgwe3 小时前
进程间通信
linux·服务器·网络·c++·进程间通信
add45a3 小时前
C++编译期数据结构
开发语言·c++·算法
灰色小旋风4 小时前
力扣21 合并两个有序链表(C++)
c++·leetcode·链表