C#中的RSA实现

我试图在C#中实现RSA算法。 下面的代码在p和q较小时起作用,但在尝试复制RSA-100或更大时p和q非常大时不起作用。

例如:

p = 61, q = 53, n = 3233, phi(n) = 3120, e = 17, d = 2753 

一旦解密,我得到正确的原始消息。 我从RSA维基百科页面获得了这些值。 该代码也适用于p和q的其他小值。

但是,当使用RSA-100或更高版本时,我不会收到原始邮件。 我已经尝试对指数(e)使用不同的值并确保它与phi(n)互质但我无法得到正确的结果。 我错过了一些简单/明显的东西吗?

预先感谢您的帮助!

 //p and q for RSA-100 //string p = "37975227936943673922808872755445627854565536638199"; //string q = "40094690950920881030683735292761468389214899724061"; string p = "61"; string q = "53"; //Convert string to BigInteger BigInteger rsa_p = BigInteger.Parse(p); BigInteger rsa_q = BigInteger.Parse(q); //n = p * q BigInteger rsa_n = BigInteger.Multiply(rsa_p, rsa_q); //phi(n) = (p-1)*(q-1) BigInteger rsa_fn = BigInteger.Multiply((rsa_p - 1), (rsa_q - 1)); BigInteger rsa_e = 17; //Compute d BigInteger rsa_d = BigInteger.ModPow(rsa_e, (rsa_fn - 1), rsa_fn); //Encrypt the message, in this case 3007 //C = (3007^rsa_e) mod rsa_n BigInteger C = BigInteger.ModPow(3007, rsa_e, rsa_n); //Decrypt the message, M should equal 3007 //M = (3007^rsa_d) mod rsa_n BigInteger M = BigInteger.ModPow(C, rsa_d, rsa_n); 

d = e ^(phi(n)-1)mod phi(n)对我来说是错误的。 你需要d = e ^(phi(phi(n)) – 1)mod phi(n),或者你可以使用扩展的euclid。

我看到你已经接受了解决方案。 但是,我想指出一篇文章,它展示了一个关于C#中RSA加密的更复杂的例子。 查看这篇文章(还有可用的源代码): http : //xmight.blogspot.com/2011/07/multithreaded-rsa-encryption-with-keys.html