作为密码学的菜鸟,我每天都会偶然发现一些简单的事情。今天只是那些日子之一。
我想用 bouncy castle 库验证 java 中的 smime 消息,我想我几乎已经弄清楚了,但此时的问题是 PKIXparameters 对象的构建。
假设我有一个具有以下结构的最终实体 x509 证书:
root certificate
+->intermediate certificate
+->end-entity certificate
为了验证消息,我需要首先构建信任链,但我无法弄清楚如何从最终实体提取根证书和中间证书。
我尝试使用最终实体作为根,但它不起作用:
InputStream isCert = GetFISCertificate();
List list = new ArrayList();
X509Certificate rootCert = (X509Certificate) certificateFactory.generateCertificate(isCert);
list.add(rootCert);
CollectionCertStoreParameters params = new CollectionCertStoreParameters(list);
CertStore store = CertStore.getInstance("Collection", params, BC);
//create cert path
List certChain = new ArrayList();
certChain.add(rootCert);
CertPath certPath = certificateFactory.generateCertPath(certChain);
Set trust = Collections.singleton(new TrustAnchor(rootCert, null));
//validation
CertPathValidator certPathValidator = CertPathValidator.getInstance("PKIX", BC);
PKIXParameters pKIXParameters = new PKIXParameters(trust);
pKIXParameters.addCertStore(store);
pKIXParameters.setDate(new Date());
try {
CertPathValidatorResult result = certPathValidator.validate(certPath, pKIXParameters);
System.out.println("certificate path validated");
} catch (CertPathValidatorException e) {
System.out.println("validation failed on certificate number " + e.getIndex() + ", details: " + e.getMessage());
}
得到这个异常:
validation failed on certificate number -1, details: Trust anchor for certification path not found.
顺便说一句,我可以只使用最终实体证书来验证消息,就像它是自签名证书一样吗?