c++实现对称加密算法
时间: 2024-04-02 21:28:22 浏览: 22
C++可以使用各种库来实现对称加密算法其中最常用的是OpenSSL库。OpenSSL是一个开源的加密库,提供了丰富的加密算法和功能。
下面是一个使用OpenSSL库实现对称加密算法的简单示例:
```cpp
#include <openssl/conf.h>
#include <openssl/evp.h>
#include <openssl/err.h>
void handleErrors()
{
ERR_print_errors_fp(stderr);
abort();
}
std::string encrypt(const std::string& plaintext, const std::string& key)
{
// 初始化加密库
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
// 创建并初始化加密上下文
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) {
handleErrors();
}
// 设置加密算法和密钥
if (EVP_EncryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*)key.c_str(), NULL) != 1) {
handleErrors();
}
// 加密数据
int ciphertext_len = plaintext.length() + EVP_MAX_BLOCK_LENGTH;
unsigned char* ciphertext = new unsigned char[ciphertext_len];
int len;
if (EVP_EncryptUpdate(ctx, ciphertext, &len, (const unsigned char*)plaintext.c_str(), plaintext.length()) != 1) {
handleErrors();
}
ciphertext_len = len;
// 结束加密过程
if (EVP_EncryptFinal_ex(ctx, ciphertext + len, &len) != 1) {
handleErrors();
}
ciphertext_len += len;
// 清理资源
EVP_CIPHER_CTX_free(ctx);
// 将加密结果转换为字符串
std::string result((char*)ciphertext, ciphertext_len);
delete[] ciphertext;
return result;
}
std::string decrypt(const std::string& ciphertext, const std::string& key)
{
// 初始化加密库
OpenSSL_add_all_algorithms();
ERR_load_crypto_strings();
// 创建并初始化解密上下文
EVP_CIPHER_CTX* ctx = EVP_CIPHER_CTX_new();
if (!ctx) {
handleErrors();
}
// 设置解密算法和密钥
if (EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, (const unsigned char*)key.c_str(), NULL) != 1) {
handleErrors();
}
// 解密数据
int plaintext_len = ciphertext.length() + EVP_MAX_BLOCK_LENGTH;
unsigned char* plaintext = new unsigned char[plaintext_len];
int len;
if (EVP_DecryptUpdate(ctx, plaintext, &len, (const unsigned char*)ciphertext.c_str(), ciphertext.length()) != 1) {
handleErrors();
}
plaintext_len = len;
// 结束解密过程
if (EVP_DecryptFinal_ex(ctx, plaintext + len, &len) != 1) {
handleErrors();
}
plaintext_len += len;
// 清理资源
EVP_CIPHER_CTX_free(ctx);
// 将解密结果转换为字符串
std::string result((char*)plaintext, plaintext_len);
delete[] plaintext;
return result;
}
```
使用上述代码,你可以调用`encrypt`函数来对明文进行加密,调用`decrypt`函数来对密文进行解密。需要注意的是,这里使用的是AES-256算法和CBC模式,你可以根据需要选择其他的加密算法和模式。