我使用 java 创建了一个 pkcs12 keystore ,其中我存储了两个 key ,现在我想使用 python 检索这些 key 。 ln java l 加载 keystore 并使用 keystore.getkey(keyalias)。我怎样才能用 python 做到这一点?
- 我首先尝试了 pyjks,但它不支持 pkcs12 keystore
- 然后我尝试了pyopenssl但是文档没有提到实际加载现有 keystore 的方法。
- 我还从这里的旧帖子中找到了这段代码:
# 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.
但是 get_privatekey() 不接受 args,这意味着不能像在 java 中那样设置我想要检索的 key 别名:
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;
}
最佳答案
在我开始之前有一个问题,您以“ secret key ”(又名对称)开头的两个 key ,还是“私钥”?
如果您的 key 是“私钥”,您应该能够将 PKCS12 keystore 转换为 JKS keystore ,并使用 pyjks 读取私钥。
要从 RHEL7 上的命令行转换 keystore 格式,请使用以下命令:
keytool -importkeystore -srckeystore <path_to_your_pkcs12_keystore> -srcstoretype PKCS12 -deststoretype JKS -destkeystore <path_to_new_jks_keystore>
如果您的 key 是“ secret key ”,则 JKS 格式不支持“ secret key ”条目类型。因此,请尝试将您的 keystore 从 PKCS12 格式转换为 JCEKS 格式的 keystore 。 JCEKS 格式是一种兼具
- 支持“ key ”条目类型
- 声称由pyjks支持
要从 RHEL7 上的命令行转换 keystore 格式,请使用以下命令:
keytool -importkeystore -srckeystore <path_to_your_pkcs12_keystore> -srcstoretype PKCS12 -deststoretype JCEKS -destkeystore <path_to_new_jceks_keystore>
这个新的 JCEKS 格式 keystore 现在应该能够使用 pyjks 通过 python 读取
关于python - 如何使用 python 加载 pkcs12 keystore ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60837051/