Crypto++理论上可以在任何平台上编译,但是作者似乎是个Windows控,默认只生成静态库。当在Linux下编译的时候,需要打个patch给GNUmakefile,然后才能生成.so动态库。
补丁见这里,请爬梯子,注意安全~
http://groups.google.com/group/cryptopp-users/browse_thread/thread/6d37437aa40fc135?pli=1
对了,编译时候记得参数
-lcryptopp -lpthread
包装类RSATools
/* * RSATools.h * * Created on: 2010-3-24 * Description: 调用Crypto++进行RSA加密和解密 * Copyright: 2010 @ ICT Li Heyuan */ #ifndef RSATOOLS_H_ #define RSATOOLS_H_ #include <cryptopp/rsa.h> #include <cryptopp/osrng.h> using namespace CryptoPP; #include <string> using std::string; class RSATools { public: RSATools(unsigned int size = 1024); virtual ~RSATools(); //加密,使用public_key string encrypt(const string &plain); //解密,使用private_key string decrypt(const string &cipher); //获取public_key的e string getPublicExponent(); //获取public_key的n string getModulus(); private: /**随机种子*/ AutoSeededRandomPool _rng; /**rsa参数,含public/private key等*/ InvertibleRSAFunction _rsa_param; }; #endif /* RSATOOLS_H_ */
实现,重点
/* * RSATools.cpp * * Created on: 2010-3-24 * Description: * Copyright: 2010 @ ICT Li Heyuan */ #include "RSATools.h" #include <iostream> #include <sstream> using std::ostringstream; RSATools::RSATools(unsigned int size) { //初始化rsa参数 _rsa_param.GenerateRandomWithKeySize(_rng, size); } RSATools::~RSATools() { } string RSATools::encrypt(const string &plain) { string cipher; RSA::PublicKey public_key(_rsa_param); RSAES_OAEP_SHA_Encryptor encryptor(public_key); StringSource(plain, true, new PK_EncryptorFilter(_rng, encryptor, new StringSink(cipher))); return cipher; } string RSATools::decrypt(const string &cipher) { string recovered; RSA::PrivateKey private_key(_rsa_param); RSAES_OAEP_SHA_Decryptor decryptor(private_key); StringSource(cipher, true, new PK_DecryptorFilter(_rng, decryptor, new StringSink(recovered))); return recovered; } string RSATools::getPublicExponent() { ostringstream os; os << _rsa_param.GetPublicExponent(); string ret = os.str(); ret.erase(ret.size() - 1); return ret; } string RSATools::getModulus() { ostringstream os; os << _rsa_param.GetModulus(); string ret = os.str(); ret.erase(ret.length() - 1); return ret; }
测试驱动
/* * main.cc * * Created on: 2010-3-24 * Description: * Copyright: 2010 @ ICT Li Heyuan */ #include "RSATools.h" #include <string> #include <iostream> using std::string; using std::cout; using std::endl; int main() { RSATools rsa(1024); cout << "公钥n " << rsa.getModulus() << endl; cout << "公钥e " << rsa.getPublicExponent() << endl; string plain("加密我把!!!!!!!"), cliper, recovered; cout << "原文 " << plain << endl; cliper = rsa.encrypt(plain); recovered = rsa.decrypt(cliper); cout << "还原 " << recovered << endl; return 0; }
Crypto++还是非常好用的,不过这个编译完的动态库居然有17Mb…好大呀,也不知怎么减肥,呵呵。。