aes输入字符加密,解密程序c+=
时间: 2023-12-23 12:03:01 浏览: 112
以下是使用AES加密和解密字符的C++代码示例:
```c++
#include <iostream>
#include <cstring>
#include <openssl/aes.h>
using namespace std;
// 加密函数
string encrypt(string plainText, string key) {
unsigned char iv[AES_BLOCK_SIZE] = {0};
AES_KEY aesKey;
if (AES_set_encrypt_key((const unsigned char*)key.c_str(), 128, &aesKey) < 0) {
cerr << "Unable to set encryption key in AES." << endl;
exit(1);
}
int length = (plainText.length() / AES_BLOCK_SIZE + 1) * AES_BLOCK_SIZE;
unsigned char* inData = new unsigned char[length];
memset(inData, 0, length);
memcpy(inData, plainText.c_str(), plainText.length());
unsigned char* outData = new unsigned char[length];
memset(outData, 0, length);
AES_cbc_encrypt(inData, outData, length, &aesKey, iv, AES_ENCRYPT);
string cipherText((const char*)outData, length);
delete [] inData;
delete [] outData;
return cipherText;
}
// 解密函数
string decrypt(string cipherText, string key) {
unsigned char iv[AES_BLOCK_SIZE] = {0};
AES_KEY aesKey;
if (AES_set_decrypt_key((const unsigned char*)key.c_str(), 128, &aesKey) < 0) {
cerr << "Unable to set decryption key in AES." << endl;
exit(1);
}
int length = cipherText.length();
unsigned char* inData = new unsigned char[length];
memset(inData, 0, length);
memcpy(inData, cipherText.c_str(), length);
unsigned char* outData = new unsigned char[length];
memset(outData, 0, length);
AES_cbc_encrypt(inData, outData, length, &aesKey, iv, AES_DECRYPT);
string plainText((const char*)outData, length);
delete [] inData;
delete [] outData;
return plainText;
}
int main() {
string plainText = "Hello World!";
string key = "0123456789abcdef";
// 加密
string cipherText = encrypt(plainText, key);
cout << "Cipher text: " << cipherText << endl;
// 解密
string decryptedText = decrypt(cipherText, key);
cout << "Decrypted text: " << decryptedText << endl;
return 0;
}
```
需要注意的是,上面的代码使用了OpenSSL库中的AES加密和解密函数。在使用之前需要确保已经安装了OpenSSL库,并在编译时链接该库。
阅读全文