如何在Java中解码DER编码的字符串?

我正在尝试从数字证书中读取自定义扩展程序。 我知道值是在DER中编码的GeneralString。 有没有一种简单的方法来正确解码它并获得Java String? 我尝试了以下内容,但是’s’包含了一些编码元数据作为字符串开头的垃圾字符。

byte[] ext = cert.getExtensionValue("1.2.3.4"); String s= new String(ext); System.out.println(s); 

有没有快速简便的方法来做到这一点? 或者我真的需要使用一些完整的ASN.1库吗?

谢谢!

BouncyCastle ( 除此之外 ):

用于读取和编写编码的ASN.1对象的库。

使用下页中包含的说明,我做了一些更改,代码与我一起工作正常。

从BC早期版本发布到1.47及更高版本 – 充气城堡军团 http://www.bouncycastle.org/wiki/display/JA1/Porting+from+earlier+BC+releases+to+1.47+and+later

 private String getExtensionValue(X509Certificate X509Certificate, String oid) throws IOException { String decoded = null; byte[] extensionValue = X509Certificate.getExtensionValue(oid); if (extensionValue != null) { ASN1Primitive derObject = toDERObject(extensionValue); if (derObject instanceof DEROctetString) { DEROctetString derOctetString = (DEROctetString) derObject; derObject = toDERObject(derOctetString.getOctets()); if (derObject instanceof ASN1String) { ASN1String s = (ASN1String)derObject; decoded = s.getString(); } } } return decoded; } /** * From http://stackoverflow.com/questions/2409618/how-do-i-decode-a-der-encoded-string-in-java */ private ASN1Primitive toDERObject(byte[] data) throws IOException { ByteArrayInputStream inStream = new ByteArrayInputStream(data); ASN1InputStream asnInputStream = new ASN1InputStream(inStream); return asnInputStream.readObject(); } 

对于BouncyCastle来说,结果非常简单:

 private String getExtensionValue(X509Certificate X509Certificate, String oid) throws IOException { String decoded = null; byte[] extensionValue = X509Certificate.getExtensionValue(oid); if (extensionValue != null) { DERObject derObject = toDERObject(extensionValue); if (derObject instanceof DEROctetString) { DEROctetString derOctetString = (DEROctetString) derObject; derObject = toDERObject(derOctetString.getOctets()); if (derObject instanceof DERUTF8String) { DERUTF8String s = DERUTF8String.getInstance(derObject); decoded = s.getString(); } } } return decoded; } private DERObject toDERObject(byte[] data) throws IOException { ByteArrayInputStream inStream = new ByteArrayInputStream(data); ASN1InputStream asnInputStream = new ASN1InputStream(inStream); return asnInputStream.readObject(); } 

在Oracle VM中:

  DerValue val = new DerValue(ext); String s = val.getGeneralString(); 

http://www.docjar.com/docs/api/sun/security/util/DerValue.html

JcaX509ExtensionUtils以更简单的方式完成上述答案。

 X509Certificate certificate; byte[] encodedExtensionValue = certificate.getExtensionValue(oid); if (encodedExtensionValue != null) { ASN1Primitive extensionValue = JcaX509ExtensionUtils .parseExtensionValue(encodedExtensionValue); String values = extensionValue.toString(); }