在C++里做一个简易密码管理器,核心是把用户输入的账号密码用对称加密算法处理后再落盘,读取时再解密。下面给出一个基于OpenSSL AES-256-CBC的实现思路与示例。

整体设计
程序提供三个基础操作:添加密码、检索密码、退出。密码以行格式存于本地文件,每行包含名称与密文,密钥由用户启动时输入。
依赖与编译
需要系统安装OpenSSL开发库,编译时链接crypto:
g++ main.cpp -o pwd_manager -lcrypto
加密与存储示例
使用EVP接口做AES-256-CBC加密,简单封装如下:
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <string>
#include <vector>
// 使用密钥key与随机iv加密明文
std::vector<unsigned char> aes_encrypt(const std::string& key,
const std::string& plaintext) {
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
unsigned char iv[16];
RAND_bytes(iv, sizeof(iv));
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
(unsigned char*)key.data(), iv);
std::vector<unsigned char> out(iv, iv + 16);
int len = 0;
EVP_EncryptUpdate(ctx, &out[16], &len,
(unsigned char*)plaintext.data(), plaintext.size());
int tot = 16 + len;
EVP_EncryptFinal_ex(ctx, &out[tot], &len);
tot += len;
out.resize(tot);
EVP_CIPHER_CTX_free(ctx);
return out;
}
写入文件
把名称与密文用逗号拼接后追加到pwd.dat:
#include <fstream>
void save_entry(const std::string& name,
const std::vector<unsigned char>& cipher) {
std::ofstream f("pwd.dat", std::ios::binary | std::ios::app);
f << name << ",";
for (auto c : cipher) f << (int)c << " ";
f << "n";
}
检索与解密
检索时按名称找到行,提取密文并用同一密钥解密:
#include <iostream>
#include <sstream>
std::string aes_decrypt(const std::string& key,
const std::vector<unsigned char>& cipher) {
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL,
(unsigned char*)key.data(), cipher.data());
std::vector<unsigned char> out(cipher.size());
int len = 0, tot = 0;
EVP_DecryptUpdate(ctx, &out[0], &len,
cipher.data() + 16, cipher.size() - 16);
tot = len;
EVP_DecryptFinal_ex(ctx, &out[tot], &len);
tot += len;
EVP_CIPHER_CTX_free(ctx);
return std::string((char*)out.data(), tot);
}
void search_entry(const std::string& key, const std::string& name) {
std::ifstream f("pwd.dat");
std::string line;
while (std::getline(f, line)) {
std::istringstream iss(line);
std::string n; std::getline(iss, n, ',');
if (n == name) {
std::vector<unsigned char> buf;
int x; while (iss >> x) buf.push_back((unsigned char)x);
std::cout << "密码: " << aes_decrypt(key, buf) << "n";
return;
}
}
std::cout << "未找到n";
}
小结
以上代码展示了怎样制作C++的简易密码管理器并实现加密存储与检索功能。实际使用中应注意密钥不要硬编码,可结合环境变量或二次口令提升安全性。