使用 Crypto++ 进行 RAW RSA 加密和解密

cra*_*pot 5 rsa crypto++

我需要在 PC 和支持 RSA 加密和使用 SHA1 签名的设备之间建立安全通信。由于我已经在应用程序的其他部分使用了 Crypto++,因此我也想为此使用 Crypto++。

该设备非常原始,但允许执行我在其上编写的程序。它内置了原始 RSA 和 SHAa 函数;但是,它可以使用的内存很少,准确地说是 2K 字节。

我必须对来自 PC 的消息进行加密和签名。然后设备解密并验证消息。然后设备将回复加密消息并在其上签名。PC 将解密该消息并随后对其进行验证。我已经使用内置函数在设备内部使用 SHA1 实现了原始 RSA 加密、签名和验证。消息足够短,可以在单轮中完成。

但是,我不知道如何在不涉及 OAEP 或 PKCS#1 的情况下使用 Crypto++ 使用原始 RSA 加密消息。有人可以向我展示一些示例代码吗?万分感谢!

jww*_*jww 5

我不知道如何在不涉及 OAEP 或 PKCS#1 的情况下使用 Crypto++ 使用原始 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;
Run Code Online (Sandbox Code Playgroud)

解密

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;
Run Code Online (Sandbox Code Playgroud)

这是一个示例输出:

$ ./cryptopp-raw-rsa.exe
message: secret
m: 736563726574h
c: 3f47c32e8e17e291h
r: 736563726574h
recovered: secret
Run Code Online (Sandbox Code Playgroud)

有一个警告:c = m ^ e mod n,因此明文大小和密文大小有一些限制。本质上,mc必须小于nsecret在此示例中,用替换字符串now is the time for all good men to come to the aid of their country将会失败,因为它比n转换为Integer.

您可以使用 函数 获取最大明文大小MaxPreImage(),使用 获取最大密文大小MaxImage()


我必须对来自 PC 的消息进行加密和签名。然后设备解密并验证该消息。然后设备将回复加密消息并登录。PC 将解密消息并随后进行验证。

从表面上看,这看起来像是会遭受重放攻击。您可能需要一个具有保护功能的协议。