我不知道如何使用 Crypto++ 在不涉及 OAEP 或 PKCS#1 的情况下使用原始 RSA 加密消息。有人可以向我展示一些示例代码吗?
当您知道在哪里查找时,这很容易:来自 Crypto++ wiki 的原始 RSA 。下面的代码取自页面。
加密
Integer n("0xbeaadb3d839f3b5f"), e("0x11"), d("0x21a5ae37b9959db9");
RSA::PublicKey pubKey;
pubKey.Initialize(n, e);
///////////////////////////////////////////////////////////////
Integer m, c;
string message = "secret";
cout << "message: " << message << endl;
// Treat the message as a big endian byte array
m = Integer((const byte *)message.data(), message.size());
cout << "m: " << hex << m << endl;
// Encrypt
c = pubKey.ApplyFunction(m);
cout << "c: " << hex << c << endl;
解密
Integer n("0xbeaadb3d839f3b5f"), e("0x11"), d("0x21a5ae37b9959db9");
AutoSeededRandomPool prng;
RSA::PrivateKey privKey;
privKey.Initialize(n, e, d);
///////////////////////////////////////////////////////////////
Integer c("0x3f47c32e8e17e291"), r;
string recovered;
// Decrypt
r = privKey.CalculateInverse(prng, c);
cout << "r: " << hex << r << endl;
// Round trip the message
size_t req = r.MinEncodedSize();
recovered.resize(req);
r.Encode((byte *)recovered.data(), recovered.size());
cout << "recovered: " << recovered << endl;
这是一个示例输出:
$ ./cryptopp-raw-rsa.exe
message: secret
m: 736563726574h
c: 3f47c32e8e17e291h
r: 736563726574h
recovered: secret
有一个警告:c = m ^ e mod n
,因此对明文大小和密文大小有一些限制。本质上,m
并且c
必须小于n
。在此示例中,将字符串替换为secret
会now is the time for all good men to come to the aid of their country
失败,因为它比n
转换为Integer
.
您可以使用 函数获取最大纯文本大小,使用 获取MaxPreImage()
最大密文大小MaxImage()
。
我必须对来自 PC 的消息进行加密和签名。然后设备解密并验证消息。然后设备将回复一条加密消息并在其上签名。PC 将解密该消息并随后对其进行验证。
从表面上看,这看起来会遭受重放攻击。您可能需要具有保护的协议。