C++中使用aes算法加解密示例
C++中使用aes算法加解密示例在 VC++ 中使用 AES 算法进行加密和解密,可以使用第三方库,例如 Crypto++。以下是一个示例代码,展示如何使用 Crypto++ 库进行 AES 加密和解密:
#include <iostream>
#include <string>
#include <cryptlib.h>
#include <modes.h>
#include <aes.h>
#include <hex.h>
#include <files.h>
using namespace std;
using namespace CryptoPP;
string AESEncrypt(const string& plainText, const byte* key, const byte* iv)
{
string cipherText;
try
{
CBC_Mode<AES>::Encryption encryption;
encryption.SetKeyWithIV(key, AES::DEFAULT_KEYLENGTH, iv);
StringSource(plainText, true,
new StreamTransformationFilter(encryption,
new StringSink(cipherText)
)
);
}
catch (const CryptoPP::Exception& e)
{
cerr << "AES encryption error: " << e.what() << endl;
}
return cipherText;
}
string AESDecrypt(const string& cipherText, const byte* key, const byte* iv)
{
string decryptedText;
try
{
CBC_Mode<AES>::Decryption decryption;
decryption.SetKeyWithIV(key, AES::DEFAULT_KEYLENGTH, iv);
StringSource(cipherText, true,
new StreamTransformationFilter(decryption,
new StringSink(decryptedText)
)
);
}
catch (const CryptoPP::Exception& e)
{
cerr << "AES decryption error: " << e.what() << endl;
}
return decryptedText;
}
int main()
{
byte key = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
byte iv = { 0x00 };
string plainText = "Hello, World!";
string cipherText = AESEncrypt(plainText, key, iv);
string decryptedText = AESDecrypt(cipherText, key, iv);
cout << "Plain Text: " << plainText << endl;
cout << "Cipher Text: " << cipherText << endl;
cout << "Decrypted Text: " << decryptedText << endl;
return 0;
}
在上述代码中,我们使用 Crypto++ 库提供的 AES 加密和解密功能。 AESEncrypt函数接受明文、密钥和初始化向量(IV)作为参数,使用 AES 算法对明文进行加密,并返回加密后的字符串。 AESDecrypt函数接受密文、密钥和初始化向量(IV)作为参数,使用 AES 算法对密文进行解密,并返回解密后的明文。在主程序中,我们使用示例的明文、密钥和初始化向量进行加密和解密,并打印结果。请确保在使用前安装并引入 Crypto++ 库,并将相关的头文件添加到项目中。
页:
[1]