How does ASN.1 encode an object identifier?

后端 未结 4 1161
春和景丽
春和景丽 2020-12-08 07:50

I am having trouble understanding the basic concepts of ASN.1.

If a type is an OID, does the corresponding number get actually encoded in the binary data?

Fo

4条回答
  •  [愿得一人]
    2020-12-08 07:59

    This is a simplistic Python 3 implementation of the of above, resp. a string form of an object identifier into ASN.1 DER or BER form.

    def encode_variable_length_quantity(v:int) -> list:
        # Break it up in groups of 7 bits starting from the lowest significant bit
        # For all the other groups of 7 bits than lowest one, set the MSB to 1
        m = 0x00
        output = []
        while v >= 0x80:
            output.insert(0, (v & 0x7f) | m)
            v = v >> 7
            m = 0x80
        output.insert(0, v | m)
        return output
    
    def encode_oid_string(oid_str:str) -> tuple:
        a = [int(x) for x in oid_str.split('.')]
        oid = [a[0]*40 + a[1]] # First two items are coded by a1*40+a2
        # A rest is Variable-length_quantity
        for n in a[2:]:
            oid.extend(encode_variable_length_quantity(n))
        oid.insert(0, len(oid)) # Add a Length
        oid.insert(0, 0x06) # Add a Type (0x06 for Object Identifier)
        return tuple(oid)
    
    if __name__ == '__main__':
        oid = encode_oid_string("1.2.840.10045.3.1.7")
        print(oid)
    

提交回复
热议问题