使用BouncyCastle创建CertificationRequestInfo时ASN1Set属性报错求助
问题描述
尝试使用从SCEP服务器获取的挑战密码创建证书请求(CSR)时,因attrs对象问题无法创建CertificationRequestInfo。使用空DERSet替代attrs时可成功生成CSR。
报错代码
ASN1Encodable[] attrValues = new ASN1Encodable[1]; attrValues[0] = new Attribute(PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERSet(new DERPrintableString(challenge))); ASN1Set attrs = new DERSet(attrValues); CertificationRequestInfo requestInfo = new CertificationRequestInfo(new X500Name(subject), pkInfo, attrs);
错误信息
Exception in thread "main" java.lang.IllegalArgumentException: unknown object in factory: org.bouncycastle.asn1.x509.Attribute at org.bouncycastle.asn1.pkcs.Attribute.getInstance(Attribute.java:37) at org.bouncycastle.asn1.pkcs.CertificationRequestInfo.validateAttributes(CertificationRequestInfo.java:159) at org.bouncycastle.asn1.pkcs.CertificationRequestInfo.<init>(CertificationRequestInfo.java:81)
解决方案
错误根源是你用错了Attribute类:
- 代码中实际导入的是
org.bouncycastle.asn1.x509.Attribute,但PKCS#10标准的CSR属性必须使用org.bouncycastle.asn1.pkcs.Attribute。
修正后的代码:
// 确保导入的是org.bouncycastle.asn1.pkcs.Attribute ASN1Encodable[] attrValues = new ASN1Encodable[1]; attrValues[0] = new org.bouncycastle.asn1.pkcs.Attribute( PKCSObjectIdentifiers.pkcs_9_at_challengePassword, new DERSet(new DERPrintableString(challenge)) ); ASN1Set attrs = new DERSet(attrValues); CertificationRequestInfo requestInfo = new CertificationRequestInfo(new X500Name(subject), pkInfo, attrs);
补充说明
PKCS#10证书请求的属性定义属于pkcs命名空间,CertificationRequestInfo在验证属性时会严格检查类型,所以使用x509包下的Attribute会触发类型不匹配的异常。
内容的提问来源于stack exchange,提问作者Arushi Pandey
相关产品推荐
相关产品推荐

