我正在尝试使用X509CertificateObject序列化和反序列化Bouncy Castle org.apache.commons.lang3.SerializationUtils
显然,反序列化对象的类型(sun.security.x509.X509CertImpl)与原始序列化对象(org.bouncycastle.jce.provider.X509CertificateObject)的类型不同。因此,铸造失败。
我究竟做错了什么?

public static void test(X509CertificateObject certObj) {
    byte[] serializedObj;
    Object deSerializedObj;
    X509CertificateObject deSerializedCertObj;
    X509Certificate deSerializedCert;

    System.out.println("certObj type: " + certObj.getClass().getName());
    serializedObj = SerializationUtils.serialize(certObj);
    deSerializedObj = SerializationUtils.deserialize(serializedObj);
    System.out.println("deSerializedObj type: " + deSerializedObj.getClass().getName());
    deSerializedCert = (X509Certificate) deSerializedObj;
    System.out.println("deSerializedCert type: " + deSerializedCert.getClass().getName());
    deSerializedCertObj = (X509CertificateObject) deSerializedObj;
    System.out.println("deSerializedCertObj type: " + deSerializedCertObj.getClass().getName());
}


结果是:

certObj type: org.bouncycastle.jce.provider.X509CertificateObject
deSerializedObj type: sun.security.x509.X509CertImpl
deSerializedCert type: sun.security.x509.X509CertImpl


终于在

java.lang.ClassCastException: sun.security.x509.X509CertImpl cannot be cast to org.bouncycastle.jce.provider.X509CertificateObject
at Test.test(Test.java:1010)
at Test.main(Test.java:153)


是因为X509CertificateObject的上层类(即X509Certificate)是抽象的,和/或是因为X509CertificateObject没有定义自己的serialVersionUID吗?

最佳答案

只需将其强制转换为java.security.cert.X509Certificate,其他所有类均应扩展。您当然不应该期望或使用sun.*类。

09-04 14:46