使用Crypto++的AES GCM对称加密

魏澄邈
2023-12-01

这里记录使用Crypto++的AES GCM对称加密的代码片段,可直接执行

运行环境:Windows, Visual Studio 2017

需安装Crypto++库,可使用cvpkg工具直接集成该库到visual Studio 中:

vcpkg install cryptopp:x64-windows

代码:

#pragma warning(disable : 4996)
#include <stdio.h>

#include <iostream>
#include <fstream>
#include <sstream>

#include <cryptopp/aes.h>
#include <cryptopp/filters.h>
#include <cryptopp/modes.h>

using namespace std;
using namespace CryptoPP;

byte key[CryptoPP::AES::DEFAULT_KEYLENGTH], iv[CryptoPP::AES::BLOCKSIZE];

void initKV()
{
	memset(key, 0x00, CryptoPP::AES::DEFAULT_KEYLENGTH);
	memset(iv, 0x00, CryptoPP::AES::BLOCKSIZE);


	// 或者也可以
	/*
	char tmpK[] = "1234567890123456";
	char tmpIV[] = "1234567890123456";
	for (int j = 0; j < CryptoPP::AES::DEFAULT_KEYLENGTH; ++j)
	{
		key[j] = tmpK[j];
	}
	for (int i = 0; i < CryptoPP::AES::BLOCKSIZE; ++i)
	{
		iv[i] = tmpIV[i];
	}
	*/
}



string encrypt(const char * plainText, size_t len_plainText)
{
	string cipherText;

	CryptoPP::AES::Encryption aesEncryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
	CryptoPP::CBC_Mode_ExternalCipher::Encryption cbcEncryption(aesEncryption, iv);
	CryptoPP::StreamTransformationFilter stfEncryptor(cbcEncryption, new CryptoPP::StringSink(cipherText));
	stfEncryptor.Put(reinterpret_cast<const unsigned char*>(plainText), len_plainText + 1);
	stfEncryptor.MessageEnd();

	/*string cipherTextHex;
	for (int i = 0; i < cipherText.size(); i++)
	{
		char ch[3] = { 0 };
		sprintf(ch, "%02x", static_cast<byte>(cipherText[i]));
		cipherTextHex += ch;
	}

	return cipherTextHex;*/

	return cipherText;
}





string decrypt(const char * cipherText, size_t cipherTextLen){
	string decryptedText;

	CryptoPP::AES::Decryption aesDecryption(key, CryptoPP::AES::DEFAULT_KEYLENGTH);
	CryptoPP::CBC_Mode_ExternalCipher::Decryption cbcDecryption(aesDecryption, iv);
	CryptoPP::StreamTransformationFilter stfDecryptor(cbcDecryption, new CryptoPP::StringSink(decryptedText));
	stfDecryptor.Put(reinterpret_cast<const unsigned char*>(cipherText), cipherTextLen);

	stfDecryptor.MessageEnd();

	return decryptedText;
}

int main()
{
	string text = "hello zhuzhu dashen dfjsldkfjljfweijrljskdfo9iew eworjwoeinmljsdf;jsdfo;ijdslfjsdjfsdflj!";
	cout << "text : " << text << endl;

	initKV();
	string cipherHex = encrypt(text.c_str(), text.length());
	//cout << "cipher : " << cipherHex << endl;

	string decryptedText = decrypt(cipherHex.c_str(), cipherHex.length());

	cout << "decrypted text = " << decryptedText << endl;

	return 0;
}

还可参考:
blog1

https://www.cryptopp.com/

 类似资料: