C++ 哪个库可以方便的进行 AES 加密解密
时间: 2024-04-03 18:34:49 浏览: 187
Crypto++(也叫CryptoPP)是一款非常方便的C++加密库,可以用于AES加密和解密。以下是简单的示例代码:
AES加密:
```cpp
#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/filters.h>
std::string plaintext = "Hello World!";
std::string key = "mysecretkey";
std::string iv = "myivalue";
CryptoPP::AES::Encryption aesEncryption((byte*)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, (byte*)iv.c_str());
std::string ciphertext;
CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink(ciphertext));
stfEncryptor.Put(reinterpret_cast<const unsigned char*>(plaintext.c_str()), plaintext.length()+1);
stfEncryptor.MessageEnd();
std::string encrypted = CryptoPP::base64_encode(reinterpret_cast<const unsigned char*>(ciphertext.c_str()), ciphertext.length());
```
AES解密:
```cpp
#include <cryptopp/aes.h>
#include <cryptopp/modes.h>
#include <cryptopp/filters.h>
std::string encrypted = "encrypted";
std::string key = "mysecretkey";
std::string iv = "myivalue";
std::string ciphertext = CryptoPP::base64_decode(encrypted);
CryptoPP::AES::Decryption aesDecryption((byte*)key.c_str(), CryptoPP::AES::DEFAULT_KEYLENGTH);
CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, (byte*)iv.c_str());
std::string decrypted;
CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink(decrypted));
stfDecryptor.Put(reinterpret_cast<const unsigned char*>(ciphertext.c_str()), ciphertext.size());
stfDecryptor.MessageEnd();
```
需要注意的是,Crypto++库需要自行安装并配置,但它提供了丰富的加密算法,使用方便,是一款广泛应用的C++加密库。
阅读全文