本文摘自 小楼一夜听春雨得博客: http://hi.baidu.com/magic475/blog/item/e8b82139020ae622b8998f96.html
使用Crypto++5.5.2完成RSA加解密
2008-07-21 12:47
忙活了一周,基本完成了Crypto++库中关于RSA加解密的API封装!这一周里,查了很多Crypto++的相关资料,感觉这方面的内容乏善可陈,或者太简单,或者太笼统!本文希望能给使用Crypto++的朋友带来一些帮助,主要还是源代码了,实在没有时间码文字!在测试过程中,感觉Crypto++还是非常高效的,期待更多的人使用Crypto++。此外,Crypto++的源代码极富研究价值,是深入学习C++的经典材料!爱好 C++的你,千万别错过了~

本文提供的C++源代码已在Redhat Enterprise Server 5.0和Windows XP平台编译链接成功,使用的编译器分别是g++ 3.4.6、Visual C++ 6.0 (SP 6)。由于两个平台的代码差别不大,仅提供Linux平台的代码!如果你需要Windows平台的代码,可以向我索取,留下你的邮件地址即可!如果你在使用过程中,遇到任何问题,也欢迎你给我留言!

源程序主要包括五个文件:MyRSA.h、 MyRSA.cpp、Main.h、Main.cpp、makefile;两个目录:lib目录包含libcryptopp.a,include目录包含Crypto++5.5.2中的所有.h头文件。对了,上述五个文件与lib,include目录在同一层目录!需要说明的是,makefile是借用了一个兄弟的,忘记名字了,不好意思:-)

哈,还是贴代码吧!

