Advertisement
Willcode4cash

Generate RSA Key Pair

Mar 15th, 2017
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.29 KB | None | 0 0
  1. /********************************************************************************
  2.  * Install and reference the following libraries:
  3.  * ----------------------------------------------
  4.  * BouncyCastle         (NuGet)
  5.  * HtmlAgilityPack      (NuGet)
  6.  * System.Globalization (.NET Framework)
  7.  * System.IO            (.NET Framework)
  8.  ********************************************************************************/
  9.  
  10. public static void Main(string[] args)
  11. {
  12.     // Generate the RSA key pair, public and private
  13.     var keys = GenerateKeys(2048);
  14.  
  15.     // Write the public RSA key
  16.     using(var textWriter = new StreamWriter("c:\\folder-name\\public.key"))
  17.     {
  18.         var writer = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter);
  19.         writer.WriteObject(keys.Public);
  20.         writer.Writer.Flush();
  21.     }
  22.  
  23.     // Write the private RSA key
  24.     using(var textWriter = new StreamWriter("c:\\folder-name\\private.key"))
  25.     {
  26.         var writer = new Org.BouncyCastle.OpenSsl.PemWriter(textWriter);
  27.         writer.WriteObject(keys.Private);
  28.         writer.Writer.Flush();
  29.     }
  30. }
  31.  
  32. // Generates a cryptographcally strong RSA key pair.
  33. public static AsymmetricCipherKeyPair GenerateKeys(int keySizeInBits)
  34. {
  35.     var r = new RsaKeyPairGenerator();
  36.     r.Init(new KeyGenerationParameters(new SecureRandom(), keySizeInBits));
  37.     var keys = r.GenerateKeyPair();
  38.     return keys;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement