开发者

RSA - Math.pow inaccurate

开发者 https://www.devze.com 2023-01-26 20:53 出处:网络
I am trying to use the RSA algorithm for learning purposes. Now I have the following issue. I stuck at the following point.

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 = encryp开发者_运维问答ted 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.


You're using a floating point function for something that should really be done using arbitrary precision integers.


If you add a reference to System.Numerics.dll (in .NET 4.0) you can use the new System.Numerics.BigInteger structure that will allow integer operations without any fear of performing and overflow operation. You can easily then implement power in terms of BigInteger which will be accurate.


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.


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.)

c = 1;
for (int i = e; i--; i > 0)
{
    c *= value;
    while ( c > n) { c -= n; }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消