title: how to load a pkcs12 keystore using python
body: <p>l used java to create a pkcs12 keystore where l stored two keys, now l want to retrieve these keys using python. ln java l load the keystore and use keystore.getkey(keyalias). how can l do that with python?</p>
  
  <ul>
  <li>l first tried pyjks but it wasn't supporting pkcs12 keystores</li>
  <li>then l tried <a href="https://www.pyopenssl.org/en/stable/api/crypto.html#pkcs12-objects" rel="nofollow noreferrer">pyopenssl</a> but l the documentation didn't mention a method to actually to load an existing keystore.</li>
  <li>l also l found this piece of code from an old post here: </li>
  </ul>
  
  <pre><code># load OpenSSL.crypto
  from OpenSSL import crypto
  
  # open it, using password. Supply/read your own from stdin.
  p12 = crypto.load_pkcs12(open("/path/to/cert.p12", 'rb').read(), passwd)
  
  # get various properties of said file.
  # note these are PyOpenSSL objects, not strings although you
  # can convert them to PEM-encoded strings.
  p12.get_certificate()     # (signed) certificate object
  p12.get_privatekey()      # private key.
  p12.get_ca_certificates() # ca chain.
  </code></pre>
  
  <p>but the <strong>get_privatekey()</strong> doesn't accept args which means that can't set the key alias that l want to retrieve the same way l do in java:</p>
  
  <pre><code>public static SecretKey getEntry(KeyStore keyStore, String keyAlias, Optional&lt;String&gt; password) {
          SecretKey key = null;
  
          try {
              key = (SecretKey) keyStore.getKey(keyAlias, password.orElse("").toCharArray());
          } catch (Exception e) {
              e.printStackTrace();
          }
          return key;
      }
  </code></pre>