title: Openssl how to find out what the bit size of the public key in an X509 certificate is
body: <p>If I have an <code>X509*</code> that openssl has provided me, what's the best way to figure out the bit-ness of the RSA public key in the certificate? I can't quite figure this out. I'm pretty sure that if I'm in the SSL certificate verification callback, I can get the X509 ptr with</p>
  
  <pre><code>X509 * cert = X509_STORE_CTX_get_current_cert(the_x509_store_ctx);
  </code></pre>
  
  <p>and I would surmise I get the public key like this</p>
  
  <pre><code>EVP_PKEY *public_key = X509_get_pubkey(cert);
  </code></pre>
  
  <p>and then I need to check whether it's RSA, presumably?</p>
  
  <pre><code>if (public_key &amp;&amp; (EVP_PKEY_RSA == public_key-&gt;type))
  </code></pre>
  
  <p>and once I know that I got a public key back and that it's RSA, I'd like to do this:</p>
  
  <pre><code>int key_length = BN_num_bits(public_key-&gt;pkey.rsa-&gt;n);
  </code></pre>
  
  <p>but I've found that while this works quite nicely on openssl 0.9.8, on 1.0.1h it segfaults on Windows. The BIGNUM 'n' doesn't seem to be valid - the data ptr in it has a garbage pointer. </p>
  
  <p>Any idea what's wrong?</p>