vs2019实现aes加密
时间: 2023-09-02 08:12:18 浏览: 64
以下是使用 VS2019 实现 AES 加密的示例代码:
```c++
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
#include <vector>
#include <stdexcept>
#include <openssl/aes.h>
using namespace std;
// 将字符串转换为 16 字节的字节数组
vector<unsigned char> string_to_bytes(const string &str)
{
vector<unsigned char> bytes(str.begin(), str.end());
if (bytes.size() < 16)
{
bytes.resize(16, '0');
}
return bytes;
}
// 加密函数
string aes_encrypt(const string &plaintext, const string &key)
{
if (key.length() < 16)
{
throw invalid_argument("key length must be at least 16 bytes");
}
vector<unsigned char> keyBytes = string_to_bytes(key);
AES_KEY aesKey;
if (AES_set_encrypt_key(&keyBytes[0], 128, &aesKey) != 0)
{
throw runtime_error("AES_set_encrypt_key failed");
}
vector<unsigned char> plaintextBytes = string_to_bytes(plaintext);
size_t plaintextLen = plaintextBytes.size();
size_t ciphertextLen = ((plaintextLen - 1) / 16 + 1) * 16;
vector<unsigned char> ciphertext(ciphertextLen);
AES_cbc_encrypt(&plaintextBytes[0], &ciphertext[0], plaintextLen, &aesKey, &keyBytes[0], AES_ENCRYPT);
return string(ciphertext.begin(), ciphertext.end());
}
// 解密函数
string aes_decrypt(const string &ciphertext, const string &key)
{
if (key.length() < 16)
{
throw invalid_argument("key length must be at least 16 bytes");
}
vector<unsigned char> keyBytes = string_to_bytes(key);
AES_KEY aesKey;
if (AES_set_decrypt_key(&keyBytes[0], 128, &aesKey) != 0)
{
throw runtime_error("AES_set_decrypt_key failed");
}
vector<unsigned char> ciphertextBytes = string_to_bytes(ciphertext);
size_t ciphertextLen = ciphertextBytes.size();
size_t plaintextLen = ((ciphertextLen - 1) / 16 + 1) * 16;
vector<unsigned char> plaintext(plaintextLen);
AES_cbc_encrypt(&ciphertextBytes[0], &plaintext[0], ciphertextLen, &aesKey, &keyBytes[0], AES_DECRYPT);
return string(plaintext.begin(), plaintext.end());
}
int main()
{
string plaintext = "hello world";
string key = "0123456789abcdef";
string ciphertext = aes_encrypt(plaintext, key);
cout << "ciphertext: " << ciphertext << endl;
string decryptedText = aes_decrypt(ciphertext, key);
cout << "decryptedText: " << decryptedText << endl;
return 0;
}
```
该示例代码使用 OpenSSL 库实现 AES 加密算法,其中使用了 CBC 模式进行加密。在使用之前,需要先安装 OpenSSL 库。建议在 Windows 上使用 vcpkg 进行安装,Linux 上使用系统包管理器进行安装。在 VS2019 中,需要将 OpenSSL 库的头文件和库文件添加到项目中。