温馨提示×

linux c++配置怎样加密

小樊
37
2026-10-05 01:51:03
栏目: 编程语言

在 Linux 下用 C++ 做“配置加密”,通常分几种场景和需求。下面按常见做法 + 示例给你一个清晰方案。


一、常见配置加密方案

方案 1:配置文件整体加密(最常见)

思路

  • 配置以明文写一份(开发用)
  • 发布前用对称加密(AES)加密成 .enc 文件
  • 程序启动时解密到内存中使用

优点:简单、安全
缺点:密钥不能硬编码太明显


方案 2:敏感字段加密(推荐)

  • 配置文件中只有密码、Token 等字段加密
  • 形如:
host = 127.0.0.1
port = 8080
password = ENC(AES:9f86d081...)

方案 3:使用系统密钥(更高安全)

  • 利用 Linux 的:
    • libsecret
    • gnome-keyring
    • systemd-cryptsetup
  • 程序运行时从系统获取密钥

二、C++ 中使用 AES 加密(示例)

1️⃣ 使用 OpenSSL(最常用)

安装

sudo apt install libssl-dev

加密配置示例(AES-256-CBC)

#include <openssl/evp.h>
#include <openssl/rand.h>
#include <vector>
#include <string>

using namespace std;

vector<unsigned char> aes_encrypt(
    const string &plaintext,
    const unsigned char *key,
    const unsigned char *iv)
{
    EVP_CIPHER_CTX *ctx = EVP_CIPHER_CTX_new();
    EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, key, iv);

    vector<unsigned char> ciphertext(plaintext.size() + 16);
    int len, ciphertext_len;

    EVP_EncryptUpdate(ctx, ciphertext.data(), &len,
                      (unsigned char*)plaintext.data(), plaintext.size());
    ciphertext_len = len;

    EVP_EncryptFinal_ex(ctx, ciphertext.data() + len, &len);
    ciphertext_len += len;

    EVP_CIPHER_CTX_free(ctx);
    ciphertext.resize(ciphertext_len);
    return ciphertext;
}

2️⃣ 密钥管理(重点)

❌ 错误方式:

unsigned char key[] = "1234567890abcdef";

✅ 推荐方式:

  • 从环境变量读取
const char* key = getenv("APP_CONFIG_KEY");
  • 或运行时由服务器注入
  • 或硬件/安全模块(HSM)

三、配置文件示例

明文配置

{
  "db_host": "localhost",
  "db_password": "mypassword"
}

加密后

config.json.enc

程序流程

  1. 启动
  2. 读取环境变量密钥
  3. 解密 config.json.enc
  4. 解析 JSON

四、配合 JSON / INI 使用

推荐库:

  • JSON:nlohmann/json
  • INI:inih

五、进阶安全建议

✅ 配置只在内存中存在
✅ 不写临时明文文件
✅ 使用 mlock() 防止被 swap
✅ 定期更换密钥


六、如果你愿意,我可以进一步帮你

你可以告诉我:

  1. 配置文件格式(JSON / ini / yaml)
  2. 加密级别(普通 / 高安全)
  3. 是否允许运行时输入密码

我可以直接给你完整可编译示例。

0 踩