Generate public-private key pair and show them in textbox in asp.net

爱⌒轻易说出口 提交于 2019-12-03 09:03:54
ChrisBint

Using the BouncyCastle API

http://www.bouncycastle.org/

and something similiar to the following:

public AsymmetricCipherKeyPair GenerateKeys(int keySizeInBits)
{
  RsaKeyPairGenerator r = new RsaKeyPairGenerator();
  r.Init(new KeyGenerationParameters(new SecureRandom(),
    keySizeInBits));
  AsymmetricCipherKeyPair keys = r.GenerateKeyPair();
  return keys;
}

You can access an object that will have a .Public and .Private property with the correctly formatted strings.

I had a similiar problem a while back and this was the best solution that I could find. I do not have the exact code to hand, but will post it when I get into the office if required, but the above should work.

Updated with Code

This is the code I used to generate public/private keys.

  using Org.BouncyCastle.Crypto;
  using Org.BouncyCastle.Crypto.Generators;
  using Org.BouncyCastle.Security;

  public static AsymmetricCipherKeyPair GenerateKeys(int keySizeInBits)
    {
        var r = new RsaKeyPairGenerator();
        r.Init(new KeyGenerationParameters(new SecureRandom(),keySizeInBits));
        var keys = r.GenerateKeyPair();
        return keys;
    }



static void Main(string[] args)
{
    var keys = GenerateKeys(2048);


    var publicKey = keys.Public.ToString();

    var textWriter = new StreamWriter("private.key");
    var pemWriter = new PemWriter(textWriter);
    pemWriter.WriteObject(keys.Private);
    pemWriter.Writer.Flush();
    textWriter.Close();


    textWriter = new StreamWriter("public.key");
    pemWriter = new PemWriter(textWriter);
    pemWriter.WriteObject(keys.Public);
    pemWriter.Writer.Flush();
    textWriter.Close();

    Console.ReadKey();


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!