我想加载密钥库文件并获取其根SSL证书的详细信息。

Link to Sample

我在上面的链接中看到了代码。该代码也在下面可见。 keyStore.isKeyEntry(alias)的用途是什么?

我检查了JavaDocs,它说


  如果给定别名标识的条目是通过调用setKeyEntry创建的,或者是通过调用带有PrivateKeyEntry或SecretKeyEntry的setEntry创建的,则返回true。


那么,它的用途是什么?

        boolean isAliasWithPrivateKey = false;
        KeyStore keyStore = KeyStore.getInstance("JKS");

        // Provide location of Java Keystore and password for access
        keyStore.load(new FileInputStream(jksPath), jksPassword.toCharArray());

        // iterate over all aliases
        Enumeration<String> es = keyStore.aliases();
        String alias = "";
        while (es.hasMoreElements()) {
            alias = (String) es.nextElement();
            // if alias refers to a private key break at that point
            // as we want to use that certificate
            if (isAliasWithPrivateKey = keyStore.isKeyEntry(alias)) {
                break;
            }
        }

        if (isAliasWithPrivateKey) {

            KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias,
                    new KeyStore.PasswordProtection(jksPassword.toCharArray()));

            PrivateKey myPrivateKey = pkEntry.getPrivateKey();

            // Load certificate chain
            Certificate[] chain = keyStore.getCertificateChain(alias);

            certDetails = new CertificateDetails();
            certDetails.setPrivateKey(myPrivateKey);
            certDetails.setX509Certificate((X509Certificate) chain[0]);
  }

最佳答案

Java密钥库中有3种类型的条目:


privateKeyEntry,私钥和关联的证书链
TrustedKeyEntry,一种受信任的证书(例如来自CA的证书,例如Verisign,GoDaddy等)
secretKeyEntry,加密密钥(例如对称密钥AES)


如Java文档中所述,KeyStore.isKeyEntry(alias)返回true是您具有秘密密钥还是私钥。

如果该条目是密钥,则代码示例将失败:

`KeyStore.PrivateKeyEntry pkEntry = (KeyStore.PrivateKeyEntry) keyStore.getEntry(alias, new KeyStore.PasswordProtection(jksPassword.toCharArray()));`


最好使用:

`KeyStore.entryInstanceOf(alias , KeyStore.PrivateKeyEntry.class)`

关于java - 在KeyStore中使用isKeyEntry(alias)-Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/49153633/

10-09 12:55