OLD | NEW |
(Empty) | |
| 1 # Copyright (c) 2012 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 """Helper module for ASN.1/DER encoding.""" |
| 6 |
| 7 import binascii |
| 8 import struct |
| 9 |
| 10 # Tags as defined by ASN.1. |
| 11 INTEGER = 2 |
| 12 BIT_STRING = 3 |
| 13 NULL = 5 |
| 14 OBJECT_IDENTIFIER = 6 |
| 15 SEQUENCE = 0x30 |
| 16 |
| 17 |
| 18 def Data(tag, data): |
| 19 """Generic type-length-value encoder. |
| 20 |
| 21 Args: |
| 22 tag: the tag. |
| 23 data: the data for the given tag. |
| 24 |
| 25 Returns: |
| 26 encoded TLV value. |
| 27 """ |
| 28 if len(data) == 0: |
| 29 return struct.pack(">BB", tag, 0); |
| 30 assert len(data) <= 0xffff; |
| 31 return struct.pack(">BBH", tag, 0x82, len(data)) + data; |
| 32 |
| 33 |
| 34 def Integer(value): |
| 35 """Encodes an integer. |
| 36 |
| 37 Args: |
| 38 value: the long value. |
| 39 |
| 40 Returns: |
| 41 encoded TLV value. |
| 42 """ |
| 43 data = '%x' % value |
| 44 return Data(INTEGER, binascii.unhexlify('00' + '0' * (len(data) % 2) + data)) |
| 45 |
| 46 |
| 47 def Bitstring(value): |
| 48 """Encodes a bit string. |
| 49 |
| 50 Args: |
| 51 value: a string holding the binary data. |
| 52 |
| 53 Returns: |
| 54 encoded TLV value. |
| 55 """ |
| 56 return Data(BIT_STRING, '\x00' + value) |
| 57 |
| 58 |
| 59 def Sequence(values): |
| 60 """Encodes a sequence of other values. |
| 61 |
| 62 Args: |
| 63 values: the list of values, must be strings holding already encoded data. |
| 64 |
| 65 Returns: |
| 66 encoded TLV value. |
| 67 """ |
| 68 return Data(SEQUENCE, ''.join(values)) |
OLD | NEW |