/************************** MyRSA.h ********************************/ #ifndef __MYRSA_H__ #define __MYRSA_H__ #include <string> #include "files.h" #include "filters.h" #include "hex.h" #include "randpool.h" #include "rsa.h" using namespace std; using namespace CryptoPP; class CMyRSA { public: CMyRSA(void); virtual ~CMyRSA(void); //You must set the KeyLength 512, 1024, 2048 ... void GenerateKey(const unsigned int KeyLength, const char *Seed, RSAES_OAEP_SHA_Decryptor &Priv, RSAES_OAEP_SHA_Encryptor &Pub); void GenerateKey(const unsigned int KeyLength, const char *Seed, string &strPriv, string &strPub); //use public key to encrypt void EncryptString(const RSAES_OAEP_SHA_Encryptor &Pub, const char *Seed, const string &Plaintext, string &Ciphertext); void EncryptString(const string &strPub, const char *Seed, const string &Plaintext, string &Ciphertext); //use private key to decrypt void DecryptString(const RSAES_OAEP_SHA_Decryptor &Priv, const string &Ciphertext, string &Plaintext); void DecryptString(const string &strPriv, const string &Ciphertext, string &Plaintext); private: static RandomPool & RNG(void); private: static RandomPool m_sRandPool; }; #endif /* End of __MYRSA_H__ */ /************************** MyRSA.cpp ********************************/ #include "MyRSA.h" CMyRSA::CMyRSA() { } CMyRSA::~CMyRSA(void) { } void CMyRSA::GenerateKey(const unsigned int KeyLength, const char *Seed, RSAES_OAEP_SHA_Decryptor &Priv, RSAES_OAEP_SHA_Encryptor &Pub) { RandomPool RandPool; RandPool.IncorporateEntropy((byte *)Seed, strlen(Seed)); //generate private key Priv = RSAES_OAEP_SHA_Decryptor(RandPool, KeyLength); //generate public key using private key Pub = RSAES_OAEP_SHA_Encryptor(Priv); } void CMyRSA::GenerateKey(const unsigned int KeyLength, const char *Seed, string &strPriv, string &strPub) { RandomPool RandPool; RandPool.IncorporateEntropy((byte *)Seed, strlen(Seed)); //generate private key RSAES_OAEP_SHA_Decryptor Priv(RandPool, KeyLength); HexEncoder PrivateEncoder(new StringSink(strPriv));//本博客作者加:就为了这句代码整整找了1天! Priv.DEREncode(PrivateEncoder); PrivateEncoder.MessageEnd(); //generate public key using private key RSAES_OAEP_SHA_Encryptor Pub(Priv); HexEncoder PublicEncoder(new StringSink(strPub)); Pub.DEREncode(PublicEncoder); PublicEncoder.MessageEnd(); } void CMyRSA::EncryptString(const RSAES_OAEP_SHA_Encryptor &Pub, const char *Seed, const string &Plaintext, string &Ciphertext) { RandomPool RandPool; RandPool.IncorporateEntropy((byte *)Seed, strlen(Seed)); int MaxMsgLength = Pub.FixedMaxPlaintextLength(); for (int i = Plaintext.size(), j=0; i > 0; i -= MaxMsgLength, j += MaxMsgLength) { string PartPlaintext = Plaintext.substr(j, MaxMsgLength); string PartCiphertext; StringSource(PartPlaintext, true, new PK_EncryptorFilter(RandPool, Pub, new HexEncoder(new StringSink(PartCiphertext)))); Ciphertext += PartCiphertext; } } void CMyRSA::EncryptString(const string &strPub, const char *Seed, const string &Plaintext, string &Ciphertext) { StringSource PublicKey(strPub, true, new HexDecoder); RSAES_OAEP_SHA_Encryptor Pub(PublicKey); RandomPool RandPool; RandPool.IncorporateEntropy((byte *)Seed, strlen(Seed)); int MaxMsgLength = Pub.FixedMaxPlaintextLength(); for (int i = Plaintext.size(), j=0; i > 0; i -= MaxMsgLength, j += MaxMsgLength) { string PartPlaintext = Plaintext.substr(j, MaxMsgLength); string PartCiphertext; StringSource(PartPlaintext, true, new PK_EncryptorFilter(RandPool, Pub, new HexEncoder(new StringSink(PartCiphertext)))); Ciphertext += PartCiphertext; } } void CMyRSA::DecryptString(const RSAES_OAEP_SHA_Decryptor &Priv, const string &Ciphertext, string &Plaintext) { //indicate the ciphertext in hexcode int CiphertextLength = Priv.FixedCiphertextLength() * 2; for (int i = Ciphertext.size(), j=0; i > 0; i -= CiphertextLength, j += CiphertextLength) { string PartCiphertext = Ciphertext.substr(j, CiphertextLength); string PartPlaintext; StringSource(PartCiphertext, true, new HexDecoder(new PK_DecryptorFilter(RNG(), Priv, new StringSink(PartPlaintext)))); Plaintext += PartPlaintext; } } void CMyRSA::DecryptString(const string &strPriv, const string &Ciphertext, string &Plaintext) { StringSource PrivKey(strPriv, true, new HexDecoder); RSAES_OAEP_SHA_Decryptor Priv(PrivKey); //indicate the ciphertext in hexcode int CiphertextLength = Priv.FixedCiphertextLength() * 2; for (int i = Ciphertext.size(), j=0; i > 0; i -= CiphertextLength, j += CiphertextLength) { string PartCiphertext = Ciphertext.substr(j, CiphertextLength); string PartPlaintext; StringSource(PartCiphertext, true, new HexDecoder(new PK_DecryptorFilter(RNG(), Priv, new StringSink(PartPlaintext)))); Plaintext += PartPlaintext; } } RandomPool & CMyRSA::RNG(void) { return m_sRandPool; } RandomPool CMyRSA::m_sRandPool; /************************** Main.h ********************************/ #ifndef __MAIN_H__ #define __MAIN_H__ #endif /* End of __MAIN_H__ */ /************************** Main.cpp ********************************/ #include <unistd.h> #include <iostream> #include "Main.h" #include "MyRSA.h" /***** STATIC VARIABLES *****/ static RSAES_OAEP_SHA_Encryptor g_Pub; static RSAES_OAEP_SHA_Decryptor g_Priv; static string g_strPub; static string g_strPriv; int main(int argc, char *argv[]) { try { char Seed[1024], Message[1024], MessageSeed[1024]; unsigned int KeyLength; CMyRSA MyRSA; cout << "Key length in bits: "; cin >> KeyLength; cout << "/nRandom Seed: "; ws(cin); cin.getline(Seed, 1024); cout << "/nMessage: "; ws(cin); cin.getline(Message, 1024); cout << "/nRandom Message Seed: "; ws(cin); cin.getline(MessageSeed, 1024); MyRSA.GenerateKey(KeyLength, Seed, g_Priv, g_Pub); //MyRSA.GenerateKey(KeyLength, Seed, g_strPriv, g_strPub); //If generate key in RSAES_OAEP_SHA_Encryptor and RSAES_OAEP_SHA_Decryptor, please note four lines below /* cout << "g_strPub = " << g_strPub << endl; cout << endl; cout << "g_strPriv = " << g_strPriv << endl; cout << endl; */ string Plaintext(Message); string Ciphertext; MyRSA.EncryptString(g_Pub, MessageSeed, Plaintext, Ciphertext); //MyRSA.EncryptString(g_strPub, MessageSeed, Plaintext, Ciphertext); cout << "/nCiphertext: " << Ciphertext << endl; cout << endl; string Decrypted; MyRSA.DecryptString(g_Priv, Ciphertext, Decrypted); //MyRSA.DecryptString(g_strPriv, Ciphertext, Decrypted); cout << "/nDecrypted: " << Decrypted << endl; return 0; } catch(CryptoPP::Exception const &e) { cout << "/nCryptoPP::Exception caught: " << e.what() << endl; return -1; } catch(std::exception const &e) { cout << "/nstd::exception caught: " << e.what() << endl; return -2; } return -3; } /************************** Makefile ********************************/ # The executable file name. PROGRAM := myrsa # The directories in which source files reside. SRCDIRS := . # current directory # The source file types (headers excluded). SRCEXTS := .cpp # The flags used by the cpp (man cpp for more). CPPFLAGS := # The compiling flags used only for C. # If it is a C++ program, no need to set these flags. # If it is a C and C++ merging program, set these flags for the C parts. CFLAGS := CFLAGS += # The compiling flags used only for C++. # If it is a C program, no need to set these flags. # If it is a C and C++ merging program, set these flags for the C++ parts. CXXFLAGS := -g -O2 -I./include CXXFLAGS += # The library and the link options ( C and C++ common). LDFLAGS := -L./lib -lcryptopp LDFLAGS += ## Implict Section: change the following only when necessary. ##============================================================================= # The C program compiler. Uncomment it to specify yours explicitly. #CC = gcc # The C++ program compiler. Uncomment it to specify yours explicitly. CXX = g++ # Uncomment the 2 lines to compile C programs as C++ ones. CC = $(CXX) CFLAGS = $(CXXFLAGS) # The command used to delete file. RM = rm -f ## Stable Section: usually no need to be changed. But you can add more. ##============================================================================= SHELL = /bin/sh SOURCES = $(foreach d,$(SRCDIRS),$(wildcard $(addprefix $(d)/*,$(SRCEXTS)))) OBJS = $(foreach x,$(SRCEXTS), / $(patsubst %$(x),%.o,$(filter %$(x),$(SOURCES)))) DEPS = $(patsubst %.o,%.d,$(OBJS)) .PHONY : all objs clean cleanall rebuild all : $(PROGRAM) # Rules for creating the dependency files (.d). #--------------------------------------------------- %.d : %.c @$(CC) -MM -MD $(CFLAGS) $< %.d : %.C @$(CC) -MM -MD $(CXXFLAGS) $< %.d : %.cc @$(CC) -MM -MD $(CXXFLAGS) $< %.d : %.cpp @$(CC) -MM -MD $(CXXFLAGS) $< %.d : %.CPP @$(CC) -MM -MD $(CXXFLAGS) $< %.d : %.c++ @$(CC) -MM -MD $(CXXFLAGS) $< %.d : %.cp @$(CC) -MM -MD $(CXXFLAGS) $< %.d : %.cxx @$(CC) -MM -MD $(CXXFLAGS) $< # Rules for producing the objects. #--------------------------------------------------- objs : $(OBJS) %.o : %.c $(CC) -c $(CPPFLAGS) $(CFLAGS) $< %.o : %.C $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< %.o : %.cc $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< %.o : %.cpp $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< %.o : %.CPP $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< %.o : %.c++ $(CXX -c $(CPPFLAGS) $(CXXFLAGS) $< %.o : %.cp $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< %.o : %.cxx $(CXX) -c $(CPPFLAGS) $(CXXFLAGS) $< # Rules for producing the executable. #---------------------------------------------- $(PROGRAM) : $(OBJS) ifeq ($(strip $(SRCEXTS)), .c) # C file $(CC) -o $(PROGRAM) $(OBJS) $(LDFLAGS) else # C++ file $(CXX) -o $(PROGRAM) $(OBJS) $(LDFLAGS) endif -include $(DEPS) rebuild: clean all clean : @$(RM) *.o *.d cleanall: clean @$(RM) $(PROGRAM) $(PROGRAM).exe

如果你还在写这个加密类库的动态链接库,我建议你不要浪费时间了!已经有了而且很好用,网址:http://download.csdn.net/source/1931336

使用Crypto++5.5.2完成RSA加解密,真正的把公钥放在字符串内,而不是放在文件内相关推荐

  1. rsa加解密 --- jsencrypt.min.js --- 支持长字符串分段加解密

    前端 + rsa加解密 + jsencrypt.min.js–(新增超长字符分段加解密) 分享2种,分段 和 不分段 加解密 --话不多说,直接上代码!~ 最终效果: 首先引入2个js <scr ...

  2. Crypto++库在VS 2005中的使用——RSA加解密

    Crypto++库在VS 2005中的使用--RSA加解密 源代码:下载 一.   下载Crypto++ Library Crypto++ Library的官方网:http://www.cryptop ...

  3. python3 RSA加解密

    python3 可以使用 Crypto.PublicKey.RSA 和 rsa 生成公钥.私钥. 其中 python3.6 Crypto 库 使用 pip3 install pycryptodome ...

  4. openresty 与 java RSA加解密

    上一篇搞定了openresty与java之间的aes加解密.这一篇就来说说openresty与java之间RSA的加解密.在测试的过程中.发现了与aes同样的问题.就是openresty支持的填充模式 ...

  5. Java中的RSA加解密工具类:RSAUtils

    本人手写已测试,大家可以参考使用 package com.mirana.frame.utils.encrypt;import com.mirana.frame.utils.log.LogUtils; ...

  6. openssl在多平台和多语言之间进行RSA加解密注意事项

    首先说一下平台和语言: 系统平台为CentOS6.3,RSA加解密时使用NOPADDING进行填充 1)使用C/C++调用系统自带的openssl 2)Android4.2模拟器,第三方openssl ...

  7. 前后端java+vue 实现rsa 加解密与摘要签名算法

    RSA有两个密钥,一个是公开的,称为公开密钥:一个是私密的,称为私密密钥. 特点: 公开密钥是对大众公开的,私密密钥是服务器私有的,两者不能互推得出. 用公开密钥对数据进行加密,私密密钥可解密:私密密 ...

  8. 区块链背后的信息安全(4)RSA加解密及签名算法的技术原理及其Go语言实现

    # RSA加解密及签名算法的技术原理及其Go语言实现 对称加密中,加密和解密使用相同的密钥,因此必须向解密者配送密钥,即密钥配送问题. 而非对称加密中,由于加密和解密分别使用公钥和私钥,而公钥是公开的 ...

  9. SHA256withRSA签名,RSA加解密

    SHA256withRSA签名,RSA加解密 简介 加密.签名流程图 具体代码实现 简介 项目用到了加密相关知识,主要包括加解密和签名过程.文章用java简单实现这一过程的工具类.(不包括公私钥的生成 ...

最新文章

  1. LeetCode 4 两个排序数组的中位数
  2. python中__str__与__repr__
  3. 网站性能调优开发工具: Lighthouse, Puppeteer 以及进阶部分丨 Google 开发者大会 2018...
  4. sigmoid函数求导与自然指数
  5. vue 非template模式_vue-template-compiler 还能这么用
  6. EasyUI DataGrid 合并单元格
  7. 使用mysql命令行的工具_[MySQL]命令行工具和基本操作
  8. 去掉IE上的 单击以激活和使用此控件 提示
  9. Opera 设置微软雅黑字体显示!
  10. 思科室外AP无法注册到WLC
  11. oracle虚拟件不活动,BOM 中的虚拟件
  12. java 微信公众平台 开源_Java微信公众号开发之开源框架推荐
  13. android MTK手机adb remount 失败,如何remont成功?
  14. matlab输出工作区,matlab保存工作区数据
  15. .NET性能相关书籍
  16. 计算机c语言入门.ppt,计算机c语言入门经典
  17. mbio期刊拒稿率_PLoS Pathogens
  18. nginx缓冲区关闭导致下载失败问题
  19. 利用CSS制作通栏,css6——通栏平均分布
  20. 京东 java 待遇_【深圳京东工资】java开发工程师待遇-看准网

热门文章

  1. TCP实时视频传输学习记录【附代码】【含视频】
  2. 移动端html右滑空白,移动端之touch事件_上滑、下滑、左滑和右滑
  3. 蓝桥杯控制PCF8591
  4. 为什么单相电机要用电容,三相电机不需要电容?
  5. 【软考系统架构设计师】2018下系统架构师综合知识历年真题
  6. macos docker 一直处于 kubernetes starting状态解决办法(当试过各种方法无用时,此方法有效)
  7. 某火炮武器系统电气控制软件测试实践
  8. 结构体和联合体详解-定义及初始化
  9. 2019年华北五省计算机应用大赛官网,我院在“远洋航空杯”2019年华北五省及港澳台大学生计算机应用大赛中荣获佳绩...
  10. GP-荧光免疫分析仪SDK 协议