【发布时间】:2017-06-22 04:01:02
【问题描述】:
我正在使用Crypto++ 库进行密码学相关工作。任务的子部分是加密和解密文本。消息最长可达 256 个字符,包含字母数字空格点和特殊字符。
这段代码在文本长度小于或等于 8 的情况下工作。但之后它无法解密加密的文本。
// g++ -std=c++1y crypto.cpp -I /home/shravan40/cryptopp/build -lcryptopp
#include <iostream>
#include <cryptopp/rsa.h>
#include <cryptopp/integer.h>
#include <cryptopp/osrng.h>
int main(){
// Keys
CryptoPP::Integer n("0xbeaadb3d839f3b5f"), e("0x11"), d("0x21a5ae37b9959db9");
CryptoPP::RSA::PrivateKey privKey;
privKey.Initialize(n, e, d);
CryptoPP::RSA::PublicKey pubKey;
pubKey.Initialize(n, e);
// Encryption
std::string message = "Shravan Kumar";
CryptoPP::Integer m((const byte *)message.data(), message.size());
std::cout << "m: " << m << std::endl;
// m: 126879297332596.
CryptoPP::Integer c = pubKey.ApplyFunction(m);
std::cout << "c: " << std::hex << c << std::endl;
// c: 3f47c32e8e17e291h
// Decryption
CryptoPP::AutoSeededRandomPool prng;
CryptoPP::Integer r = privKey.CalculateInverse(prng, c);
std::cout << "r: " << std::hex << r << std::endl;
// r: 736563726574h
std::string recovered;
recovered.resize(r.MinEncodedSize());
r.Encode((byte *)recovered.data(), recovered.size());
std::cout << "recovered: " << recovered << std::endl;
// recovered: Expected : (Shravan Kumar), Received -> y5��dqm0
return 0;
}
【问题讨论】:
-
您通常不会直接使用 PKI 来加密消息,因为消息会受到密钥长度的限制。您应该使用对称算法(例如 CBC 模式下的 AES)来加密消息文本。然后使用公钥加密对称密钥。
-
另见 Crypto++ wiki 上的 RSA Cryptography。
标签: c++ encryption cryptography crypto++