pyasn1 vs不定长度结构

时间:2019-06-22 15:30:40

标签: python asn.1 pyasn1

pyasn1 不能单独解析(未定义新类型)以下代码片段中描述的不确定长度的构造数据的错误,还是我的示例不是有效的BER编码的ASN。 1?

如果pyasn1在没有帮助的情况下无法处理此问题,那么我可以转向另一个python库吗?


# e7 80       : private, constructed, tag 7, indefinite length
#    02 01 44 : integer 0x44
#    02 01 55 : integer 0x55
#    00 00    : end of contents (terminating the 0xe7 object)
data = 'e7 80 02 01 44 02 01 55 00 00'

data = binascii.unhexlify( ''.join(data.split()) )

# throws pyasn1.error.PyAsn1Error: Missing end-of-octets terminator
pyasn1.codec.ber.decoder.decode(data)

2 个答案:

答案 0 :(得分:1)

您的示例完全有效(BER编码)

您甚至可以使用https://asn1.io/asn1playground/来证明

编译以下架构:

Schema DEFINITIONS EXPLICIT TAGS ::= 
BEGIN
  ASequence::= [PRIVATE 7] IMPLICIT SEQUENCE       
  {                                                     
    num1 INTEGER,
    num2 INTEGER
  }                                                     
END

并解码e7 80 02 01 44 02 01 55 00 00

结果将是:

> OSS ASN-1Step Version 9.0.1 Copyright (C) 2019 OSS Nokalva, Inc.  All
> rights reserved. This product is licensed for use by "OSS Nokalva,
> Inc."
> 
> C0043I: 0 error messages, 0 warning messages and 0 informatory
> messages issued.
> 
> 
> ASN1STEP: Decoding PDU #1 :
> 
> ASequence SEQUENCE: tag = [PRIVATE 7] constructed; length = indef  
> num1 INTEGER: tag = [UNIVERSAL 2] primitive; length = 1
>     68   
> num2 INTEGER: tag = [UNIVERSAL 2] primitive; length = 1
>     85 
> EOC 
> Successfully decoded 10 bytes. rec1value ASequence ::=  {   num1 68,   num2 85 }

请注意,您不需要使用架构来对此进行解码(只需松开语义即可)

您将需要pyasn1的见解。尝试在此处打开一个问题:https://github.com/etingof/pyasn1/issues

答案 1 :(得分:-1)

您的示例数据似乎格式不正确。我不知道详细信息,但它似乎涉及数据的第一个字节'e7'。我了解这是邮件的“类型”。看来这种类型必须期望比您提供的数据更多。

我看到了一些示例,这些示例使用“ 30”作为第一个字节,代表一个“序列”。这些示例的格式非常类似于您的示例。因此,我尝试在示例数据中将“ e7”替换为“ 30”,并且通过此更改,您的代码可以正常运行。

要清楚我的意思,这段代码对我来说没有错误:

# 30 80       : sequence, indefinite length
#    02 01 44 : integer 0x44
#    02 01 55 : integer 0x55
#    00 00    : end of contents (terminating the 0x30 object)
data = '30 80 02 01 44 02 01 55 00 00'

data = binascii.unhexlify( ''.join(data.split()) )

# throws pyasn1.error.PyAsn1Error: Missing end-of-octets terminator
pyasn1.codec.ber.decoder.decode(data)

我相信这表明您的代码“正确”。我希望我对这方面的东西有更多的了解,以便为您提供更多帮助,例如向您解释“ e7”类型的含义。没有这个,我希望这仍然会有所帮助。

相关问题