从 X500Name 解码 DER 编码值

Decode DER-encoded valued from X500Name

我有一个 java.security.util.DerValue 从 X500Name 中检索到的。

x500Name.findMostSpecificAttribute(SOME_OID)

一些值存储为 DER 编码。 .toString returns 我有点儿小事:

[DerValue, tag = 18, length = 12]

如何解码?

此外,无法从中获取 bytes[]。

derValue.getOctetString

returns我

java.io.IOException: DerValue.getOctetString, not an Octet String: 18

编辑:

我的解决方案是:

def decodeDERValue(derValue: DerValue): String = {
    val asnInput = new ASN1InputStream(new ByteArrayInputStream(derValue.toByteArray))

    val obj = asnInput.readObject()
    val derValueSting = obj match {
      case p: DERPrintableString => p.getString
      case p: DERUTF8String => p.getString
      case p: DERIA5String => p.getString
      case _ => ASN1Dump.dumpAsString(obj, true)
    }
   asnInput.close()

   derValueSting.trim
}

那是 Sun 内部 class,它叫做 sun.security.util.DerValue,而不是 java.security.util.DerValue。 ASN.1 类型由标签中的信息标识。因此,它取决于标签,您可以从 DerValue 检索什么样的数据。可以找到更多信息 in this book or in the standards 8824-1 and 8825-1.

但是,您不应依赖 Sun 内部 classes。如果你可以在 byte[] 中获得底层 DER 编码,你可以使用例如用于解析 BER/DER.

的 Bouncy Castle

class 提供了各种构造函数和方法。

1) 试试这个class的其他方法。怎么样

toByteArray()
getDataBytes()
getAsString() // calls toPrintableString internally

?我不能肯定地说,只是仔细查看了字节码。

2) 如果显式调用构造函数,请尝试从提供给构造函数的参数中获取内容。