OLD | NEW |
---|---|
(Empty) | |
1 #!/usr/bin/env python | |
2 # Copyright (c) 2012 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 | |
8 import binascii | |
9 import struct | |
10 | |
11 # Tags as defined by ASN.1. | |
12 INTEGER = 2 | |
Nirnimesh
2012/04/05 19:05:30
global vars local to this file should have _ prefi
bartfab (slow)
2012/04/10 15:27:20
I had actually copied this file from another place
| |
13 BIT_STRING = 3 | |
14 NULL = 5 | |
15 OBJECT_IDENTIFIER = 6 | |
16 SEQUENCE = 0x30 | |
17 | |
Nirnimesh
2012/04/05 19:05:30
nit: need 2 blank lines between functions in globa
bartfab (slow)
2012/04/10 15:27:20
Done.
| |
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. | |
Nirnimesh
2012/04/05 19:05:30
nit: leave a blank line before Returns: section
Re
bartfab (slow)
2012/04/10 15:27:20
Done.
| |
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 def 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 | |
43 def 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 | |
53 def 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)) | |
OLD | NEW |