• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python2.7
2# Copyright 2019 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Helper module for ASN.1/DER encoding."""
7
8import binascii
9import struct
10
11# Tags as defined by ASN.1.
12INTEGER = 2
13BIT_STRING = 3
14NULL = 5
15OBJECT_IDENTIFIER = 6
16SEQUENCE = 0x30
17
18def 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  Returns:
25    encoded TLV value.
26  """
27  if len(data) < 128:
28    return struct.pack(">BB", tag, len(data)) + data;
29  assert len(data) <= 0xffff;
30  return struct.pack(">BBH", tag, 0x82, len(data)) + data;
31
32def Integer(value):
33  """Encodes an integer.
34
35  Args:
36    value: the long value.
37  Returns:
38    encoded TLV value.
39  """
40  data = '%x' % value
41  if (len(data) % 2 == 1):
42    # Odd number of non-zero bytes - pad out our data to a full number of bytes.
43    data = '0' + data
44
45  # If the high bit is set, need to prepend a null byte to denote a positive
46  # number.
47  if (int(data[0], 16) >= 8):
48    data = '00' + data
49
50  return Data(INTEGER, binascii.unhexlify(data))
51
52def Bitstring(value):
53  """Encodes a bit string.
54
55  Args:
56    value: a string holding the binary data.
57  Returns:
58    encoded TLV value.
59  """
60  return Data(BIT_STRING, '\x00' + value)
61
62def Sequence(values):
63  """Encodes a sequence of other values.
64
65  Args:
66    values: the list of values, must be strings holding already encoded data.
67  Returns:
68    encoded TLV value.
69  """
70  return Data(SEQUENCE, ''.join(values))
71