然后将-DCRYPTOPP_DISABLE_ASM-DCRYPTOPP_DISABLE_SSE2两个宏定义加到工程中,原因是crypto++内嵌了很多汇编,这个我们不需要。
#include "rc2.h"
using namespace CryptoPP;
//RC2加密解密类
class cRC2Test
{
public:
//设置key
static void setKey(const unsigned char* pKey);
//加密
static std::string encode(const std::string& rStr);
//解密
static std::string decode(const std::string& rStr);
private:
//加密RC2块
static void encodeBlock(unsigned char* pData,unsigned char* pOut);
//解密RC2块
static void decodeBlock(unsigned char* pData,unsigned char* pOut);
//RC2 key
static unsigned char sm_cKey[RC2::DEFAULT_KEYLENGTH];
//RC2加密类
static RC2Encryption sm_rcEncr;
//RC2解密类
static RC2Decryption sm_rcDecr;
};
cRC2Test.cpp
#include<vector>
#include<string>
using namespacestd;
//静态变量定义
unsigned char cRC2Test::sm_cKey[RC2::DEFAULT_KEYLENGTH] = {0,};
RC2EncryptioncRC2Test::sm_rcEncr;
RC2DecryptioncRC2Test::sm_rcDecr;
void cRC2Test::setKey(const unsigned char* pKey)
{
memset(sm_cKey, 0,sizeof(sm_cKey));
//保存key
memcpy(sm_cKey,pKey, RC2::DEFAULT_KEYLENGTH);
//对加密器与解密器设置key值
sm_rcEncr.SetKey(sm_cKey, RC2::DEFAULT_KEYLENGTH);
sm_rcDecr.SetKey(sm_cKey, RC2::DEFAULT_KEYLENGTH);
}
std::string cRC2Test::encode(const std::string& rStr)
{
size_t strIndex = 0;
size_t strLen =rStr.size();
//保存加密后的数据
vector<unsigned char> vBuffer;
//保存加密后的临时数据块
unsigned char rcBlock[RC2::BLOCKSIZE];
unsigned char *ptr = (unsigned char*)rStr.c_str();
//遍历字符串
while(strIndex <strLen) {
memset(rcBlock,0,RC2::BLOCKSIZE);
//加密一块数据
encodeBlock(&ptr[strIndex],rcBlock);
//保存加密结果
vBuffer.insert(vBuffer.end(),rcBlock,rcBlock+RC2::BLOCKSIZE);
strIndex += RC2::BLOCKSIZE;
}
return string(vBuffer.begin(),vBuffer.end());
}
std::string cRC2Test::decode(const std::string& rStr)
{
size_t strIndex = 0;
size_t strLen =rStr.size();
//保存解密后的数据
vector<unsigned char> vBuffer;
//保存解密后的临时数据块
unsigned char rcOut[32];
unsigned char *ptr = (unsigned char*)rStr.c_str();
//遍历字符串
while(strIndex <strLen) {
memset(rcOut,sizeof(rcOut));
//解密一块数据
decodeBlock(&ptr[strIndex],rcOut);
//保存解密结果
vBuffer.insert(vBuffer.end(),rcOut,rcOut+strlen((char*)rcOut));
strIndex += RC2::BLOCKSIZE;
}
return string(vBuffer.begin(),vBuffer.end());
}
voidcRC2Test::encodeBlock(unsigned char* pData,unsigned char* pOut)
{
sm_rcEncr.ProcessBlock(pData,pOut);
}
voidcRC2Test::decodeBlock(unsigned char* pData,unsigned char* pOut)
{
sm_rcDecr.ProcessBlock(pData,pOut);
}