我在 Java 中使用 bouncycastle
CertificateFactory.getInstance("X509", "BC")
certFactory.generateCertificate(in)
生成证书。它工作正常。但是当我使用
x509Certificate.getExtensionValue("1.2.3.4.5.6.7")
返回值与membersrvc 的不匹配。我错过了什么?
我在 Java 中使用 bouncycastle
CertificateFactory.getInstance("X509", "BC")
certFactory.generateCertificate(in)
生成证书。它工作正常。但是当我使用
x509Certificate.getExtensionValue("1.2.3.4.5.6.7")
返回值与membersrvc 的不匹配。我错过了什么?
使用 bouncycastle,您可以执行此操作来提取扩展的 ASN1 结构
public ASN1Primitive getExtensionValue(X509Certificate certificate, String oid) throws IOException {
byte[] bytes = certificate.getExtensionValue(oid);
if (bytes == null) {
return null;
}
ASN1InputStream aIn = new ASN1InputStream(new ByteArrayInputStream(bytes));
ASN1OctetString octs = (ASN1OctetString) aIn.readObject();
aIn = new ASN1InputStream(new ByteArrayInputStream(octs.getOctets()));
return aIn.readObject();
}
ASN1 是一个复杂的对象,您需要对其进行解析以获取所需的字段。例如,返回在给定 X509 证书中找到的 CA URI 元数据。
public String getIssuerURL(final X509Certificate certificate) throws Exception {
final ASN1ObjectIdentifier ocspAccessMethod = X509ObjectIdentifiers.id_ad_caIssuers;
final byte[] authInfoAccessExtensionValue = certificate.getExtensionValue(Extension.authorityInfoAccess.getId());
if (null == authInfoAccessExtensionValue) {
return null;
}
ASN1InputStream ais1 = null;
ASN1InputStream ais2 = null;
try {
final ByteArrayInputStream bais = new ByteArrayInputStream(authInfoAccessExtensionValue);
ais1 = new ASN1InputStream(bais);
final DEROctetString oct = (DEROctetString) (ais1.readObject());
ais2 = new ASN1InputStream(oct.getOctets());
final AuthorityInformationAccess authorityInformationAccess = AuthorityInformationAccess.getInstance(ais2.readObject());
final AccessDescription[] accessDescriptions = authorityInformationAccess.getAccessDescriptions();
for (AccessDescription accessDescription : accessDescriptions) {
final boolean correctAccessMethod = accessDescription.getAccessMethod().equals(ocspAccessMethod);
if (!correctAccessMethod) {
continue;
}
final GeneralName gn = accessDescription.getAccessLocation();
if (gn.getTagNo() != GeneralName.uniformResourceIdentifier) {
continue;
}
final DERIA5String str = (DERIA5String) ((DERTaggedObject) gn.toASN1Primitive()).getObject();
final String accessLocation = str.getString();
return accessLocation;
}
return null;
} catch (IOException e) {
throw new Exception(e);
} finally {
IOUtils.closeQuietly(ais1);
IOUtils.closeQuietly(ais2);
}
}
从 ASN1Primitive 返回人类可读的字符串
public String getStringFromGeneralName(ASN1Primitive names) throws IOException {
ASN1TaggedObject taggedObject = (ASN1TaggedObject) names ;
return new String(ASN1OctetString.getInstance(taggedObject, false).getOctets(), "ISO-8859-1");
}