2012-01-15 70 views
1

RSA解密问题RSA解密问题C#

我遇到了C#RSA程序的问题。它没有正确解密。当我分配d =(e^-1)%phiN,然后将d应用于我的密文时,会出现荒谬的十进制答案。它应该拿出一个整数。我认为这是我的数学问题。你有什么建议吗? 如果您需要详细信息或其他代码,请询问。 另外,有没有可用于使此代码更好的填充方案?此时此代码易受频率分析影响。

protected void decryptRSA(object sender, EventArgs ev) 

{ 
     double p = (double)Convert.ToInt64(P.Text);//I use 123 for testing 
     double q = (double)Convert.ToInt64(Q.Text);//127 
     double e = (double)Convert.ToInt64(E.Text);//133 
     double phiN = (p-1)*(q-1); 
     double n = p*q; 
     double d = Math.Pow(e, -1D); 
     d = d%phiN; 

     string cipherStr = outputBuffer.Text; 
     double[] cipherTextDouble = new double[100]; 
     string[]plainText = new string[cipherTextDouble.Length]; 

     cipherTextDouble = parser(cipherStr, 'D'); 
    for(int slot = 0; slot<cipherTextDouble.Length; slot++) 
     { 
    cipherTextDouble[slot] = (double)(Math.Pow((double)cipherTextDouble[slot],(double)d)%n); 
     } 
     for(int slot = 0; slot<cipherTextDouble.Length; slot++) 
     { 
      inputBuffer.Text += Convert.ToChar(cipherTextDouble[slot]) + ' ';//the spot were it dies 
//it doesn't like to convert from a decimal like 1.75 to a char. Of course I should never get a decimal like 1.75, which is the problem 
     } 
    } 
+1

不要使用双。 – 2012-01-15 13:00:38

回答

2

您没有正确计算指数。您需要找到一个数字d,使得ed = 1 (mod phi)e (mod phi)的倒数。这与在实数中计算e的倒数不同,后者是double d = Math.Pow(e, -1D);计算的值,然后执行mod操作。这就是你最终得到一个十进制数的原因(在这种情况下,1/133〜0.007和1/133%15372仍然= 0.007,因为%实际上是C#中的“余数”运算符,而不是整数模数(否则它不会无论如何都不会在双打上工作))。您需要使用Euclidean Algorithm来计算逆模mod。

编辑:GregS正确地指出,对于计算机实现,您可能希望使用Extended Euclidean Algorithm来代替在单遍中查找模块逆。这通常是以计算方式完成的。你可以用欧几里德算法(通常是手工)来完成,但这是浪费时间。

+1

* extended * euclidean算法。 – 2012-01-15 12:58:35