Reputation: 113
exception is :Exception in thread "main" java.lang.ClassCastException: [Ljava.security.cert.Certificate; cannot be cast to [Ljava.security.cert.X509Certificate;
in keystore.jks file, it has one entry, its alias is "/btsmed-1/certh-1/necert-1", certificate chain in this keystore.jks file was set into by this method:
keystore.setKeyEntry(alias, Keys.keyPair().getPrivate(),KEY_STORE_PASSWORD.toCharArray(), certChain);
keystore.store(out, KEY_STORE_PASSWORD.toCharArray());
before I re-load jks to keystore, when execute this statement:
X509Certificate[] certs1 = (X509Certificate[])keystore.getCertificateChain(alias);
it will not throw cast exception.
but after keystore.load(fIn, password); it will throw cast exception when execute this statement:
X509Certificate[] certs1 = (X509Certificate[]) keystore.getCertificateChain(alias);
====================below is source code.
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));
}
}
Upvotes: 0
Views: 1140
Reputation: 4840
It is because the java compiler doesn't know if all the objects in the Certificate[]
returned by the getCertificateChain()
method contains only X509Certificate
[even though the X509Certificate
is the only class that extends the Certificate
class as of now].
So if you need the X509Certificate[]
you have to loop through the Certificate[]
, like below:
Certificate[] certChain = ks.getCertificateChain("ALIAS");
X509Certificate[] x509CertChain = new X509Certificate[certChain.length];
for (int i = 0; i < certChain.length; i++)
x509CertChain[i] = (X509Certificate) certChain[i];
Upvotes: 1
Reputation: 137
try this one
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));
}
}
got it insted of imporing javax.security.cert.X509Certificate use java.security.cert.X509Certificate
Upvotes: 0