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?
# 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;
}
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With