码迷,mamicode.com
首页 > 其他好文 > 详细

Crypto++应用:非对称加密RSA

时间:2015-07-16 20:10:59      阅读:440      评论:0      收藏:0      [点我收藏+]

标签:

1,非对称加密RSA:

    (1)乙方生成两把密钥(公钥和私钥)。公钥是公开的,任何人都可以获得,私钥则是保密的。

    (2)甲方获取乙方的公钥,然后用它对信息加密。

    (3)乙方得到加密后的信息,用私钥解密。

2,使用CryptoPP实现RSA:

    CryptoPP是一套非常完整的加密解密开源解决方案,如何使用这里就不多说了,请自行Google。

#include "..\cryptopp562\randpool.h"
#include "..\cryptopp562\osrng.h"
#include "..\cryptopp562\rsa.h"

//自动生成随机数据
byte seed[1024] = "";
AutoSeededRandomPool rnd;
rnd.GenerateBlock(seed, sizeof(seed));
printf("seed = %s\n", (char *)seed, strlen((char *)seed));

//生成加密的高质量伪随机字节播种池一体化后的熵
RandomPool randPool;
randPool.Put(seed, sizeof(seed));

//待加密的字符串
string message = "http://my.oschina.net/xlplbo/blog";
printf("message = %s, length = %d\n", message.c_str(), strlen(message.c_str()));

//使用OAEP模式
RSAES_OAEP_SHA_Decryptor pri(randPool, sizeof(seed));
RSAES_OAEP_SHA_Encryptor pub(pri);
printf("max plaintext Length = %d,%d\n", pri.FixedMaxPlaintextLength(), pub.FixedMaxPlaintextLength());
//待加密文本不能大于最大加密长度
if (pub.FixedMaxPlaintextLength() > message.length())
{
	string chilper;
	StringSource(message, true, new PK_EncryptorFilter(randPool, pub, new StringSink(chilper)));
	printf("chilper = %s, length = %d\n", chilper.c_str(), strlen(chilper.c_str()));

	string txt;
	StringSource(chilper, true, new PK_DecryptorFilter(randPool, pri, new StringSink(txt)));
	printf("txt = %s, length = %d\n", txt.c_str(), strlen(txt.c_str()));
}

//使用PKCS1v15模式
RSAES_PKCS1v15_Decryptor pri1(randPool, sizeof(seed));
RSAES_PKCS1v15_Encryptor pub1(pri1);
printf("max plaintext Length = %d,%d\n", pri1.FixedMaxPlaintextLength(), pub1.FixedMaxPlaintextLength());
//待加密文本不能大于最大加密长度
if (pub1.FixedMaxPlaintextLength() > message.length())
{
	string chilper;
	StringSource(message, true, new PK_EncryptorFilter(randPool, pub1,new StringSink(chilper)));
	printf("chilper = %s, length = %d\n", chilper.c_str(), strlen(chilper.c_str()));

	string txt;
	StringSource(chilper, true, new PK_DecryptorFilter(randPool, pri1, new StringSink(txt)));
	printf("txt = %s, length = %d\n", txt.c_str(), strlen(txt.c_str()));
}

    Cryptopp提供两种RSA的padding模式,分别是OAEP和PK1v15,padding模式跟安全性其实是紧密挂钩的,有兴趣的朋友可以去了解一下。

    值得注意的seed的大小决定了能够加密的文本长度,可以通过修改seed的大小,运行查看结果。seed越大,加密解密的时间也越长,超过2048一般就能明显感觉到时间很长了,一般使用1024就已经具有足够的安全性,参照下表:

技术分享

    当然CryptoPP不只是提供加密解密算法,还提供很多易用的工具,如AutoSeededRandomPool, RandomPool, StringSource,StringSink,SocketSource,SocketSink,FileSource,FileSink等类,RSAES_OAEP_SHA_Decryptor, RSAES_OAEP_SHA_Encryptor等宏定义,具体使用方法请阅读源码。


参考链接:

    http://www.cryptopp.com/

    http://www.ruanyifeng.com/blog/2013/06/rsa_algorithm_part_one.html

    http://www.ruanyifeng.com/blog/2013/07/rsa_algorithm_part_two.html


Crypto++应用:非对称加密RSA

标签:

原文地址:http://my.oschina.net/xlplbo/blog/479462

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!