title: Android - converting pkcs12 certificate string to x509 certificate object for bks keystore
body: <p>I am writing an android app that requires SSL certification for certain web requests. Unlike the options I see online about creating the keystore files using the cert file, I have to make an initial web request that returns the certificate as a string in a json response.</p>
  
  <p>The JSON data is formatted like the following... (note: the following certificate is shortened, the "..." does not exist in an actual response)</p>
  
  <pre><code>"result":{
      "pkcs12": "Ulv6GtdFbjzLeqlkelqwewlq822OrEPdH+zxKUkKGX/eN...9801asds3BCfu52dm7JHzPAOqWKaEwIgymlk="
  },
  </code></pre>
  
  <p>I am decoding this value using Base64.deocode to save it as a byte[]</p>
  
  <pre><code>ssl.setPkcs12( Base64.decode( jsonObject.optString( "pkcs12" ) ) );
  </code></pre>
  
  <p>Then I am trying to create a X509Certificate using the byte[]</p>
  
  <pre><code>CertificateFactory certFactory = CertificateFactory.getInstance( "X.509" );
  InputStream in = new ByteArrayInputStream( ssl.getPkcs12() );
  X509Certificate cert = (X509Certificate) certFactory.generateCertificate( in );
  </code></pre>
  
  <p>My code is failing on the generateCertificate() method with</p>
  
  <pre><code>"java.security.cert.CertificateException: org.apache.harmony.security.asn1.ASN1Exception: ASN.1 Sequence: mandatory value is missing at [4]".
  </code></pre>
  
  <p>I have spent a great deal of time trying to fix what appears to be a simple problem with no luck at all. Any help would be amazing!</p>