RSA - Math.pow 不准确
我正在尝试使用 RSA 算法进行学习。现在我有以下问题。我陷入了以下这一点。
我需要解决以下函数:
c = value^e % n
c = 加密结果 value = 需要加密的数字 d = 我的公钥 n = RSA 模块
我仅使用 double 作为所有变量的数据类型。我用以下行解决了这个函数:
double c = Math.Pow(value, e) % n
这里的问题是, math.pow 函数看起来产生了错误的值,看起来有点不准确。当我使用 Windows 计算器尝试此操作时,我得到了更好的正确结果。
我的问题:有人知道如何解决这个问题以获得与 RSA 一起使用的正确结果吗?所有其他部分的计算绝对正确。它只能是 math.pow 或模数。
I am trying to use the RSA algorithm for learning purposes. Now I have the following issue. I stuck at the following point.
i need to solve the following function:
c = value^e % n
c = encrypted result
value = the number to be encrypted
d = my public key
n = RSA module
I only use double as a datatype for all variables. The function I solved with the following line:
double c = Math.Pow(value, e) % n
The issue here is, that it looks like the math.pow function produces a wrong value, it seems like it a bit inaccurate. When I try this with the Windows calculator I get a much better result which is correct.
My questions: Does someone know, how to solve this to get the correct result to work with RSA. The calculation of all teh other parts is definetly correct. It only can be the math.pow or the modulus thing.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您正在使用浮点函数来完成实际上应该使用任意精度整数完成的事情。
You're using a floating point function for something that should really be done using arbitrary precision integers.
如果您添加对 System.Numerics.dll 的引用(在 .NET 4.0 中),您可以使用新的 System.Numerics.BigInteger 结构,该结构将允许整数运算而无需担心执行和溢出操作。然后,您可以轻松地以
BigInteger
的形式实现功能,这将是准确的。If you add a reference to
System.Numerics.dll
(in .NET 4.0) you can use the newSystem.Numerics.BigInteger
structure that will allow integer operations without any fear of performing and overflow operation. You can easily then implement power in terms ofBigInteger
which will be accurate.编写一个方法来计算任意精度数字的幂并不那么难,只需使用 Decimal 数据类型就可以了。
Writing a method to calculate the power of arbitrary precision numbers isn't all that hard, just use Decimal datatype and you should be ok.
以整数执行所有计算。
求幂就变成了循环 e 次乘以值。在循环内执行%运算以避免溢出。
您可以通过替换 while 循环将结果减少到 n 以下来避免使用 % 运算符。 (%运算符通常非常慢。如果速度不是问题,请继续使用它。)
Perform all the computation in integers.
Raising to the power becomes multiplying by value in a loop e times. Perform a % operation within the loop to avoid overflow.
You may be able to avoid the % operator by substituting a while loop to reduce the result to below n. (% operators are generally very slow. If speed is not an issue, go ahead an use it.)