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 | |
Nirnimesh
2012/04/10 17:48:55
nit: need 2 blank lines here
| |
17 def Data(tag, data): | |
18 """Generic type-length-value encoder. | |
19 | |
20 Args: | |
21 tag: the tag. | |
22 data: the data for the given tag. | |
23 | |
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 | |
32 | |
33 def Integer(value): | |
34 """Encodes an integer. | |
35 | |
36 Args: | |
37 value: the long value. | |
38 | |
39 Returns: | |
40 encoded TLV value. | |
41 """ | |
42 data = '%x' % value | |
43 return Data(INTEGER, binascii.unhexlify('00' + '0' * (len(data) % 2) + data)) | |
44 | |
45 | |
46 def Bitstring(value): | |
47 """Encodes a bit string. | |
48 | |
49 Args: | |
50 value: a string holding the binary data. | |
51 | |
52 Returns: | |
53 encoded TLV value. | |
54 """ | |
55 return Data(BIT_STRING, '\x00' + value) | |
56 | |
57 | |
58 def Sequence(values): | |
59 """Encodes a sequence of other values. | |
60 | |
61 Args: | |
62 values: the list of values, must be strings holding already encoded data. | |
63 | |
64 Returns: | |
65 encoded TLV value. | |
66 """ | |
67 return Data(SEQUENCE, ''.join(values)) | |
OLD | NEW |