【问题标题】:RSA Implementation in C#C# 中的 RSA 实现
【发布时间】:2013-04-10 20:23:57
【问题描述】:

我正在尝试在 C# 中实现 RSA 算法。以下代码在 p 和 q 很小时有效,但在尝试复制 RSA-100 或更高版本时 p 和 q 非常大时无效。

例如当:

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

解密后,我会得到正确的原始消息。我从RSA Wikipedia page 获得了这些值。该代码也适用于 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);

【问题讨论】:

标签: c# encryption rsa biginteger public-key-encryption


【解决方案1】:

d=e^(phi(n)-1) mod phi(n) 在我看来是错误的。您要么需要 d=e^(phi(phi(n))-1) mod phi(n),要么可以使用扩展的 euclid。

【讨论】:

  • 我最终从维基百科页面上的伪代码实现了扩展欧几里得算法来计算 d 并且它工作正常。谢谢!
【解决方案2】:

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

【讨论】:

  • XMight === 安德烈???我非常感谢您的文章,特别是因为在阅读了有关 RSA 的内容后,我可以跟踪一个完整的工作示例。非常有用的强化。
  • 很高兴听到这个消息,这就是它的目的。是的,你是对的:)
  • @XMight 您的源代码链接现在已损坏。请创建一个新链接。
猜你喜欢
  • 1970-01-01
  • 2012-04-30
  • 2010-09-27
  • 2012-12-11
  • 2014-08-12
  • 1970-01-01
  • 2019-05-07
  • 2020-11-25
相关资源
最近更新 更多