• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/python2.5
2# Copyright (c) 2011 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) == 0:
28    return struct.pack(">BB", tag, 0);
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  return Data(INTEGER, binascii.unhexlify('00' + '0' * (len(data) % 2) + data))
42
43def Bitstring(value):
44  """Encodes a bit string.
45
46  Args:
47    value: a string holding the binary data.
48  Returns:
49    encoded TLV value.
50  """
51  return Data(BIT_STRING, '\x00' + value)
52
53def Sequence(values):
54  """Encodes a sequence of other values.
55
56  Args:
57    values: the list of values, must be strings holding already encoded data.
58  Returns:
59    encoded TLV value.
60  """
61  return Data(SEQUENCE, ''.join(values))
62