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;
}
相关推荐
Jay Kay16 分钟前
深入解析协程:高并发编程的轻量级解决方案
开发语言·c++·算法
岁忧19 分钟前
(LeetCode 每日一题) 2966. 划分数组并满足最大差限制 (贪心、排序)
java·c++·算法·leetcode·职场和发展·go
mit6.82424 分钟前
[Linux_core] “虚拟文件” | procfs | devfs | 上下文
linux·c语言·c++
wen__xvn4 小时前
基础数据结构第03天:顺序表(实战篇)
数据结构·c++·算法
坏柠5 小时前
C++ 进阶:深入理解虚函数、继承与多态
java·jvm·c++
虾球xz7 小时前
CppCon 2017 学习:10 Core Guidelines You Need to Start Using Now
开发语言·c++·学习
南岩亦凛汀7 小时前
在Linux下使用wxWidgets进行跨平台GUI开发(三)
c++·跨平台·gui·开源框架·工程实战教程
帅_shuai_8 小时前
UE5 游戏模板 —— Puzzle 拼图游戏
c++·游戏·ue5·虚幻引擎
字节高级特工8 小时前
每日一篇博客:理解Linux动静态库
linux·运维·服务器·c语言·c++·windows·ubuntu
oioihoii8 小时前
C++11可变参数模板从入门到精通
前端·数据库·c++