aes算法的c++实现
时间: 2023-07-26 22:40:40 浏览: 105
以下是AES算法的C++实现代码,可以用于加密和解密:
```c++
#include <iostream>
#include <string>
#include <cstring>
#include <openssl/aes.h>
using namespace std;
string aes_encrypt(string key, string plain_text) {
unsigned char iv[AES_BLOCK_SIZE];
memset(iv, 0x00, AES_BLOCK_SIZE);
AES_KEY aes_key;
if (AES_set_encrypt_key((unsigned char*)key.c_str(), 128, &aes_key) < 0) {
cerr << "Unable to set encryption key in AES." << endl;
return "";
}
int plain_text_len = plain_text.length();
int len = 0;
int max_len = plain_text_len + AES_BLOCK_SIZE - plain_text_len % AES_BLOCK_SIZE;
unsigned char* in_data = new unsigned char[max_len];
memset(in_data, 0x00, max_len);
memcpy(in_data, plain_text.c_str(), plain_text_len);
unsigned char* out_data = new unsigned char[max_len];
memset(out_data, 0x00, max_len);
AES_cbc_encrypt(in_data, out_data, max_len, &aes_key, iv, AES_ENCRYPT);
string encrypted_text((char*)out_data, max_len);
delete[] in_data;
delete[] out_data;
return encrypted_text;
}
string aes_decrypt(string key, string encrypted_text) {
unsigned char iv[AES_BLOCK_SIZE];
memset(iv, 0x00, AES_BLOCK_SIZE);
AES_KEY aes_key;
if (AES_set_decrypt_key((unsigned char*)key.c_str(), 128, &aes_key) < 0) {
cerr << "Unable to set decryption key in AES." << endl;
return "";
}
int encrypted_text_len = encrypted_text.length();
int len = 0;
int max_len = encrypted_text_len + AES_BLOCK_SIZE - encrypted_text_len % AES_BLOCK_SIZE;
unsigned char* in_data = new unsigned char[max_len];
memset(in_data, 0x00, max_len);
memcpy(in_data, encrypted_text.c_str(), encrypted_text_len);
unsigned char* out_data = new unsigned char[max_len];
memset(out_data, 0x00, max_len);
AES_cbc_encrypt(in_data, out_data, max_len, &aes_key, iv, AES_DECRYPT);
string decrypted_text((char*)out_data);
delete[] in_data;
delete[] out_data;
return decrypted_text;
}
int main() {
string key = "1234567890123456"; // 16-byte (128-bit) key
string plain_text = "This is a test message.";
string encrypted_text = aes_encrypt(key, plain_text);
cout << "Encrypted text: " << encrypted_text << endl;
string decrypted_text = aes_decrypt(key, encrypted_text);
cout << "Decrypted text: " << decrypted_text << endl;
return 0;
}
```
注意:需要安装OpenSSL库才能正常编译和运行此代码。
阅读全文