CryptoPP加密算法库使用

#include "include/cryptlib.h"
#include "include/aes.h"
#include "include/osrng.h"
#include "include/modes.h"
#include "include/base64.h"
#include "include/files.h"
#include "include/filters.h"
#include "include/default.h"
#include "include/hex.h"
#include "include/rsa.h"
#include "include/randpool.h"


using namespace CryptoPP;
using namespace std;

string encryptStr_ECB_AES(std::string sKey, string strPlainText)
{
	string outstr;
	//填key    
	SecByteBlock key(AES::MAX_KEYLENGTH);
	memset(key, 0x30, key.size());
	sKey.size() <= AES::MAX_KEYLENGTH ? memcpy(key, sKey.c_str(), sKey.size()) : memcpy(key, sKey.c_str(), AES::MAX_KEYLENGTH);
	AES::Encryption aesEncryption((byte *)key, AES::MAX_KEYLENGTH);
	ECB_Mode_ExternalCipher::Encryption ecbEncryption(aesEncryption);
	StreamTransformationFilter ecbEncryptor(ecbEncryption, new HexEncoder(new StringSink(outstr)));
	ecbEncryptor.Put((byte *)strPlainText.c_str(), strlen(strPlainText.c_str()));
	ecbEncryptor.MessageEnd();
	return outstr;
}

string decryptStr_ECB_AES(string sKey, string cipherText)
{
	std::string outstr;
	//填key  
	SecByteBlock key(AES::MAX_KEYLENGTH);
	memset(key, 0x30, key.size());
	sKey.size() <= AES::MAX_KEYLENGTH ? memcpy(key, sKey.c_str(), sKey.size()) : memcpy(key, sKey.c_str(), AES::MAX_KEYLENGTH);
	ECB_Mode<AES>::Decryption ecbDecryption((byte *)key, AES::MAX_KEYLENGTH);
	HexDecoder decryptor(new StreamTransformationFilter(ecbDecryption, new StringSink(outstr)));
	decryptor.Put((byte *)cipherText.c_str(), strlen(cipherText.c_str()));
	decryptor.MessageEnd();
	return outstr;
}

// 使用AES(CBC模式)加密,返回base64编码的数据
string encryptStr_CBC_AES(const string &plain, const string &key, const string &iv) 
{
	string cipher;
	try
	{
		CBC_Mode< AES >::Encryption e;
		e.SetKeyWithIV((byte*)key.c_str(), key.size(), (byte*)iv.c_str());
		StringSource s(plain, true, new StreamTransformationFilter(e, new StringSink(cipher)));
	}
	catch (const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
	}
	string encoded;
	StringSource(cipher, true,new Base64Encoder(new StringSink(encoded))); // StringSource
	return encoded;
}
// 使用AES(CBC模式)解密,encode为base64编码的密文
string decryptStr_CBC_AES(const string &encode, const string &key, const string &iv)
{
	string encodeByte;
	StringSource(encode, true, new Base64Decoder(new StringSink(encodeByte)));

	string recovered;
	try
	{
		CBC_Mode< AES >::Decryption d;
		d.SetKeyWithIV((byte*)key.c_str(), key.size(), (byte*)iv.c_str());
		StringSource s(encodeByte, true,new StreamTransformationFilter(d,new StringSink(recovered))); // StringSource
	}
	catch (const CryptoPP::Exception& e)
	{
		cerr << e.what() << endl;
	}
	return recovered;
}


void encrytFile_ECB_AES(const string& strPwd, const string& strInFileName, const string& strOutFileName)
{
	ECB_Mode<AES>::Encryption aesEncryptor;
	aesEncryptor.SetKey((CryptoPP::byte*)strPwd.c_str(), strPwd.size());
	FileSource(strInFileName.c_str(), true, new StreamTransformationFilter(aesEncryptor, new FileSink(strOutFileName.c_str())));
}

void decrytFile_ECB_AES(const string& strPwd, const string& strDecFileName, const string& strOutFileName)
{
	ECB_Mode<AES>::Decryption aesDecryptor;
	aesDecryptor.SetKey((CryptoPP::byte*)strPwd.c_str(), strPwd.size());
	FileSource(strDecFileName.c_str(), true, new StreamTransformationFilter(aesDecryptor, new FileSink(strOutFileName.c_str())));
}

//根据长度生成公钥和私钥,并分别保存到pubFilename文件和privFilename文件
void Generate_Key_RSA(unsigned int keyLength, const char *privFilename, const char *pubFilename)
{
	AutoSeededRandomPool rng;
	InvertibleRSAFunction privkey;
	privkey.GenerateRandomWithKeySize(rng, keyLength);

	Base64Encoder privkeysink(new FileSink(privFilename));  //"privkey.txt"
	privkey.DEREncode(privkeysink);
	privkeysink.MessageEnd();

	RSAFunction pubkey(privkey);
	Base64Encoder pubkeysink(new FileSink(pubFilename));  //"pubkey.txt"
	pubkey.DEREncode(pubkeysink);
	pubkeysink.MessageEnd();
}

void PrintFileContent(const string& strFile, int mode)
{
	ifstream inFile;
	inFile.open(strFile);
	assert(inFile.is_open());
	string strContent;
	while (getline(inFile, strContent))
	{
		if (0==mode)//原文内容
		{
			cout << "Source content:" << strContent << endl;
		}
		else if (1==mode)//加密内容
		{
			cout << "Encrypt content:" << strContent << endl;
		}
		else if (2==mode)//恢复加密后的内容
		{
			cout << "recover Encrypt content:" << strContent << endl;
		}
	}
	inFile.close();
}

