给出C++语言的AES加解密算法
时间: 2023-10-12 09:20:19 浏览: 157
下面是C++语言的AES加解密算法示例代码,其中使用了Crypto++库实现AES加解密:
```cpp
#include <iostream>
#include <string>
#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/filters.h>
using namespace CryptoPP;
std::string aes_encrypt(const std::string& plaintext, const std::string& key) {
std::string ciphertext;
try {
CBC_Mode<AES>::Encryption encryption((byte*)key.c_str(), key.length());
StringSource(plaintext, true,
new StreamTransformationFilter(encryption,
new StringSink(ciphertext)
)
);
}
catch (const CryptoPP::Exception& e) {
std::cerr << e.what() << std::endl;
exit(1);
}
return ciphertext;
}
std::string aes_decrypt(const std::string& ciphertext, const std::string& key) {
std::string decryptedtext;
try {
CBC_Mode<AES>::Decryption decryption((byte*)key.c_str(), key.length());
StringSource(ciphertext, true,
new StreamTransformationFilter(decryption,
new StringSink(decryptedtext)
)
);
}
catch (const CryptoPP::Exception& e) {
std::cerr << e.what() << std::endl;
exit(1);
}
return decryptedtext;
}
int main() {
std::string key = "0123456789abcdef"; // 128-bit key
std::string plaintext = "Hello, world!";
std::string ciphertext = aes_encrypt(plaintext, key);
std::cout << "Ciphertext: " << ciphertext << std::endl;
std::string decryptedtext = aes_decrypt(ciphertext, key);
std::cout << "Decryptedtext: " << decryptedtext << std::endl;
return 0;
}
```
在此示例代码中,使用了Crypto++库中的 `CBC_Mode` 来实现AES加解密,其中 `key` 是128位的AES密钥, `plaintext` 是待加密的明文, `ciphertext` 是加密后的密文, `decryptedtext` 是解密后的明文。
阅读全文