基于Crypto++的aes 字符串加解密实现
esaes.h:
#ifndef ESAES_H
#define ESAES_H
#include <cryptopp/aes.h>
#include <iostream>
#include <string>
using namespace std;
using namespace CryptoPP;
class ESAes
{
public:
ESAes();
string encrypt();
string decrypt();
void test();
void Setkey(string inkey);
void Setcleartext(string incleartext);
void Setciphertext(string inciphertext);
private:
string cleartext;
string ciphertext;
string key;
unsigned char inBlock[AES::BLOCKSIZE];
};
#endif // ESAES_H
esaes.cpp
string ESAes::encrypt()
{
//加密
AESEncryption aesEncryptor; //加密器
unsigned char aesKey[AES::DEFAULT_KEYLENGTH]=""; //密钥
strcpy((char*)aesKey, key.c_str());
unsigned char inBlock[AES::BLOCKSIZE]="";// = cleartext; //要加密的数据块
strcpy((char*)inBlock,cleartext.c_str());
unsigned char outBlock[AES::BLOCKSIZE]; //加密后的密文块
unsigned char xorBlock[AES::BLOCKSIZE]; //必须设定为全零
memset( xorBlock, 0, AES::BLOCKSIZE ); //置零
aesEncryptor.SetKey( aesKey, AES::DEFAULT_KEYLENGTH ); //设定加密密钥
//aesEncryptor.SetKey();
aesEncryptor.ProcessAndXorBlock( inBlock, xorBlock, outBlock ); //加密
//以16进制显示加密后的数据
//for( int i=0; i<16; i++ ) {
//cout << hex << (int)outBlock[i] << " ";
//}
//这里将字符数组转换成string类型
ciphertext=(char*)outBlock;
return ciphertext;
}
string ESAes::decrypt()
{
//解密
AESDecryption aesDecryptor;
unsigned char aesKey[AES::DEFAULT_KEYLENGTH]=""; //密钥
strcpy((char*)aesKey, key.c_str());
unsigned char plainText[AES::BLOCKSIZE];
//unsigned char outBlock[AES::BLOCKSIZE]=ciphertext; //加密后的密文块
unsigned char outBlock[AES::BLOCKSIZE]="";
strcpy((char*)outBlock,ciphertext.c_str());
unsigned char xorBlock[AES::BLOCKSIZE]; //必须设定为全零
memset( xorBlock, 0, AES::BLOCKSIZE ); //置零
aesDecryptor.SetKey( aesKey, AES::DEFAULT_KEYLENGTH );
//细心的朋友注意到这里的函数不是之前在DES中出现过的:ProcessBlock,
//而是多了一个Xor。其实,ProcessAndXorBlock也有DES版本。用法跟AES版本差不多。
//笔者分别在两份代码中列出这两个函数,有兴趣的朋友可以自己研究一下有何差异。
aesDecryptor.ProcessAndXorBlock( outBlock, xorBlock, plainText );
//for( int i=0; i<16; i++ )
//{
// cout << plainText[i];
//}
cleartext=(char*)plainText;
//cout << endl;
return cleartext;
}
void ESAes::Setkey(string inkey)
{
//设置密钥
this->key=inkey;
}
void ESAes::Setcleartext(string incleartext)
{
this->cleartext=incleartext;
}
void ESAes::Setciphertext(string inciphertext)
{
ciphertext=inciphertext;
}
posted on 2017-06-11 17:13 LittleRookie_Avalon 阅读(438) 评论(0) 收藏 举报
浙公网安备 33010602011771号