如何修复此异常:java.lang.ClassCastException 线程"main"中的异常



异常是:线程中的异常" java.lang.classcastException:[ljava.security.cert.cert.certificate;不能施放给[ljava.security.cert.x509certificate;

在keystore.jks文件中,它有一个条目,其别名为"/btsmed-1/certh-1/necert-1",此方法将此keystore.jks文件中的证书链设置为:

keystore.setKeyEntry(alias, Keys.keyPair().getPrivate(),KEY_STORE_PASSWORD.toCharArray(), certChain);
keystore.store(out, KEY_STORE_PASSWORD.toCharArray());

在执行此语句时,我将JKS重新加载到KeyStore之前:

X509Certificate[] certs1 = (X509Certificate[])keystore.getCertificateChain(alias);

它不会抛出异常。

但是,在keystore.load之后(fin,password(;执行此语句时,它将抛出铸件例外:

X509Certificate[] certs1 = (X509Certificate[]) keystore.getCertificateChain(alias);

=====================下面是源代码。

public class KeystoreLoad {
    public static void main(String[] args) throws Exception {
      char[] password = "nokia123".toCharArray();
      String alias = "/btsmed-1/certh-1/necert-1";
      KeyStore keystore = KeyStore.getInstance("JKS");
      keystore.load(null, null);
      FileInputStream fIn = new FileInputStream("d://keystore/keystore.jks");
      keystore.load(fIn, password);
      X509Certificate[] certs1 = (X509Certificate[]) keystore.getCertificateChain(alias);
      System.out.println(Arrays.toString(certs1));
    }
}

这是因为java编译器不知道getCertificateChain()方法返回的Certificate[]中的所有对象是否仅包含X509Certificate [即使X509Certificate是唯一扩展Certificate类的类截至目前]。

因此,如果您需要X509Certificate[],则必须循环穿过Certificate[],如下:

Certificate[] certChain = ks.getCertificateChain("ALIAS");
X509Certificate[] x509CertChain = new X509Certificate[certChain.length];
for (int i = 0; i < certChain.length; i++)
    x509CertChain[i] = (X509Certificate) certChain[i];

尝试这个

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.Arrays;
import java.security.cert.X509Certificate;
public class TestDemo {
    public static void main(String[] args) throws Exception {
        char[] password = "nokia123".toCharArray();
        String alias = "/btsmed-1/certh-1/necert-1";
        KeyStore keystore = KeyStore.getInstance("JKS");
        keystore.load(null, null);
        FileInputStream fIn = new FileInputStream("d://keystore/keystore.jks");
        keystore.load(fIn, password);
        keystore.getCertificateChain(alias);
        X509Certificate[] certs1 = (X509Certificate[]) keystore.getCertificateChain(alias);
        System.out.println(Arrays.toString(certs1));
    }
}

使它启动了Javax.Security.cert.x509certificate使用 java.security.cert.x509certificate

相关内容

  • 没有找到相关文章

最新更新