如何在 C 中为 RSA 算法操作大整数?

How to manipulate big integers for the RSA algorithm in C?

我想在 C 中实现 RSA 密码系统。现在我可以加密适合一个字节的值(我知道这对于任何安全来说都太小了),但是当我增加素数的大小时 pq(因此模数 n = pq ), 以及加密值的大小,它不起作用。

我相信我知道我的代码失败的原因:

  1. 要加密的值必须小于n值(并非总是如此),并且
  2. 我计算的n = pq的值是不正确的,因为变量类型不能存储真实的值我正在使用的,而是溢出了。

我的问题是,如何使用大数字(打包成 256 字节、512 字节等)并在 C 中对其进行操作?我必须使用库(例如 GMP)吗?

C 语言本身不支持任意精度整数(“bignum”)算法,因此您要么必须使用提供它的库(我听说 GMP 是一个流行的选择)或编写自己的代码来处理它。

如果您选择自己动手,我建议您将数字表示为一些相当大的本机无符号整数类型的数组(例如 uint32_tuint64_t),其中 each array element representing a digit in base 2k,其中 k 是基础本机整数中的位数。

对于 RSA,您无需担心表示负值,因为所有数学运算都是使用从 0 到 RSA 模数 n 的数字完成的。如果你愿意,也可以利用上限n固定基数2k 数字用于特定 RSA 实例中的所有值,这样您就不必将它显式地存储在每个数字数组旁边。


Ps。注意"textbook RSA" is not a secure encryption scheme by itself. To make it semantically secure, you need to also include a suitable randomized padding scheme such as OAEP. Also, padded or not, normal RSA can only encrypt messages shorter than the modulus, minus the length taken up by padding, if any. To encrypt longer messages, the standard solution is to use hybrid encryption, where you first encrypt the message using a symmetric encryption scheme (I would recommend AES-SIV)用随机密钥,然后用RSA加密密钥。