我正在尝试从数字证书中读取自定义扩展。我知道该值是用 DER 编码的 GeneralString。有没有一种简单的方法可以正确解码并获得 Java 字符串?我尝试了以下操作,但“s”在字符串的开头包含了一些作为垃圾字符的编码元数据。
byte[] ext = cert.getExtensionValue("1.2.3.4");
String s= new String(ext);
System.out.println(s);
有没有快速简便的方法来做到这一点?或者我真的需要使用一些完整的 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();
}
关于java - 如何在 Java 中解码 DER 编码的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2409618/