利用crypto++库实现AES加密算法

利用crypto++库实现AES加/解密字符串,文件

MyAES.h:

/*
 * MyAES.h
 *
 *  Created on: 2013-3-6
 *      Author: hust
 */

#ifndef MYAES_H_
#define MYAES_H_

#include <cryptopp/aes.h>
#include <cryptopp/default.h>
#include <cryptopp/filters.h>
#include <cryptopp/files.h>
#include <cryptopp/osrng.h>

#include <stdlib.h>
#include <string>
#include <iostream>

using namespace CryptoPP;
using namespace std;

class MyAES
{
public:
	byte * key;
	byte * iv;
	int key_length;

	MyAES();
	MyAES(byte * key, byte *iv, int length);
	~MyAES();

	//use the key to encrypt the plainText and return the cipher
	string Encrypt(const string &plainText);
	//use the same key to decrypt the cipher and return the recover
	string Decrypt(const string &cipher);
	//use the key to encrypt the file
	bool EncryptFile(const string & inFilename, const string & outFilename);
	//use the key to decyrpt the file
	bool DecryptFile(const string & DecFilename,
			const string & recoverFilename);
	void GenerateKey();
	void SetKey(byte * key, byte * iv, int length);
};

#endif /* MYAES_H_ */

MyAES.cpp:

//============================================================================
// Name        : MyAES.cpp
// Author      : hust
// Version     :
// Copyright   : 1.0
// Description : 本类将AES的加密,解密函数封装,直接调用即可对string进行加密or解密
//				 另外,构造MyAES类的时候,传入参数key, iv, key_length
//				 待解决:编写一个生成密钥的函数,即需要 KeyGenerate(Random random);
// reference   : http://www.codeproject.com/Articles/21877/Applied-Crypto-Block-Ciphers
//============================================================================

#include "MyAES.h"
#include <time.h>
MyAES::MyAES()
{

}

MyAES::MyAES(byte * key1, byte * iv1, int key_length1)
{
	SetKey(key1, iv1, key_length1);
}

MyAES::~MyAES()
{

}

void MyAES::GenerateKey()
{
	AutoSeededRandomPool rnd;
	byte key1[AES::DEFAULT_KEYLENGTH];
	rnd.GenerateBlock(key1, AES::DEFAULT_KEYLENGTH);

	// Generate a random IV
	byte iv1[AES::BLOCKSIZE];
	rnd.GenerateBlock(iv1, AES::BLOCKSIZE);

	SetKey(key1, iv1, 16);
}

void MyAES::SetKey(byte * key1, byte * iv1, int length1)
{
	this->key = key1;
	this->iv = iv1;
	this->key_length = length1;
}

/*
 * Description: use key to encrypt 'plainText', return the cipher
 * Input:
 * 	plainText: the string need to be encrypted
 * OutPUt:
 * 	return the cipher
 */
string MyAES::Encrypt(const string &plainText)
{
	string cipher;
	CBC_Mode<AES>::Encryption aesEncryptor(key, key_length, iv);
//	AESEncryption aesEncryptor; //加密器
//	aesEncryptor.SetKey( key, key_length );  //设定加密密钥
	StringSource(plainText, true,
			new StreamTransformationFilter(aesEncryptor,
					new StringSink(cipher)));
	return cipher;
}

/*
 * Description: use the same key to decrypt "cipher" and return the plainText
 * Input:
 * 	cipher: the string to be decrypted
 * Output:
 * 	return the recover
 */
string MyAES::Decrypt(const string & cipher)
{
	string recover;
	CBC_Mode<AES>::Decryption aesDecryptor(key, key_length, iv);
	//AESDecryption aesDecryptor; //解密器
	//aesDecryptor.SetKey( key, key_length );  //设定加密密钥
	StringSource(cipher, true,
			new StreamTransformationFilter(aesDecryptor,
					new StringSink(recover)));
	return recover;
}

/*
 * Description: use the key to encrypt the 'inFilename' and store the cipher in 'outFilname'
 * Input:
 *  inFilename: the file need to be encrypted!
 *  outFilename: the encrypted file
 * OutPut:
 *  if encrypt success, return true, or return false
 * Others: the function should delete the file : 'inFilename', however I note it
 */
bool MyAES::EncryptFile(const string & inFilename, const string & outFilename)
{
	// check if the file 'inFilename' exists.
	if (access(inFilename.c_str(), 0) == -1)
	{
		cout << "The file " << inFilename << " is not exist! " << endl;
		return false;
	}
	// file exists, the encrypt the file
	CBC_Mode<AES>::Encryption aesEncryptor(key, key_length, iv);

	FileSource(inFilename.c_str(), true,
			new StreamTransformationFilter(aesEncryptor,
					new FileSink(outFilename.c_str())));
	// remove the file 'inFilename'
	// if(remove(inFilename) == 0) cout << "remove file succeed! " << endl;
	// 		else cout << "fail to remove the file " << inFilname << endl;
	// use function remove(), you have to add #include <cstdio> in the .h file
	return true;
}

/*
 * Description: use the same key to decrypt the 'decFilename' and create recoverFile
 * Input:
 * 	decFilename: the encrypted file name
 * 	recoverFilename: the decrypted file name
 * OutPut:
 * 	if decrypted the file successful, return true, else return false
 * Others: we should also delete the file 'decFilename'
 */
