using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Linq;
using Newtonsoft.Json;
namespace LTEMvcApp.Models
{
///
/// ASN1解析器,用于解析GSER格式的ASN1数据
///
public class ASN1Parser
{
private static readonly Regex RegExpOpen = new Regex(@"((?! )[\w-\s]+(?
/// 从GSER格式的字符串数组解析ASN1数据
///
/// GSER格式的字符串数组
/// 解析后的ASN1对象
public static Dictionary FromGSER(string[] data)
{
if (data == null || data.Length == 0)
return null;
var root = (ASN1Node)null;
var stack = new Stack();
try
{
int i = 0;
// 移除十六进制转储
for (; i < data.Length; i++)
{
var d = data[i];
if (!RegExpHexDump.IsMatch(d))
break;
}
for (; i < data.Length; i++)
{
var d = data[i];
// 移除注释
for (int j = 0; j < 10; j++) // 最多10次迭代
{
var c0 = d.IndexOf("/*");
if (c0 < 0) break;
var c1 = d.IndexOf("*/");
if (c1 >= 0)
{
d = d.Remove(c0, c1 + 2 - c0);
}
else
{
d = d.Substring(0, c0);
for (i++; i < data.Length; i++)
{
var d1 = data[i];
var c2 = d1.IndexOf("*/");
if (c2 >= 0)
{
d += d1.Substring(c2 + 2);
break;
}
}
}
}
var match = RegExpOpen.Match(d);
if (match.Success)
{
var node = new ASN1Node { Name = match.Groups[1].Success ? match.Groups[1].Value.Trim() : null };
if (root == null) root = node;
stack.Push(node);
continue;
}
if (stack.Count == 0) continue;
match = RegExpClose.Match(d);
if (match.Success)
{
var node = stack.Pop();
if (stack.Count == 0) // 结束
break;
AddProperty(stack.Peek(), node.Name, node.Obj ?? new Dictionary());
continue;
}
// 数值常量
match = RegExpValueNum.Match(d);
if (match.Success)
{
AddProperty(stack.Peek(), match.Groups[1].Value, int.Parse(match.Groups[2].Value));
}
// 通用字符串
else if ((match = RegExpValueEnumerated.Match(d)).Success)
{
var value = match.Groups[2].Value;
switch (value)
{
case "TRUE":
AddProperty(stack.Peek(), match.Groups[1].Value, true);
break;
case "FALSE":
AddProperty(stack.Peek(), match.Groups[1].Value, false);
break;
default:
AddProperty(stack.Peek(), match.Groups[1].Value, value);
break;
}
}
// 带基本值的Choice
else if ((match = RegExpValueChoice.Match(d)).Success)
{
AddProperty(stack.Peek(), match.Groups[1].Value,
new Dictionary
{
["choice"] = match.Groups[2].Value,
["value"] = match.Groups[3].Value
});
}
else if ((match = RegExpValueListNum.Match(d)).Success)
{
AddProperty(stack.Peek(), null, int.Parse(match.Groups[1].Value));
}
else if ((match = RegExpValueListMisc.Match(d)).Success)
{
AddProperty(stack.Peek(), null, match.Groups[1].Value);
}
}
// 验证解析结果
if (root == null)
return null;
if (stack.Count != 0)
{
// 栈不为空说明解析不完整,返回null
return null;
}
// 确保返回的是Dictionary类型
if (root.Obj is Dictionary dict)
{
return dict;
}
else if (root.Obj is List