void PrintStrContent(const string& strContent,int mode)
{
	if (0==mode)
	{
		cout << "Source string:" << strContent << endl;
	}
	else if (1==mode)
	{
		cout << "Cipher string:" << strContent << endl;
	}
	else if (2==mode)
	{
		cout << "Recover string:" << strContent << endl;
	}
}

void PrintKey(const string& strFile, int mode)
{
	ifstream inFile;
	inFile.open(strFile);
	assert(inFile.is_open());
	string strContent;
	string strTmp;
	while (getline(inFile, strTmp))
	{
		strContent += strTmp;
	}
	inFile.close();

	if (0 == mode)//公钥
	{

		cout << "私钥:" << strContent << endl;
	}
	else if (1 == mode)//私钥
	{
		cout << "公钥:" << strContent << endl;
	}
}
void PrintFile_RSA(const string& strFile, int mode)
{
	ifstream inFile;
	inFile.open(strFile);
	assert(inFile.is_open());
	string strContent;
	string strTmp;
	while (getline(inFile, strTmp))
	{
		strContent += strTmp;
	}
	inFile.close();

	if (0 == mode)//公钥
	{

		cout << "加密内容(RSA):" << strContent << endl;
	}
	else if (1 == mode)//私钥
	{
		cout << "公钥:" << strContent << endl;
	}
}

//把字符串strPlain中的内容用public_key文件中的公钥加密数据并保存到encrypted_File中。
void encryptString_RSA(const string &strPlain, const char *public_key, const char *encrypted_File)
{
	RSAES_OAEP_SHA_Encryptor pubkey(FileSource(public_key, true, new Base64Decoder));

	SecByteBlock sbbCipherText(pubkey.CiphertextLength(strPlain.size()));
	AutoSeededRandomPool rng;
	pubkey.Encrypt(rng, (byte const*)strPlain.data(), strPlain.size(), sbbCipherText.begin());
	FileSink(encrypted_File).Put(sbbCipherText.begin(), sbbCipherText.size());
}
//用private_key文件中的私钥解密encrypted_File文件中的加密内容,并返回解密内容。
string decryptString_RSA(const char *private_key, const char *encrypted_File)
{
	string strContents, recovered;
	FileSource(encrypted_File, true, new StringSink(strContents));
	AutoSeededRandomPool rng;
	RSAES_OAEP_SHA_Decryptor privkey(FileSource(private_key, true, new Base64Decoder));
	StringSource(strContents, true, new PK_DecryptorFilter(rng, privkey, new StringSink(recovered)));
	return recovered;
}

int main()
{
	int n = 1 << 16;
	cout << n << endl;

	cout << "--------ECB_AES模式加密文件-----------" << endl;
	string strPwd = "9d906013b5e97a0d";
	string strSourceFile = "./test.txt";
	string strEncryptFile = "./encrypt_test.txt";
	string strDecryptFile = "./decrypt_test.txt";
	encrytFile_ECB_AES(strPwd, strSourceFile, strEncryptFile);
	decrytFile_ECB_AES(strPwd, strEncryptFile, strDecryptFile);
	PrintFileContent(strSourceFile, 0);
	PrintFileContent(strEncryptFile, 1);
	PrintFileContent(strDecryptFile, 2);
	cout << "\t" << endl;
	cout << "--------ECB_AES模式加密字符串-----------" << endl;
	string strText = "hello,hikvision!";
	string strCipherText = encryptStr_ECB_AES(strPwd, strText);
	string strRecoverText = decryptStr_ECB_AES(strPwd, strCipherText);
	PrintStrContent(strText, 0);
	PrintStrContent(strCipherText, 1);
	PrintStrContent(strRecoverText, 2);
	cout << "\t" << endl;
	cout << "--------CBC_AES模式加密字符串-----------" << endl;
	string strKey = "9d906013b5e97a0d";
	string strIV = "Zx8dG46ax3Mc8Mj2";
	string strEncrypt_CBC = encryptStr_CBC_AES(strText, strKey, strIV);
	cout << "AES(CBC)加密结果:" << strEncrypt_CBC << endl;
	string strDecrypt_CBC = decryptStr_CBC_AES(strEncrypt_CBC, strKey, strIV);
	cout << "AES(CBC)解密结果:" << strDecrypt_CBC << endl;
	cout << "\t" << endl;
	cout << "--------RSA非对称模式加密字符串-----------" << endl;
	string strPrivateKey = "privkey.txt";
	string strPublickKey = "pubkey.txt";
	uint8_t seed[] = "hivision12345";
	string strEncryFile = "./encrypt_RSA.txt";
	cout << "--------生成RSA秘钥对-----------" << endl;
	Generate_Key_RSA(1024, strPrivateKey.c_str(), strPublickKey.c_str());
	PrintKey(strPrivateKey, 0);
	PrintKey(strPublickKey, 1);
	encryptString_RSA(strText, strPublickKey.c_str(), strEncryFile.c_str());
	cout << "原始字符:" << strText << endl;
	PrintFile_RSA(strEncryFile, 0);
	string strDecryptString = decryptString_RSA(strPrivateKey.c_str(), strEncryFile.c_str());
	cout << "解密字符(RSA):" << strDecryptString << endl;
	getchar();
	return 0;
}

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值