Willcode4cash icon

Generate RSA Key Pair

Willcode4cash | PRO | 03/15/17 05:12:54 AM UTC | 0 ⭐ | 318 👁️ | Never ⏰ | []
C# |

1.29 KB

|

None

|

0 👍

/

0 👎

/********************************************************************************
 * Install and reference the following libraries:
 * ----------------------------------------------
 * BouncyCastle         (NuGet)
 * HtmlAgilityPack      (NuGet)
 * System.Globalization (.NET Framework)
 * System.IO            (.NET Framework)
 ********************************************************************************/
 
public static void Main(string[] args)
{
    // Generate the RSA key pair, public and private
    var keys = GenerateKeys(2048);
 
    // Write the public RSA key
    using(var textWriter = new StreamWriter("c:\\folder-name\\public.key"))
    {
        var writer = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter);
        writer.WriteObject(keys.Public);
        writer.Writer.Flush();
    }
 
    // Write the private RSA key
    using(var textWriter = new StreamWriter("c:\\folder-name\\private.key"))
    {
        var writer = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter);
        writer.WriteObject(keys.Private);
        writer.Writer.Flush();
    }
}
 
// Generates a cryptographcally strong RSA key pair.
public static AsymmetricCipherKeyPair GenerateKeys(int keySizeInBits)
{
    var r = new RsaKeyPairGenerator();
    r.Init(new KeyGenerationParameters(new SecureRandom(), keySizeInBits));
    var keys = r.GenerateKeyPair();
    return keys;
}

Comments