Search code examples
c#bouncycastleecdsa

C# - AsymmetricCipherKeyPair to hexadecimal


I would like an ECDSA AsymmetricCipherKeyPair that I generate in hexadecimal format. Both the public and private keys.

Now I am doing this:

//Generate key pair
ECKeyPairGenerator gen = new ECKeyPairGenerator("ECDSA");
SecureRandom secureRandom = new SecureRandom();
KeyGenerationParameters keyGenParam = new KeyGenerationParameters(secureRandom, keySize);
gen.Init(keyGenParam);
AsymmetricCipherKeyPair keys = gen.GenerateKeyPair();

//Create a PEM and then extract the BASE64 part
var key = keys.Private;
TextWriter textWriter = new StringWriter();
PemWriter pemWriter = new PemWriter(textWriter);
pemWriter.WriteObject(key);
pemWriter.Writer.Flush();
string pem = textWriter.ToString();
var pem2 = pem.Split('\r').Skip(1).TakeWhile(i => !i.Contains("-----")).ToArray();
pem = string.Join("",pem2);

//BASE64 to byte[] to hex
byte[] bytes = Convert.FromBase64String(pem);
string hex = BitConverter.ToString(bytes);

There must be an easier way to get the hexadecimal output.


Solution

  • For the private key:

    bytes = Org.BouncyCastle.Pkcs.PrivateKeyInfoFactory.CreatePrivateKeyInfo(keys.Private).ParsePrivateKey().GetDerEncoded();
    

    and the public:

    bytes = Org.BouncyCastle.X509.SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keys.Public).GetDerEncoded();