1 # Copyright (c) 2011 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.
5 """Helper module for ASN.1/DER encoding."""
10 # Tags as defined by ASN.1.
18 """Generic type-length-value encoder.
22 data: the data for the given tag.
27 return struct
.pack(">BB", tag
, len(data
)) + data
;
28 assert len(data
) <= 0xffff;
29 return struct
.pack(">BBH", tag
, 0x82, len(data
)) + data
;
32 """Encodes an integer.
35 value: the long value.
40 if (len(data
) % 2 == 1):
41 # Odd number of non-zero bytes - pad out our data to a full number of bytes.
44 # If the high bit is set, need to prepend a null byte to denote a positive
46 if (int(data
[0], 16) >= 8):
49 return Data(INTEGER
, binascii
.unhexlify(data
))
52 """Encodes a bit string.
55 value: a string holding the binary data.
59 return Data(BIT_STRING
, '\x00' + value
)
62 """Encodes a sequence of other values.
65 values: the list of values, must be strings holding already encoded data.
69 return Data(SEQUENCE
, ''.join(values
))