Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to load a pkcs12 keystore using python

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?

  • l first tried pyjks but it wasn't supporting pkcs12 keystores
  • then l tried pyopenssl but l the documentation didn't mention a method to actually to load an existing keystore.
  • l also l found this piece of code from an old post here:
# 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.

but the get_privatekey() 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:

public static SecretKey getEntry(KeyStore keyStore, String keyAlias, Optional<String> password) {
        SecretKey key = null;

        try {
            key = (SecretKey) keyStore.getKey(keyAlias, password.orElse("").toCharArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return key;
    }
like image 445
Achraf ELKHANDOULI Avatar asked Jun 29 '26 20:06

Achraf ELKHANDOULI


1 Answers

One question before I begin, are the two keys that you are starting with "secret keys" (aka symmetric), or are they "private keys"?

If your keys are "private keys", you should be able to convert the PKCS12 keystore to a JKS keystore, and read the private keys using pyjks.

To convert a keystore format from the command line on RHEL7, use the following:

keytool -importkeystore -srckeystore <path_to_your_pkcs12_keystore> -srcstoretype PKCS12 -deststoretype JKS -destkeystore <path_to_new_jks_keystore>

If your keys are "secret keys", the JKS format doesn't support "secret key" entry types. Therefore, try to convert your keystore from the PKCS12 format to a JCEKS format keystore. The JCEKS format is one that both

  • Supports "secret key" entry types
  • Is claimed to be supported by pyjks

To convert a keystore format from the command line on RHEL7, use the following:

keytool -importkeystore -srckeystore <path_to_your_pkcs12_keystore> -srcstoretype PKCS12 -deststoretype JCEKS -destkeystore <path_to_new_jceks_keystore>

This new JCEKS format keystore should now be able to get read in via python using pyjks

like image 117
M Ross Avatar answered Jul 01 '26 10:07

M Ross



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!