本文主要介绍AES算法的相关知识,同时通过示例代码介绍使用AES算法实现加解密操作的方法。
说明:本文的示例程序使用的是C++编程语言,调用的AES库为cryptopp。
1 概述
引用WikiPedia上对于AES加密算法的介绍,内容如下:
高级加密标准(英语:Advanced Encryption Standard,缩写:AES),在密码学中又称Rijndael加密法,是美国联邦政府采用的一种区块加密标准。这个标准用来替代原先的DES,已经被多方分析且广为全世界所使用。经过五年的甄选流程,高级加密标准由美国国家标准与技术研究院(NIST)于2001年11月26日发布于FIPS PUB 197,并在2002年5月26日成为有效的标准。2006年,AES已然成为对称密钥加密中最流行的算法之一。
该算法为比利时密码学家Joan Daemen和Vincent Rijmen所设计,结合两位作者的名字,以Rijndael为名投稿高级加密标准的甄选流程。
引用GitHub上对于cryptopp(crypto++)的介绍,内容如下:
Crypto++ Library is a free C++ class library of cryptographic schemes.
2 安装cryptopp
GitHub地址:GitHub - weidai11/cryptopp: free C++ class library of cryptographic schemes
官方网站: Crypto++ Library 8.9 | Free C++ Class Library of Cryptographic Schemes
本文直接使用yum方式安装cryptopp(在epel源中已经包含了cryptopp),命令如下:
yum install cryptopp-devel.x86_64
3 示例代码
本章介绍在ECB模式、16字节长度的key、PKCS7填充方式场景下,使用AES算法进行加解密的示例代码。
示例代码(aes_test1.cpp)的内容如下:
#include <iostream>
#include <string>
#include "hex.h"
#include "aes.h"
#include "modes.h"
using namespace CryptoPP;
using namespace std;
int main(int argc, char* argv[])
{
// use default key length 16 bytes
byte key[AES::DEFAULT_KEYLENGTH] = "abcd1234";
// string to be encrypted
string strPlain = "ECB Mode Test";
// cipher string
string strCipher;
// encoded string
string strEncoded;
// recovered string, should be same with strPlain
string strRecovered;
try
{
cout << "key is: " << key << endl;
cout << "plain is: " << strPlain << endl;
// encrypt with ECB mode
ECB_Mode< AES >::Encryption e;
e.SetKey(key, sizeof(key));
// encrypt here
// The StreamTransformationFilter adds padding as required, use PKCS_PADDING(PKCS7Padding) default.
// ECB and CBC Mode must be padded to the block size of the cipher.
StringSource(strPlain, true,
new StreamTransformationFilter(e,
new StringSink(strCipher) // StringSink
) // StreamTransformationFilter
); // StringSource
}
catch (const Exception& e)
{
cerr << e.what() << endl;
exit(1);
}
// print cipher string
strEncoded.clear();
StringSource(strCipher, true,
new HexEncoder(
new StringSink(strEncoded) // StringSink
) // HexEncoder
); // StringSource
cout << "cipher is: " << strEncoded << endl;
try
{
// decrypt with ECB mode
ECB_Mode< AES >::Decryption d;
d.SetKey(key, sizeof(key));
// The StreamTransformationFilter removes padding as required.
StringSource s(strCipher, true,
new StreamTransformationFilter(d,
new StringSink(strRecovered) // StringSink
) // StreamTransformationFilter
); // StringSource
cout << "recovered string is: " << strRecovered << endl;
}
catch(const Exception& e)
{
cerr << e.what() << endl;
exit(1);
}
return 0;
}
编译并执行上述代码,结果如下:
在上述结果中可以看到,通过调用相关接口,实现了AES算法的加解密操作。
说明:可以通过对比“示例代码”和“网上一些在线AES加解密网站”的加密结果,来检验示例程序的加解密操作是否正确。