title: Decoding an ASN.1 DER OCTET STRING with OpenSSL
body: <p>Using the OpenSSL API, I have extracted a custom extension from a X.509v3 certificate with:</p>
  
  <pre class="lang-c prettyprint-override"><code>X509_EXTENSION* ex = X509_get_ext(x509, 4);
  </code></pre>
  
  <p>The X509_EXTENSION object contains a value (ex->value) that is an ASN.1 OCTET STRING. The OCTET STRING contains a DER encoded UTF-8 string. I'm trying to decode the OCTET STRING to get the plain UTF-8 string.</p>
  
  <p>I have tried a few things, such as:</p>
  
  <pre class="lang-c prettyprint-override"><code>ASN1_STRING_to_UTF8(&amp;buf, ex-&gt;value);
  </code></pre>
  
  <p>and</p>
  
  <pre class="lang-c prettyprint-override"><code>M_ASN1_OCTET_STRING_print(bio, ex-&gt;value);
  int len = BIO_read(bio, buf, buf_size);
  buf[len] = '\0';
  </code></pre>
  
  <p>These both give me the DER encoded string. How do I get the plain UTF-8 string?</p>