我是 ASN1 表示法的新手,我对无法继续进行的地方感到震惊。我可以使用 ASN1Dump.dumpAsString() 转储输出 [引用自 link]
我能够得到一个转储(见下面的例子)。但我想提取个人值(value)并使用它们。如何将其转换为类或访问单个 oid?
Sequence
DER Set
Sequence
ObjectIdentifier(1.3.6.1.4.1.4843.1.1)
PrintableString(testValue1)
DER Set
Sequence
ObjectIdentifier(1.3.6.1.4.1.4843.1.2)
PrintableString(testValue2)
DER Set
Sequence
ObjectIdentifier(1.3.6.1.4.1.4843.1.3)
PrintableString(testValue3)
我想要这样的东西..
t.getValue("1.3.6.1.4.1.4843.1.1") should return testValue1 where t is of type some TestClass which contains members of testValue1,testValue2,testValue3.
提前致谢..
最佳答案
我假设,如果您可以使用 ASN1Dump
,那么您已经拥有具有上述结构的对象。
对于这个答案,我创建了相同的结构(因为我没有您的原始数据),但有细微差别(DERSequence
而不仅仅是 Sequence
), 但逻辑基本相同。
您需要解析 asn1 结构并存储所需的字段。对于此代码,我使用了 bouncycaSTLe 1.46 jdk1.6。
首先,您使用解析对象的构造函数创建 TestClass
(与您传递给 ASN1Dump.dumpAsString()
的对象相同)。我假设它是一个 DERSequence
- 可能是,但它也可以是 ASN1Sequence
(执行 obj.getClass()
以确保)。代码不会改变因为 ASN1Sequence
是 DERSequence
的父类(super class),使用的方法属于父类(super class)。
public class TestClass {
// this map will contain the values (key is 1.3.6.etc and value is testValue1, testValue2...)
private Map<String, String> fields = new HashMap<String, String>();
public TestClass(DERSequence sequence) {
// parse objects from sequence
Enumeration<?> objects = sequence.getObjects();
while (objects.hasMoreElements()) {
DERSet set = (DERSet) objects.nextElement(); // casting because I know from dump it's a DERSet
// I'm assuming it's a DERSequence, but do a System.out.println(set.getObjectAt(0).getClass()) to make sure and cast accordinly
DERSequence seq = (DERSequence) set.getObjectAt(0);
// I'm assuming it's a DERObjectIdentifier, but do a System.out.println(set.getObjectAt(0).getClass()) to make sure and cast accordinly
DERObjectIdentifier oid = (DERObjectIdentifier) seq.getObjectAt(0); // this object contains 1.3.6.etc...
// I'm assuming it's a DERPrintableString, but do a System.out.println(set.getObjectAt(1).getClass()) to make sure and cast accordinly
DERPrintableString str = (DERPrintableString) seq.getObjectAt(1);
// store the values in the map
fields.put(oid.getId(), str.getString());
}
}
public String getValue(String oid) {
// optional: you can check for null, or if oid exists (fields.contains(oid)), and return "" or null when it doesn't
return fields.get(oid);
}
}
之后,你可以这样使用TestClass
:
// assuming seq is the object you passed to ASN1Dump.dumpAsString
// check if its type is DERSequence (do a seq.getClass() to check)
// if it's another type of sequence, change the TestClass code accordingly, as already explained above
TestClass t = new TestClass(seq);
System.out.println(t.getValue("1.3.6.1.4.1.4843.1.1")); // prints testValue1
PS:请注意,我刚刚按照 ASN1Dump
打印的结构进行了解析:
- 该对象是一个包含 3 个集合的序列
- 每个集合只包含一个元素,这是一个序列
- 每个序列包含 2 个元素:一个对象标识符和一个可打印字符串
- 每个集合只包含一个元素,这是一个序列
我只是浏览了这些元素,直到找到我想要的元素。
关于java - 将 ASN1Dump.dumpAsString 的输出转换为 java 中的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42949777/