RSA解密问题C#

本文关键字:问题 解密 RSA | 更新日期: 2023-09-27 18:20:15

RSA解密问题

我在使用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
        }
    }

RSA解密问题C#

您没有正确计算指数。你需要找到一个数字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#中的一个"余数"运算符,而不是整数模(否则它无论如何都不会对双精度运算))。

您需要使用欧几里得算法来计算逆mod phi。

编辑:GregS正确地指出,对于计算机实现,你可能想使用扩展欧几里得算法来在一次遍历中找到模逆。这通常是通过计算来完成的。你可以用欧几里得算法(通常是手工)来做,但这是浪费时间。