title: Generating 64-byte public key for DH key exchange using Bouncy Castle
body: <p>I need to generate a key pair for Diffie-Hellman key exchange using the <code>secp256r1</code> curve using Bouncy Castle in C#. The public key should be 64 bytes (I'm not sure which format this is (compressed?), but I can find out).</p>
  
  <p>I have the following code, but the lack of Bouncy Castle documentation has me lost.</p>
  
  <pre><code>X9ECParameters ecParams = SecNamedCurves.GetByName("secp256r1");
  var spec = new ECDomainParameters(ecParams.Curve, ecParams.G, ecParams.N, ecParams.H, ecParams.GetSeed());
  var keyGenParams = new ECKeyGenerationParameters(spec, new SecureRandom());
  
  var keyGen = new ECKeyPairGenerator("ECDH");
  keyGen.Init(keyGenParams);
  AsymmetricCipherKeyPair keyPair = keyGen.GenerateKeyPair();
  var pubKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
  
  // pubKeyInfo.GetDerEncoded()
  // pubKeyInfo.GetEncoded()
  // pubKeyInfo.PublicKey
  // pubKeyInfo.ToAsn1Object()
  </code></pre>
  
  <p>From here, I have access to a lot of different export formats (seen above), but most values end up being 335 bytes long. <code>pubKeyInfo.PublicKeyData.GetBytes()</code> gives 65 bytes, but I'm not sure why.</p>
  
  <p>I must have some basic misunderstanding here. What am I missing?</p>
  
  <p>If it helps, another client uses the <a href="https://github.com/kmackay/micro-ecc/blob/master/uECC.c#L981" rel="nofollow"><code>uECC_make_key</code> function</a> to generate the key pair.</p>