简体   繁体   中英

RSA Implementation in C#

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);

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM