蟒蛇。对象标识符转换ASN1

时间:2015-02-26 11:31:03

标签: python encoding asn.1

我试图在Python中实现ASN1的自定义对象标识符,这些是示例测试用例。

    asn1_objectidentifier([1,2])
    asn1_objectidentifier([1,2,840])
    asn1_objectidentifier([1,2,840,5,1000000])
    asn1_objectidentifier([1,2,840,5,127,128,129])

我无法做的是在base 128中编码value3 ... value n 到目前为止这是我的代码

def asn1_objectidentifier(oid):
    first_octet = 40 * oid[0] + oid[1]
    rest = ""
    length = 1
    for v in range(2, len(oid)):
       if oid[v] < 127:
          rest += chr(oid[v])
          length += 1
       else:
          rem = oid[v] / 128
          first = (rem * 128) ^ 1
          second = (oid[v] - first) * 128 ^ 0
          rest += int_to_bytestring(first)
          rest += int_to_bytestring(second)
          length += 2 
rest = chr(first_octet) + rest
return chr(0x06) + chr(length) + rest 

2 个答案:

答案 0 :(得分:2)

优秀文章A Layman's Guide to a Subset of ASN.1, BER, and DER详细描述了这一点,并且 - 最有价值的 - 提供了许多优秀的测试用例和边缘案例。

顺便说一句:该文件似乎没有网络上的规范主页。以上是CiteseerX参考信息的链接;其他PDF存在;和HTML versions

答案 1 :(得分:1)

这是对128进行整数值编码的方法&gt; -1:

def base128_encode(n): # int/long to byte string
    if n > 0:
        arr = []
        while n:
            n, rem = divmod(n, 128)
            arr.append(chr(rem))
        return ''.join(reversed(arr))
    elif n == 0:
        return '\x00'
    else:
        raise ValueError

print [ord(c) for c in base128_encode(840)]  # --> [6, 72]