在 Linux 下用 C++ 做“配置加密”,通常分几种场景和需求。下面按常见做法 + 示例给你一个清晰方案。
思路
.enc 文件优点:简单、安全
缺点:密钥不能硬编码太明显
host = 127.0.0.1
port = 8080
password = ENC(AES:9f86d081...)
libsecretgnome-keyringsystemd-cryptsetupsudo apt install libssl-dev
#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;
}
❌ 错误方式:
unsigned char key[] = "1234567890abcdef";
✅ 推荐方式:
const char* key = getenv("APP_CONFIG_KEY");
{
"db_host": "localhost",
"db_password": "mypassword"
}
config.json.enc
config.json.enc推荐库:
nlohmann/jsoninih✅ 配置只在内存中存在
✅ 不写临时明文文件
✅ 使用 mlock() 防止被 swap
✅ 定期更换密钥
你可以告诉我:
我可以直接给你完整可编译示例。