C++ aes加密例子
时间: 2024-08-14 11:04:14 浏览: 44
AES (Advanced Encryption Standard) 是一种常用的对称加密算法,常用于保护数据的安全传输。在C++中,我们可以使用第三方库如 CryptoPP 或 OpenSSL 来实现AES加密。这里以CryptoPP为例给出一个简单的AES加密示例:
```cpp
#include "cryptopp/aes.h"
#include "cryptopp/filters.h"
#include <string>
#include <iostream>
// 加密函数
std::string encrypt(const std::string &plaintext, const std::string &key) {
CryptoPP::AES::Encryption aesEncryption(key.c_str(), key.size());
CryptoPP::StringSource(plaintext, true,
new CryptoPP::StreamTransformationFilter(aesEncryption,
new CryptoPP::StringSink()));
return reinterpret_cast<const char*>(aesEncryption.OutputData()) + aesEncryption.TotalBytesProcessed();
}
// 解密函数
std::string decrypt(const std::string &ciphertext, const std::string &key) {
CryptoPP::AES::Decryption aesDecryption(key.c_str(), key.size());
CryptoPP::MemoryBuffer memoryBuffer(ciphertext.begin(), ciphertext.end());
CryptoPP::AutoSeededRandomPool randomPool;
CryptoPP::StreamTransformationFilter filter(aesDecryption, memoryBuffer, false, true, &randomPool);
std::string plaintext;
CryptoPP::StringSource(src, true, new CryptoPP::StringSink(plaintext));
return plaintext;
}
int main() {
std::string plainText = "Hello, AES!";
std::string key = "0123456789abcdef"; // 使用16字节的密钥
std::string encrypted = encrypt(plainText, key);
std::cout << "Encrypted: " << encrypted << "\n";
std::string decrypted = decrypt(encrypted, key);
std::cout << "Decrypted: " << decrypted << "\n";
return 0;
}
```
这个示例首先包含了必要的头文件,然后定义了`encrypt`和`decrypt`函数,分别使用AES加密和解密操作。注意,实际应用中你需要处理错误并妥善管理内存。
阅读全文