RSA Implementation in C#

12,901

Solution 1

d=e^(phi(n)-1) mod phi(n) looks wrong to me. You either need d=e^(phi(phi(n))-1) mod phi(n), or you could use extended euclid.

Solution 2

I see that you already accepted the solution. However, I would like to point you to the article that shows a more complex example on RSA encryption in C#. Check this post (There is also source code available): http://xmight.blogspot.com/2011/07/multithreaded-rsa-encryption-with-keys.html

Share:
12,901
Ivan Stalev
Author by

Ivan Stalev

Updated on June 04, 2022

Comments

  • Ivan Stalev
    Ivan Stalev almost 2 years

    I am trying to implement the RSA Algorithm in C#. The code below works when p and q are small, but not when trying to replicate RSA-100 or greater where p and q are very large.

    For example when:

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

    Once decrypted, I get the correct original messsage. I got these values from the RSA Wikipedia page. The code also works for other small values of p and q.

    However, when using RSA-100 or greater, I do not get back my original message. I have tried using different values for the exponent (e) and made sure it is coprime with phi(n) but I cannot get the correct result. Am I missing something simple/obvious?

    Thank you in advance for your help!

    //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);
    
  • Ivan Stalev
    Ivan Stalev about 11 years
    I ended up implementing the Extended Euclidean algorithm from the pseudo code on the Wikipedia page to compute d and it worked correctly. Thank you!
  • GPGVM
    GPGVM over 9 years
    XMight === Andrei??? I for one am very grateful for the / your article especially since after reading about RSA I can then trace through a COMPLETE working example. Very helpful reinforcement.
  • XMight
    XMight over 9 years
    Glad to hear that, this was its purpose. And yes, you are right :)
  • AlexMelw
    AlexMelw over 6 years
    @XMight Your link to source code is broken now. Please, create a new link.