以编程方式获取 KeyStore 的条目类型

Get the Entry type of a KeyStore programatically

通过keytool命令,我们得到了这样的信息:

Keystore type: JKS
Keystore provider: SUN

Your keystore contains 1 entry

Alias name: myname
Creation date: 21-Aug-2011
Entry type: PrivateKeyEntry
Certificate chain length: 1
...

在 Java 中(以编程方式),如何检索“条目类型”值以了解它是私有证书还是 public?我以这种方式使用 KeyStore Java class:

File file = new File(filePath);
String password = password.toCharArray();
KeyStore keyStore = KeyStore.getInstance(format);
keyStore.load(new FileInputStream(file), password);

您需要做的是检查 KeyStore 中给定别名的 KeyEntry 是 PrivateKeyEntry 还是 TrustedCertificateEntry。

char[] password = "mypassword";

ProtectionParameter passwordProtection = new KeyStore.PasswordProtection(password.toCharArray());

KeyEntry entry = keystore.getEntry("myname", passwordProtection);

if (entry instanceof PrivateKeyEntry) {
    // is a private key entry
}