我不知道如何使用 Crypto++ 使用原始 RSA 加密消息,而无需
涉及 OAEP 或 PKCS#1。有人可以给我一些示例代码吗?
当您知道在哪里查找时,这很容易:来自 Crypto++ wiki 的 Raw 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 会失败,因为在转换为 Integer 时它大于 n。
您可以使用MaxPreImage()函数获取最大纯文本大小,使用MaxImage()获取最大密文大小。
我必须对来自 PC 的消息进行加密和签名。然后设备解密
并验证消息。然后设备将回复一条加密消息
并在上面签名。 PC 将解密该消息并随后对其进行验证。
从表面上看,这看起来会遭受重放攻击。您可能需要具有保护功能的协议。