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

时间:2017-04-27 05:47:04

标签: java security x509certificate keystore private-key

异常是:线程“main”中的异常java.lang.ClassCastException:[Ljava.security.cert.Certificate;无法转换为[Ljava.security.cert.X509Certificate;

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

this._rowResult = this._agSvc.setRowResult(data);

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

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

它不会抛出强制转换异常。

但是在keystore.load(fIn,password)之后;它会在执行此语句时抛出强制转换异常:

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

====================以下是源代码。

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

2 个答案:

答案 0 :(得分:1)

这是因为java编译器不知道Certificate[]方法返回的getCertificateChain()中的所有对象是否仅包含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];

答案 1 :(得分:0)

尝试这个

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