Skip to content

Instantly share code, notes, and snippets.

@Demonslay335
Last active December 17, 2018 18:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Demonslay335/f70f17b169379a9be204428bfbd4372d to your computer and use it in GitHub Desktop.
Save Demonslay335/f70f17b169379a9be204428bfbd4372d to your computer and use it in GitHub Desktop.
Generate private RSA key from factored primes
using System;
using Org.BouncyCastle.Math;
public BigInteger CalculateRSA(BigInteger p, BigInteger q, BigInteger e)
{
// n = p*q - for illustration
BigInteger n = p.Multiply(q);
// phi / r = (p-1)*(q-1)
BigInteger phi = p.Subtract(BigInteger.One).Multiply(q.Subtract(BigInteger.One));
// d = e^−1 (mod λ(n))
BigInteger d = e.ModInverse(phi);
// Return d
return d;
}
public void Main(string[] args){
// Example usage - primes would have to be factored from n of public key
string pText = "CC9EEF4A31452B93A2C3658566841BA7DFCD10B847D6749A91A32271DAAC6EFB5A45150AE684D632EDF8EAC03AA3F65EAA2648738E1B86137F66BE238B96D4AB",
qText = "C364D7C501E30FC2076E5CFA57DFD4D8970AF695D754DD41A5CA13E760E2C5A1A447A1B7B8985225C25D0966C8CD8DB198860C37F3CE6CB190FB2B1FCDE11E61",
eText = "65537";
// Load p and q as hex, e as decimal
BigInteger p = new BigInteger(pText, 16),
q = new BigInteger(qText, 16),
e = new BigInteger(eText, 10);
// Calculate d - the private key
BigInteger d = CalculateRSA(p, q, e);
// Output as hex
Console.WriteLine(d.ToString(16));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment