简短的回答:您需要递归地遍历树以找到包含 DerObjectIdentifier 的 DerSequence,然后返回 DerObjectIdentifiers 下一个兄弟。
长答案:查看 ASN1/DER 结构,对象图中似乎没有一个条目具有 OID 和值。似乎对于特定的 OID,它将是 DerSequence 中的第一个子对象,而值将是第二个子对象。
一个递归方法将找到包含与您的 OID 匹配的 DerObjectIdentifier 的 DerSequence 并返回下一个兄弟姐妹:
public static Asn1Object FindAsn1Value(string oid, Asn1Object obj)
{
Asn1Object result = null;
if (obj is Asn1Sequence)
{
bool foundOID = false;
foreach (Asn1Object entry in (Asn1Sequence)obj)
{
var derOID = entry as DerObjectIdentifier;
if (derOID != null && derOID.Id == oid)
{
foundOID = true;
}
else if (foundOID)
{
return entry;
}
else
{
result = FindAsn1Value(oid, entry);
if (result != null)
{
return result;
}
}
}
}
else if (obj is DerTaggedObject)
{
result = FindAsn1Value(oid, ((DerTaggedObject)obj).GetObject());
if (result != null)
{
return result;
}
}
else
{
if (obj is DerSet)
{
foreach (Asn1Object entry in (DerSet)obj)
{
result = FindAsn1Value(oid, entry);
if (result != null)
{
return result;
}
}
}
}
return null;
}
要调用它,您将使用您提供的方法加载 Asn1Object,然后调用上面显示的 FindAsn1Value。这应该返回您所追求的 Asn1Object(在我的测试 cat 文件的情况下,该值是一个 DerOctetString)。
Asn1Object asn = asn1Object(File.ReadAllBytes(@"test_file.cat"));
Asn1Object value = FindAsn1Value("1.3.6.1.4.1.311.12.2.1", asn);
if (value is DerOctetString)
{
UnicodeEncoding unicode = new UnicodeEncoding(true, true);
Console.WriteLine("DerOctetString = {0}", unicode.GetString(((DerOctetString)value).GetOctets()));
}
我不确定该 OID 的值是否始终是 DerOctetString,也不确定我的解码选择是否一定正确,但是它为我提供了我的测试正在使用的值的最易读版本。
更新
如果相同的 OID 在层次结构中出现多次并且您需要返回所有可能的值,则另一种方法可能是:
public static List<Asn1Object> FindAsn1Values(string oid, Asn1Object obj)
{
Asn1Object result = null;
List<Asn1Object> results = new List<Asn1Object>();
if (obj is Asn1Sequence)
{
bool foundOID = false;
foreach (Asn1Object entry in (Asn1Sequence)obj)
{
var derOID = entry as DerObjectIdentifier;
if (derOID != null && derOID.Id == oid)
{
foundOID = true;
}
else if (foundOID)
{
results.Add(entry);
}
else
{
result = FindAsn1Values(oid, entry);
if (result.Count > 0)
{
results.AddRange(result);
}
}
}
}
else if (obj is DerTaggedObject)
{
result = FindAsn1Values(oid, ((DerTaggedObject)obj).GetObject());
if (result.Count > 0)
{
results.AddRange(result);
}
}
else
{
if (obj is DerSet)
{
foreach (Asn1Object entry in (DerSet)obj)
{
result = FindAsn1Values(oid, entry);
if (result.Count > 0)
{
results.AddRange(result);
}
}
}
}
return results;
}