Convert::ASN1解码错误

Convert::ASN1 decode error

我一定是遗漏了一些非常明显的东西。我可以使用像 http://asn1-playground.oss.com/ 这样的在线工具来解码这个样本数据位,但是我在使用 Perl 的 Convert::ASN1 时遇到了问题。知道我错过了什么吗?

use strict;
use warnings;
use Convert::ASN1;
use feature 'say';

# example from:
# http://www.oss.com/asn1/resources/asn1-made-simple/introduction.html

my $hex_data = '3018800A4A6F686E20536D697468810A39383736353433323130';
my $bin_data = join '', pack 'H*', $hex_data;

Convert::ASN1::asn_dump($bin_data);
# prints:
#    0000   24: SEQUENCE {
#    0002   10:   [CONTEXT 0]
#    0004     :     4A 6F 68 6E 20 53 6D 69 74 68 __ __ __ __ __ __ John Smith
#    000E   10:   [CONTEXT 1]
#    0010     :     39 38 37 36 35 34 33 32 31 30 __ __ __ __ __ __ 9876543210
#    001A     : }    

my $asn = Convert::ASN1->new;
$asn->prepare(<<ASN1) or die $asn->error;    
    Contact ::= SEQUENCE {
        name VisibleString,
        phone NumericString
    }
ASN1

my $asn1_node = $asn->find('Contact') 
    or die $asn->error;

my $payload = $asn1_node->decode($bin_data) 
    or die "can't decode Contact: ".$asn1_node->error;
# prints:
#    can't decode Contact: decode error 80<=>1a 2 4 name

支持下面 YaFred 的回答,这是 80 和 81 在编码字符串中的位置:

SEQ length=24 ** l=10  J  o  h n   S m i t h  ** l=10  9 8 7 6 5 4 3 2 1 0
30  18        80 0A    4A 6F 686E20536D697468 81 0A    39383736353433323130

我不确定你从哪里得到你的十六进制字符串...但是如果你使用 Convert::ASN1::encode 方法,你会得到一个略有不同的十六进制字符串,它可以被正确解码:

my $res = $asn->encode({ name => 'John Smith', phone => 9876543210 });
my $res_hex = unpack 'H*', $res;
print "res_hex after encode : $res_hex\n";
print "original hex_data    : " . lc($hex_data) . "\n";
print "\n";

my payload = $asn1_node->decode($res) or die $asn1_node->error;
use Data::Dumper;
print Dumper($payload);

输出

res_hex after encode : 30181a0a4a6f686e20536d697468120a39383736353433323130
original hex_data    : 3018800a4a6f686e20536d697468810a39383736353433323130

$VAR1 = {
      'name' => 'John Smith',
      'phone' => '9876543210'
};

可能这就像

一样简单
$asn->prepare(<<ASN1) or die $asn->error; 
My-Module DEFINITIONS AUTOMATIC TAGS ::=
BEGIN   
        Contact ::= SEQUENCE {
            name VisibleString,
            phone NumericString
        }
END
    ASN1

如果从ASN.1开始解释有点长...

您没有提供标记上下文(联系人类型应该是模块的一部分)。因此,工具正在做出选择...

你显示的hexa是用AUTOMATIC TAGS编码的结果

2 个字符串的标签是“80”(上下文标签 0 = 1000 0000)和“81”(上下文标签 1 = 1000 0001)

@xxfelixxx 得到一些不同的东西,因为编码是作为 EXPLICIT TAGS

执行的

2 个字符串的标签是“1a”(VisibleString 的通用标签)和“12”(NumericString 的通用标签)