CS客户端 加密保存不同用户不同的字符串到本地,Cpp源码实现
时间: 2024-01-11 17:04:46 浏览: 25
以下是一个简单的示例代码,可以实现将不同用户的字符串加密保存到本地。
```cpp
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <openssl/evp.h>
#include <openssl/rand.h>
using namespace std;
class Encryption {
public:
Encryption(const string& key)
: m_key(key) {}
string encrypt(const string& plaintext) const {
// 生成随机向量
unsigned char iv[EVP_MAX_IV_LENGTH];
RAND_bytes(iv, EVP_MAX_IV_LENGTH);
// 初始化加密上下文
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, (const unsigned char*)m_key.c_str(), iv);
// 分配输出缓冲区
int outlen = plaintext.length() + EVP_MAX_BLOCK_LENGTH;
unsigned char* outbuf = new unsigned char[outlen];
// 执行加密操作
int ciphertext_len = 0;
EVP_EncryptUpdate(ctx, outbuf, &outlen, (const unsigned char*)plaintext.c_str(), plaintext.length());
ciphertext_len += outlen;
EVP_EncryptFinal_ex(ctx, outbuf + ciphertext_len, &outlen);
ciphertext_len += outlen;
// 将密文和随机向量合并
string ciphertext((char*)iv, EVP_MAX_IV_LENGTH);
ciphertext += string((char*)outbuf, ciphertext_len);
// 释放内存
delete[] outbuf;
EVP_CIPHER_CTX_free(ctx);
return ciphertext;
}
string decrypt(const string& ciphertext) const {
// 提取随机向量和密文
unsigned char iv[EVP_MAX_IV_LENGTH];
memcpy(iv, ciphertext.c_str(), EVP_MAX_IV_LENGTH);
string data(ciphertext, EVP_MAX_IV_LENGTH, string::npos);
// 初始化解密上下文
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), nullptr, (const unsigned char*)m_key.c_str(), iv);
// 分配输出缓冲区
int outlen = data.length() + EVP_MAX_BLOCK_LENGTH;
unsigned char* outbuf = new unsigned char[outlen];
// 执行解密操作
int plaintext_len = 0;
EVP_DecryptUpdate(ctx, outbuf, &outlen, (const unsigned char*)data.c_str(), data.length());
plaintext_len += outlen;
EVP_DecryptFinal_ex(ctx, outbuf + plaintext_len, &outlen);
plaintext_len += outlen;
// 释放内存
string plaintext((char*)outbuf, plaintext_len);
delete[] outbuf;
EVP_CIPHER_CTX_free(ctx);
return plaintext;
}
private:
string m_key;
};
int main() {
map<string, string> user_data = {
{"user1", "data1"},
{"user2", "data2"}
};
Encryption encrypter("my_secret_key");
for (const auto& [user, data] : user_data) {
// 加密并保存到文件
string encrypted = encrypter.encrypt(data);
ofstream file(user + ".dat", ios::binary);
file.write(encrypted.c_str(), encrypted.length());
file.close();
// 读取并解密文件
ifstream infile(user + ".dat", ios::binary);
string ciphertext((istreambuf_iterator<char>(infile)), istreambuf_iterator<char>());
string decrypted = encrypter.decrypt(ciphertext);
cout << user << ": " << decrypted << endl;
}
return 0;
}
```
在此示例中,我们使用 OpenSSL 库中的 EVP 加密算法进行加密和解密。具体来说,我们使用 AES-256-CBC 加密算法来加密数据。在加密过程中,我们使用一个固定的密钥对数据进行加密。在实际情况中,你可能需要使用更加安全的密钥管理方案,例如使用密钥派生函数生成密钥。
在 `main` 函数中,我们首先定义了一个 `user_data` 映射,其中存储了每个用户的数据。然后,我们使用 `Encryption` 类来加密每个用户的数据,并将其保存到 `user.dat` 文件中。接下来,我们读取该文件并解密其中的数据,并将其输出到控制台。注意,我们使用的是二进制文件模式来打开文件,以确保所有字节都能正确地读取和写入。