C++或C 实现AES ECB模式加密解密,支持官方验证
本文主要介紹 AES 算法的加解密方法。本文使用的語言為 C++,調(diào)用的 AES 庫為:cryptopp。
1 概述
AES 加密算法的介紹如下(摘自 WikiPedia):
高級加密標(biāo)準(zhǔn)(英語:Advanced Encryption Standard,縮寫:AES),在密碼學(xué)中又稱 Rijndael 加密法,是美國聯(lián)邦政府采用的一種區(qū)塊加密標(biāo)準(zhǔn)。這個(gè)標(biāo)準(zhǔn)用來替代原先的 DES,已經(jīng)被多方分析且廣為全世界所使用。經(jīng)過五年的甄選流程,高級加密標(biāo)準(zhǔn)由美國國家標(biāo)準(zhǔn)與技術(shù)研究院(NIST)于2001年11月26日發(fā)布于FIPS PUB 197,并在2002年5月26日成為有效的標(biāo)準(zhǔn)。2006年,AES 已然成為對稱密鑰加密中最流行的算法之一。
該算法為比利時(shí)密碼學(xué)家 Joan Daemen 和 Vincent Rijmen 所設(shè)計(jì),結(jié)合兩位作者的名字,以 Rijndael 為名投稿高級加密標(biāo)準(zhǔn)的甄選流程。
2 cryptopp安裝
cryptopp:Crypto++ Library is a free C++ class library of cryptographic schemes.?
C++頭文件GitHub地址:https://github.com/weidai11/cryptopp
C++頭文件官方網(wǎng)站:?https://cryptopp.com/
3 示例代碼
本節(jié)介紹在?ECB 模式、16字節(jié)長度的 key、PKCS7填充方式的場景下,使用?AES 算法進(jìn)行加解密的示例代碼。
示例代碼(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 bytesbyte key[AES::DEFAULT_KEYLENGTH] = "abcd1234";// string to be encryptedstring strPlain = "ECB Mode Test";// cipher stringstring strCipher;// encoded stringstring strEncoded;// recovered string, should be same with strPlainstring strRecovered;try{cout << "key is: " << key << endl;cout << "plain is: " << strPlain << endl;// encrypt with ECB modeECB_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 stringstrEncoded.clear();StringSource(strCipher, true,new HexEncoder(?new StringSink(strEncoded) // StringSink) // HexEncoder); // StringSourcecout << "cipher is: " << strEncoded << endl;try{// decrypt with ECB modeECB_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); // StringSourcecout << "recovered string is: " << strRecovered << endl;}catch(const Exception& e){cerr << e.what() << endl;exit(1);}return 0; }編譯并執(zhí)行上述代碼,結(jié)果如下:
在上述結(jié)果中可以看到,我們通過調(diào)用接口,完成了?AES 算法的加解密操作。
說明:我們可以通過對比“示例代碼的加密結(jié)果”和“網(wǎng)上一些在線 aes 加解密網(wǎng)站的加密結(jié)果”,來驗(yàn)證我們的加密操作是否正確:http://tool.chacuo.net/cryptaes。
總結(jié)
以上是生活随笔為你收集整理的C++或C 实现AES ECB模式加密解密,支持官方验证的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Docker Registry 删除镜像
- 下一篇: Windows MinGW配置C、C++