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

这里记录使用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/

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值