在 Linux 下用 C++ 做“配置加密”,通常目标是:配置文件不直接是明文,程序运行时再解密使用。下面按常见做法从简单到安全给你一套思路和示例。
适合:
适合:
适合:
openssl enc -aes-256-cbc -salt -in config.txt -out config.bin
输入密码(如:mypassword)
#include <openssl/evp.h>
#include <fstream>
#include <vector>
#include <string>
#include <iostream>
using namespace std;
vector<unsigned char> readFile(const string& path) {
ifstream f(path, ios::binary);
return {istreambuf_iterator<char>(f), {}};
}
bool decrypt(const vector<unsigned char>& in,
const string& password,
string& out) {
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
const EVP_CIPHER* cipher = EVP_aes_256_cbc();
unsigned char key[32], iv[16];
EVP_BytesToKey(cipher, EVP_sha256(), nullptr,
(unsigned char*)password.data(), password.size(),
1, key, iv);
EVP_DecryptInit_ex(ctx, cipher, nullptr, key, iv);
vector<unsigned char> buf(in.size() + 16);
int len1, len2;
EVP_DecryptUpdate(ctx, buf.data(), &len1, in.data(), in.size());
EVP_DecryptFinal_ex(ctx, buf.data() + len1, &len2);
out.assign(buf.begin(), buf.begin() + len1 + len2);
EVP_CIPHER_CTX_free(ctx);
return true;
}
int main() {
auto data = readFile("config.bin");
string config;
decrypt(data, "mypassword", config);
cout << config << endl;
}
编译:
g++ main.cpp -lcrypto -o app
❌ 不要:
✅ 推荐:
| 场景 | 推荐 |
|---|---|
| 服务器 | Vault / KMS |
| 嵌入式 | 加密 + 安全芯片 |
| 多进程 | shared memory + keyring |
| 高安全 | 白盒加密 |
Linux C++ 配置加密 = AES 加密文件 + 密钥安全托管
如果你愿意,可以告诉我:
我可以给你更精确的方案。