bool MyAES::DecryptFile(const string & decFilename,
		const string & recoverFilename)
{
	// check if the file 'decFilename' exists!
	if (access(decFilename.c_str(), 0) == -1)
	{
		cout << "The file " << decFilename << " is not exist! " << endl;
		return false;
	}
	// exist , then decrypt the file
	CBC_Mode<AES>::Decryption aesDecryptor(key, key_length, iv);
	FileSource(decFilename.c_str(), true,
			new StreamTransformationFilter(aesDecryptor,
					new FileSink(recoverFilename.c_str())));
	return true;
}



 int main() {

	 //	byte key[]	= {0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,	0x01,0x02, 0x03,0x04,0x05,0x06,0x07,0x08};
	 //	//AES::DEFAULT_KEYLENGTH
	 //	byte iv[]	= {0x01,0x02,0x03,0x03,0x03,0x03,0x03,0x03,	0x03,0x03, 0x01,0x02,0x03,0x03,0x03,0x03};
	 //	int keysize = 16;


	 // generate the key
	 AutoSeededRandomPool rnd;
	 byte key[AES::DEFAULT_KEYLENGTH];
	 rnd.GenerateBlock( key, AES::DEFAULT_KEYLENGTH);

	 // Generate a random IV
	 byte iv[AES::BLOCKSIZE];
	 rnd.GenerateBlock(iv, AES::BLOCKSIZE);

	 int keysize = 16;

	 string plainText = "Hello World!";

	 clock_t start , finish;
	 double duration;
	 start = clock();

	 MyAES aes(key, iv, keysize);

	 cout << "AES parameters: " << endl;
	 cout << "The algorithm name is : " << AES::StaticAlgorithmName() << endl;
	 cout << "The iv is : " << aes.iv << endl;
	 cout << "The key is : " << aes.key << endl;
	 cout << "The key length is : " << aes.key_length << endl;

	 string cipher = aes.Encrypt(plainText);
	 cout << "The cipher is : " << cipher << endl;

	 string recover = aes.Decrypt(cipher);
	 cout << "The recover is : " << recover << endl;

	 cout << "=====================" << endl;

	 // encrypt the file and decrypt it
	 string inFilename = "aesTest";
	 string outFilename = "aesEncrypt";
	 string recoverFilename = "aesRecover";

	 if(aes.EncryptFile(inFilename, outFilename)){
	 cout << "*__*" << endl << "Encrypt succeed!" << endl;
	 if(aes.DecryptFile(outFilename, recoverFilename)){
	 cout << "*__*" << endl << "Recover succeed!" << endl;
	 } else
	 cout << ")__(" << endl << "Recover failed!" << endl;
	 } else
	 cout << ")__(" << endl << "Encrypt failed!" << endl;



	 finish = clock();
	 duration = (double)(finish - start) / CLOCKS_PER_SEC;
	 cout << "the cost is : " << duration << endl;

	 return 0;
 }

在linux系统中编译命令为:

g++ MyAES.cpp -o test -lpthread -lcryptopp

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏技术博文

php des 加密解密实例

des加密是对称加密中在互联网应用的比较多的一种加密方式,php 通过mcrypt扩展库来支持des加密,要在Php中使用des加密,需要先安装mcrypt扩展...

577100
来自专栏编程之旅

AES加密——Java与iOS的解决方案

该算法为比利时密码学家Joan Daemen和Vincent Rijmen所设计,结合两位作者的名字,以Rijndael为名投稿高级加密标准的甄选流程。(Rij...

73260
来自专栏三流程序员的挣扎

RxJava 创建操作符

内部触发对 Observer 的 onNext 方法的调用,just 中传递的参数将直接在 onNext 方法中接收到,参数的类型要和 Observer 的泛型...

26210
来自专栏晓晨的专栏

.NET Core 使用RSA算法 加密/解密/签名/验证签名

59420
来自专栏FreeBuf

非对称算法之RSA的签名剖析

数字签名,就是只有信息的发送者才能产生的别人无法伪造的一段数字串,这段数字串同时也是对信息的发送者发送信息真实性的一个有效证明。 不清楚的请自行科普数字签名。本...

28730
来自专栏freesan44

三重Des对称加密在Android、Ios 和Java 平台的实现

如今手机app五彩缤纷,确保手机用户的数据安全是开发人员必须掌握的技巧,下面通过实例介绍DES在android、ios、java平台的使用方法;

16710
来自专栏编程微刊

三分钟教你学会如何将密文解码成明文

19640
来自专栏小工匠技术圈

【小工匠聊密码学】--对称加密--3DES

  3DES(或称为Triple DES)是三重数据加密算法(TDEA,Triple Data Encryption Algorithm)块密码的通称。它相当于...

12020
来自专栏Hongten

PBE_Password-based encryption(基于密码加密)_项目中你也可以有

中说道了PBE——Password-based encryption(基于密码加密)。我也做测试了一下,现在把我做的效果给大家演示一下:

11210
来自专栏与神兽党一起成长

在XMLSignature中使用BouncyCastle做RSA

There is an article shows demo code for making XMLSignature by using Java XML Di...

18120

扫码关注云+社区

领取腾讯云代金券