x690.types

The type classes of X.690 and the decode() function.

Every class wraps a Python value and encodes it with bytes. X690Type is the base class: subclassing it registers a new universal, application or private type with decode(). Context-specific types are declared on their enclosing type with X690Type.CHILD_TYPES. The documentation pages “Supported types” and “Custom types” describe the classes and how to add new ones.

class x690.types.BitString(value=UNINITIALISED)

Bases: X690Type[Bits]

The BIT STRING type, tag 0x03, holding a Bits.

Construct it from a Bits value, or from bytes for a string of whole octets such as a key or a signature. The contents start with the number of unused bits. Decoding raises ValueError if that number is above 7, or not 0 for an empty string. Unused bits that are not zero are kept, but ignored.

Only the primitive encoding is supported.

>>> bytes(BitString(b"\x01\x02"))
b'\x03\x03\x00\x01\x02'
>>> decode(b"\x03\x02\x05\xa0")[0].value
Bits(b'\xa0', unused=5)
Parameters:
value=UNINITIALISED

The bits, or whole octets as bytes.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 3

The x690 identifier for the type

static decode_raw(data, slc=slice(None, None, None))

Decode the content octets into a Bits.

Empty contents decode to an empty value.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

Bits

Returns:

The decoded bits.

Raises:

ValueError – if the number of unused bits is invalid.

encode_raw()

Overrides X690Type.encode_raw()

Return type:

bytes

class x690.types.Bits(data=b'', unused=0)

Bases: object

The value of a BitString: a string of bits.

It holds the octets and the number of unused bits at the end of the last octet, so a decoded value encodes back without loss. Bit 0 is the most significant bit of the first octet, as in ASN.1 named bit lists such as the X.509 KeyUsage.

>>> flags = Bits.from_bin("101")
>>> flags
Bits(b'\xa0', unused=5)
>>> len(flags), flags[0], flags[1]
(3, True, False)
>>> str(flags)
'101'

Equality and hashing look at the bits only: the unused bits of the last octet are ignored, as they are on indexing and iteration.

Parameters:
data=b''

The octets.

unused=0

The number of unused bits at the end of the last octet, from 0 to 7. It must be 0 if data is empty.

Raises:

ValueError – if unused is out of range.

classmethod from_bin(text)

Create a value from a string of "0" and "1".

>>> Bits.from_bin("10000001")
Bits(b'\x81')
Parameters:
text

The bits, bit 0 first.

Return type:

Bits

Returns:

A new value, with the last octet padded with zeros.

Raises:

ValueError – if text holds other characters.

is_set(index)

Return whether bit index is 1, where bits past the end are 0.

Use it for named bit lists: DER drops their trailing zero bits, so a set of flags is often shorter than the list of names.

>>> Bits.from_bin("1").is_set(5)
False
Parameters:
index

The position of the bit, 0 being the first.

Return type:

bool

Returns:

Whether the bit is set.

Raises:

ValueError – if index is negative.

class x690.types.BmpString(value=UNINITIALISED)

Bases: X690Type[str]

The BMPString type, tag 0x1E, holding a str encoded as UTF-16-BE.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 30

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets with the character set of the type.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The decoded text.

Raises:

UnicodeDecodeError – if the data is invalid for the character set of the type.

encode_raw()

Overrides X690Type.encode_raw()

Raises:
  • UnicodeEncodeError – if the value contains characters that the character set of the type cannot represent.

  • ValueError – if the value contains characters outside of the alphabet of the type.

Return type:

bytes

class x690.types.Boolean(value=UNINITIALISED)

Bases: X690Type[bool]

The BOOLEAN type, tag 0x01, holding a bool.

Encoding writes one content octet: 0x01 for true, 0x00 for false.

NATURE = [TypeNature.PRIMITIVE]

The x690 “private/constructed” information

TAG : int = 1

The x690 identifier for the type

static decode_raw(data, slc=slice(None, None, None))

Decode the content octets as a bool.

Any content other than a single zero octet is true.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

bool

Returns:

The decoded value.

encode_raw()

Overrides X690Type.encode_raw()

Return type:

bytes

classmethod validate(data)

Overrides X690Type.validate()

Parameters:
data

A complete encoded value, starting with the type octet.

Raises:

ValueError – If the type octet is not that of a BOOLEAN or the length is not 1.

Return type:

None

class x690.types.CharacterString(value=UNINITIALISED)

Bases: X690Type[bytes]

The CHARACTER STRING type, tag 0x1D.

The structured content (identification, string value) is not interpreted: a decoded value holds the raw content octets as bytes.

TAG : int = 29

The x690 identifier for the type

class x690.types.EOC(value=UNINITIALISED)

Bases: X690Type[bytes]

The end-of-contents marker, tag 0x00, two zero octets in total.

It terminates a constructed value of indefinite length and has no content. Its value is an empty bytes.

NATURE = [TypeNature.PRIMITIVE]

The x690 “private/constructed” information

TAG : int = 0

The x690 identifier for the type

class x690.types.EmbeddedPdv(value=UNINITIALISED)

Bases: X690Type[bytes]

The EMBEDDED PDV type, tag 0x0B, holding bytes.

The structured content (identification, data value) is not interpreted, so the value is the raw content octets.

TAG : int = 11

The x690 identifier for the type

class x690.types.Enumerated(value=UNINITIALISED)

Bases: X690Type[int]

The Enumerated type, tag 0x0A, holding an int.

The value is encoded like an Integer: as two’s-complement octets, so negative numbers are valid.

NATURE = [TypeNature.PRIMITIVE]

The x690 “private/constructed” information

SIGNED = True

Whether the content octets are read as signed numbers

TAG : int = 10

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets as a big-endian int.

The number is read as two’s complement if SIGNED is true.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

int

Returns:

The decoded number.

encode_raw()

Overrides X690Type.encode_raw()

Return type:

bytes

class x690.types.Explicit[TInnerType: X690Type[Any]](value=UNINITIALISED)

Bases: X690Type[TInnerType]

An explicitly tagged value: a constructed context-specific value that wraps exactly one inner value, as in version [0] EXPLICIT Version.

Subclass it with the TAG of the wrapper, and declare the inner type in CHILD_TYPES if it is not a globally registered type. The value is the inner value:

>>> class Version(Explicit[Integer]):
...     TAG = 0
>>> bytes(Version(Integer(2)))
b'\xa0\x03\x02\x01\x02'
>>> decode(b"\xa0\x03\x02\x01\x02", types=[Version])[0]
Version(Integer(2))
NATURE = [TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TYPECLASS : TypeClass = 'context'

The x690 type-class (universal, application, context or private)

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the inner value, resolving its tag with CHILD_TYPES.

Overrides decode_raw()

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

TInnerType

Returns:

The inner value.

Raises:

ValueError – If the wrapper holds no value.

encode_raw()

Overrides X690Type.encode_raw()

Return type:

bytes

pretty(depth=0)

Returns a prettified string with depth levels of indentation

The inner value is shown below the tag of the wrapper. See pretty().

Parameters:
depth=0

The number of indentation levels to prepend.

Return type:

str

Returns:

The text to display.

pythonize()

Return the Python value of the inner value.

Overrides pythonize()

Return type:

Any

class x690.types.External(value=UNINITIALISED)

Bases: X690Type[bytes]

The EXTERNAL type, tag 0x08, holding bytes.

The structured content (identification, data value) is not interpreted, so the value is the raw content octets.

TAG : int = 8

The x690 identifier for the type

class x690.types.GeneralString(value=UNINITIALISED)

Bases: X690Type[bytes]

The GeneralString type, tag 0x1B.

The character set is not interpreted: a decoded value holds the raw content octets as bytes, because the encoding depends on escape sequences that this library does not process.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 27

The x690 identifier for the type

class x690.types.GeneralizedTime(value=UNINITIALISED)

Bases: X690Type[datetime]

The GeneralizedTime type, tag 0x18, holding a datetime.

Decoding reads YYYYMMDDHH[MM[SS[.fff]]], optionally followed by Z or +hhmm / -hhmm (also +hh). A comma may replace the decimal point. With a zone the result is timezone-aware, without one it is naive (local time, as X.680 defines it).

Encoding writes aware datetimes in UTC with a Z, and naive ones without a zone. Microseconds are written only if they are not zero.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 24

The x690 identifier for the type

static decode_raw(data, slc=slice(None, None, None))

Decode the content octets into a datetime.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

datetime

Returns:

The decoded moment, naive if the text has no zone.

Raises:
encode_raw()

Overrides X690Type.encode_raw()

Return type:

bytes

class x690.types.GraphicString(value=UNINITIALISED)

Bases: X690Type[str]

The GraphicString type, tag 0x19, holding an ASCII str.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 25

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets with the character set of the type.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The decoded text.

Raises:

UnicodeDecodeError – if the data is invalid for the character set of the type.

encode_raw()

Overrides X690Type.encode_raw()

Raises:
  • UnicodeEncodeError – if the value contains characters that the character set of the type cannot represent.

  • ValueError – if the value contains characters outside of the alphabet of the type.

Return type:

bytes

class x690.types.IA5String(value=UNINITIALISED)

Bases: X690Type[str]

The IA5String type, tag 0x16, holding an ASCII str.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 22

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets with the character set of the type.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The decoded text.

Raises:

UnicodeDecodeError – if the data is invalid for the character set of the type.

encode_raw()

Overrides X690Type.encode_raw()

Raises:
  • UnicodeEncodeError – if the value contains characters that the character set of the type cannot represent.

  • ValueError – if the value contains characters outside of the alphabet of the type.

Return type:

bytes

class x690.types.Integer(value=UNINITIALISED)

Bases: X690Type[int]

The INTEGER type, tag 0x02, holding an int.

The value is encoded as the shortest big-endian two’s-complement octets, so negative numbers are valid and its size is not limited.

NATURE = [TypeNature.PRIMITIVE]

The x690 “private/constructed” information

SIGNED = True

Whether the content octets are read as signed numbers

TAG : int = 2

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets as a big-endian int.

The number is read as two’s complement if SIGNED is true.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

int

Returns:

The decoded number.

encode_raw()

Overrides X690Type.encode_raw()

Return type:

bytes

x690.types.LOG = <Logger x690.types (WARNING)>

Identifies a type within a lookup: its class, tag and nature

class x690.types.Null(value=UNINITIALISED)

Bases: X690Type[None]

The NULL type, tag 0x05. Its value is always None.

The content is empty. An instance is false in a boolean context.

NATURE = [TypeNature.PRIMITIVE]

The x690 “private/constructed” information

TAG : int = 5

The x690 identifier for the type

static decode_raw(data, slc=slice(None, None, None))

Return None, whatever the content octets are.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

None

Returns:

None.

encode_raw()

Overrides X690Type.encode_raw()

>>> Null().encode_raw()
b'\x00'
Return type:

bytes

classmethod validate(data)

Overrides X690Type.validate()

Parameters:
data

A complete encoded value, starting with the type octet.

Raises:

ValueError – If the type octet is not that of a NULL or the length is not 0.

Return type:

None

class x690.types.NumericString(value=UNINITIALISED)

Bases: X690Type[str]

The NumericString type, tag 0x12, holding a str.

Decoding accepts any ASCII. Encoding accepts only digits and the space and raises ValueError for anything else.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 18

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets with the character set of the type.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The decoded text.

Raises:

UnicodeDecodeError – if the data is invalid for the character set of the type.

encode_raw()

Overrides X690Type.encode_raw()

Raises:
  • UnicodeEncodeError – if the value contains characters that the character set of the type cannot represent.

  • ValueError – if the value contains characters outside of the alphabet of the type.

Return type:

bytes

class x690.types.ObjectDescriptor(value=UNINITIALISED)

Bases: X690Type[str]

The ObjectDescriptor type, tag 0x07, holding an ASCII str.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 7

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets with the character set of the type.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The decoded text.

Raises:

UnicodeDecodeError – if the data is invalid for the character set of the type.

encode_raw()

Overrides X690Type.encode_raw()

Raises:
  • UnicodeEncodeError – if the value contains characters that the character set of the type cannot represent.

  • ValueError – if the value contains characters outside of the alphabet of the type.

Return type:

bytes

class x690.types.ObjectIdentifier(value=UNINITIALISED)

Bases: X690Type[str]

Represents an OID.

Instances of this class support containment checks to determine if one OID is a sub-item of another:

>>> ObjectIdentifier("1.2.3.4.5") in ObjectIdentifier("1.2.3")
True

>>> ObjectIdentifier("1.2.4.5.6") in ObjectIdentifier("1.2.3")
False
Parameters:
value=UNINITIALISED

The dotted notation of the identifier, such as "1.3.6.1". A leading dot is dropped.

NATURE = [TypeNature.PRIMITIVE]

The x690 “private/constructed” information

TAG : int = 6

The x690 identifier for the type

childof(other)

Convenience method to check whether this OID is a child of another OID

An identifier is a child of itself.

>>> ObjectIdentifier("1.2.3.4").childof(ObjectIdentifier("1.2.3"))
True
Parameters:
other

The identifier to test.

Return type:

bool

Returns:

True if this identifier is other or below it.

collapse_identifiers()

Meld the first two octets into one octet as defined by x.690

In x.690 ObjectIdentifiers are a sequence of numbers. In the byte-representation the first two of those numbers are stored in the first byte.

This function takes a “human-readable” OID tuple and returns a new tuple with the first two elements merged (collapsed) together.

>>> ObjectIdentifier("1.3.6.1.4.1").collapse_identifiers()
(43, 6, 1, 4, 1)
>>> ObjectIdentifier().collapse_identifiers()
()
Return type:

tuple[int, ...]

static decode_large_value(current_char, stream)

If we encounter a value larger than 127, we have to consume from the stream until we encounter a value below 127 and recombine them.

See: https://msdn.microsoft.com/en-us/library/bb540809(v=vs.85).aspx

>>> ObjectIdentifier.decode_large_value(0x81, iter([0x48]))
200
Parameters:
current_char

The first octet of the arc. It must be above 127, otherwise it is the whole arc.

stream

The following octets. Octets are consumed up to and including the last one of the arc.

Return type:

int

Returns:

The recombined number.

Raises:

StopIteration – If stream ends before the arc is complete.

static decode_raw(data, slc=slice(None, None, None))

Decode the content octets into the dotted notation.

The first octet holds the first two arcs. Empty content gives an empty string.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The dotted identifier.

Raises:

ValueError – If the last arc is incomplete.

static encode_large_value(value)

Inverse function of decode_large_value()

>>> ObjectIdentifier.encode_large_value(200)
[129, 72]
Parameters:
value

The number to encode as one arc.

Return type:

list[int]

Returns:

The octets of the arc, each but the last with the high bit set.

encode_raw()

Overrides X690Type.encode_raw()

Return type:

bytes

property nodes : tuple[int, ...]

Returns the numerical nodes for this instance as tuple

>>> ObjectIdentifier("1.2.3").nodes
(1, 2, 3)
>>> ObjectIdentifier().nodes
()
parentof(other)

Convenience method to check whether this OID is a parent of another OID

An identifier is a parent of itself.

>>> ObjectIdentifier("1.2.3").parentof(ObjectIdentifier("1.2.3.4"))
True
Parameters:
other

The identifier to test.

Return type:

bool

Returns:

True if other is this identifier or below it.

class x690.types.OctetString(value=b'')

Bases: X690Type[bytes]

The OCTET STRING type, tag 0x04, holding bytes.

The content is arbitrary binary data without a character encoding, so it is kept as raw bytes.

Parameters:
value=b''

The octets. A str is encoded as ASCII.

Raises:

UnicodeEncodeError – If value is a str with non-ASCII characters.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 4

The x690 identifier for the type

pretty(depth=0)

Returns a prettified string with depth levels of indentation

If the content is itself an encoded value, it is shown decoded in a box, otherwise as a hexdump. See pretty().

Parameters:
depth=0

The number of indentation levels to prepend.

Return type:

str

Returns:

The text to display.

class x690.types.PrintableString(value=UNINITIALISED)

Bases: X690Type[str]

The PrintableString type, tag 0x13, holding a str.

Decoding accepts any ASCII, because real data often breaks the alphabet. Encoding accepts only A-Z, a-z, 0-9, the space and '()+,-./:=?, and raises ValueError for anything else.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 19

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets with the character set of the type.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The decoded text.

Raises:

UnicodeDecodeError – if the data is invalid for the character set of the type.

encode_raw()

Overrides X690Type.encode_raw()

Raises:
  • UnicodeEncodeError – if the value contains characters that the character set of the type cannot represent.

  • ValueError – if the value contains characters outside of the alphabet of the type.

Return type:

bytes

class x690.types.Real(value=UNINITIALISED)

Bases: X690Type[float]

The REAL type, tag 0x09, holding a float.

Decoding reads every form of X.690 section 8.5: zero, the special values (infinities, NaN and minus zero), binary in base 2, 8 or 16 with a scaling factor, and decimal in the ISO 6093 forms NR1, NR2 and NR3. Malformed contents raise ValueError. A binary value outside the range of a float decodes to an infinity or to zero.

Encoding writes base 2 with an odd mantissa, as DER requires. Every finite float survives a round trip unchanged. An int is converted to a float.

>>> bytes(Real(0.5))
b'\t\x03\x80\xff\x01'
>>> decode(b"\t\x04\x01-25")[0]
Real(-25.0)
Parameters:
value=UNINITIALISED

The number. An int is converted to a float.

NATURE = [TypeNature.PRIMITIVE]

The x690 “private/constructed” information

TAG : int = 9

The x690 identifier for the type

static decode_raw(data, slc=slice(None, None, None))

Decode the content octets into a float.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

float

Returns:

The decoded number. Empty content is 0.0.

Raises:

ValueError – if the contents are not a valid REAL.

encode_raw()

Overrides X690Type.encode_raw()

Return type:

bytes

class x690.types.RelativeOid(value=UNINITIALISED)

Bases: X690Type[str]

The RELATIVE-OID type, tag 0x0D, holding a dotted str such as "8571.3.2".

The arcs are encoded like those of an ObjectIdentifier, but the first two are not merged into one octet.

NATURE = [TypeNature.PRIMITIVE]

The x690 “private/constructed” information

TAG : int = 13

The x690 identifier for the type

static decode_raw(data, slc=slice(None, None, None))

Decode the content octets into the dotted notation.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The dotted arcs. Empty content gives an empty string.

Raises:

ValueError – if the last arc is not complete.

encode_raw()

Overrides X690Type.encode_raw()

Raises:

ValueError – if an arc is not a non-negative integer.

Return type:

bytes

class x690.types.Sequence(value=UNINITIALISED)

Bases: X690Type[list[X690Type[Any]]]

Represents an X.690 sequence type. Instances of this class are iterable and indexable.

TAG : int = 16

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode every item of the value, resolving the tags with child_lookup().

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

list[X690Type[Any]]

Returns:

The decoded items, in order.

detach()

Overrides X690Type.detach()

Also resets the cached item offsets, which refer to the old buffer.

Return type:

Self

encode_raw()

Overrides X690Type.encode_raw()

Return type:

bytes

static item_offsets(data, slc=slice(None, None, None))

Return the start index of every item in the value at slc.

Only the type and length headers are read; no item is decoded.

Parameters:
data

The buffer holding the encoded items.

slc=slice(None, None, None)

The location of the items within data.

Return type:

array[int]

Returns:

The start index of each item within data.

Raises:

X690Error – If an item announces more data than available.

pretty(depth=0)

Returns a prettified string with depth levels of indentation

Each item is shown as a bullet. See pretty().

Parameters:
depth=0

The number of indentation levels to prepend.

Return type:

str

Returns:

The text to display.

pythonize()

Overrides pythonize()

Return type:

list[X690Type[Any]]

property value : list[X690Type[Any]]

The items of this value.

Overrides value

class x690.types.Set(value=UNINITIALISED)

Bases: X690Type[list[X690Type[Any]]]

The SET type, tag 0x11, holding a list of x690 values.

It behaves like Sequence: it is iterable and indexable, and a decoded value reads its items lazily. The items keep the order in which they were given or decoded; they are not sorted as DER requires.

>>> value = Set([Integer(1), Boolean(True)])
>>> bytes(value)
b'1\x06\x02\x01\x01\x01\x01\x01'
>>> decode(bytes(value))[0]
Set([Integer(1), Boolean(True)])
TAG : int = 17

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode every item of the value, resolving the tags with child_lookup().

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

list[X690Type[Any]]

Returns:

The decoded items, in order.

detach()

Overrides X690Type.detach()

Also resets the cached item offsets, which refer to the old buffer.

Return type:

Self

encode_raw()

Overrides X690Type.encode_raw()

Return type:

bytes

static item_offsets(data, slc=slice(None, None, None))

Return the start index of every item in the value at slc.

Only the type and length headers are read; no item is decoded.

Parameters:
data

The buffer holding the encoded items.

slc=slice(None, None, None)

The location of the items within data.

Return type:

array[int]

Returns:

The start index of each item within data.

Raises:

X690Error – If an item announces more data than available.

pretty(depth=0)

Returns a prettified string with depth levels of indentation

Each item is shown as a bullet. See pretty().

Parameters:
depth=0

The number of indentation levels to prepend.

Return type:

str

Returns:

The text to display.

pythonize()

Overrides pythonize()

Return type:

list[X690Type[Any]]

property value : list[X690Type[Any]]

The items of this value.

Overrides value

class x690.types.T61String(value='')

Bases: X690Type[str]

The T61String (TeletexString) type, tag 0x14.

Decoding and encoding are strict ITU-T T.61 (1988), via t61codec 3. Accented letters decode to precomposed characters (b"Caf\xc2e" becomes "Café") and 0xE0 is Ω (U+03A9, GREEK CAPITAL LETTER OMEGA). Invalid T.61 raises UnicodeDecodeError, and characters without a T.61 representation raise UnicodeEncodeError.

Data written by OpenSSL is often Latin-1 rather than T.61. For such values, decode the raw bytes with bytes.decode("latin-1").

The T.61 codec is never registered globally.

Parameters:
value=''

The text. bytes are decoded as T.61.

Raises:

UnicodeDecodeError – If value is bytes that are not valid T.61.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 20

The x690 identifier for the type

static decode_raw(data, slc=slice(None, None, None))

Decode the content octets as T.61 text.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The decoded text.

Raises:

UnicodeDecodeError – if the data is not valid T.61.

encode_raw()

Overrides X690Type.encode_raw()

Raises:

UnicodeEncodeError – if the value cannot be represented in T.61.

Return type:

bytes

class x690.types.TWrappedPyType

The Python type wrapped by an X690Type

alias of TypeVar(‘TWrappedPyType’, bound=Any)

x690.types.UNINITIALISED = UNINITIALISED

sentinel value for uninitialised objects (used for lazy decoding)

class x690.types.Uninitialised

Bases: object

The type of UNINITIALISED, the only instance.

It marks a value that has not been decoded yet.

class x690.types.UniversalString(value=UNINITIALISED)

Bases: X690Type[str]

The UniversalString type, tag 0x1C, holding a str encoded as UTF-32-BE.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 28

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets with the character set of the type.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The decoded text.

Raises:

UnicodeDecodeError – if the data is invalid for the character set of the type.

encode_raw()

Overrides X690Type.encode_raw()

Raises:
  • UnicodeEncodeError – if the value contains characters that the character set of the type cannot represent.

  • ValueError – if the value contains characters outside of the alphabet of the type.

Return type:

bytes

class x690.types.UnknownType(value=b'', tag=-1)

Bases: X690Type[bytes]

A fallback type for anything not in X.690.

Instances of this class contain the raw information as parsed from the bytes as the following attributes:

  • value: The value without leading metadata (as bytes value)

  • tag: The unparsed “tag”. This is the type ID as defined in the reference document. See TypeInfo for details.

  • typeinfo: unused (derived from tag and only here for consistency with __repr__ of this class).

Parameters:
value=b''

The content octets.

tag=-1

The unparsed identifier octet of the value.

TAG : int = 153

The x690 identifier for the type

pretty(depth=0)

Returns a prettified string with depth levels of indentation

The content is shown as a hexdump, shortened if it is long. See pretty().

Parameters:
depth=0

The number of indentation levels to prepend.

Return type:

str

Returns:

The text to display.

class x690.types.UtcTime(value=UNINITIALISED)

Bases: X690Type[datetime]

The UTCTime type, tag 0x17, holding a timezone-aware datetime.

Decoding reads YYMMDDhhmm[ss] followed by Z or +hhmm / -hhmm. Years 50 to 99 are 1950 to 1999, years 00 to 49 are 2000 to 2049 (the rule of X.509).

Encoding converts to UTC and writes YYMMDDhhmmssZ. Fractions of a second are dropped. A naive datetime or a year outside 1950 to 2049 raises ValueError.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 23

The x690 identifier for the type

static decode_raw(data, slc=slice(None, None, None))

Decode the content octets into an aware datetime.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

datetime

Returns:

The decoded moment.

Raises:
encode_raw()

Overrides X690Type.encode_raw()

Raises:

ValueError – if the value is naive or the year is outside of 1950 to 2049.

Return type:

bytes

class x690.types.Utf8String(value=UNINITIALISED)

Bases: X690Type[str]

The UTF8String type, tag 0x0C, holding a str.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 12

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets with the character set of the type.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The decoded text.

Raises:

UnicodeDecodeError – if the data is invalid for the character set of the type.

encode_raw()

Overrides X690Type.encode_raw()

Raises:
  • UnicodeEncodeError – if the value contains characters that the character set of the type cannot represent.

  • ValueError – if the value contains characters outside of the alphabet of the type.

Return type:

bytes

class x690.types.VideotexString(value=UNINITIALISED)

Bases: X690Type[bytes]

The VideotexString type, tag 0x15.

The character set is not interpreted: a decoded value holds the raw content octets as bytes, because the encoding depends on escape sequences that this library does not process.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 21

The x690 identifier for the type

class x690.types.VisibleString(value=UNINITIALISED)

Bases: X690Type[str]

The VisibleString type, tag 0x1A, holding an ASCII str.

NATURE = [TypeNature.PRIMITIVE, TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = 26

The x690 identifier for the type

classmethod decode_raw(data, slc=slice(None, None, None))

Decode the content octets with the character set of the type.

Parameters:
data

A data-block containing the content octets.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

str

Returns:

The decoded text.

Raises:

UnicodeDecodeError – if the data is invalid for the character set of the type.

encode_raw()

Overrides X690Type.encode_raw()

Raises:
  • UnicodeEncodeError – if the value contains characters that the character set of the type cannot represent.

  • ValueError – if the value contains characters outside of the alphabet of the type.

Return type:

bytes

class x690.types.X690Type[TWrappedPyType: Any](value=UNINITIALISED)

Bases: Generic[TWrappedPyType]

The superclass for all supported types.

An instance wraps one Python value of type TWrappedPyType. It is created either from that value, to be encoded, or by decode(), which keeps the encoded bytes and converts them to a Python value only when value is first read. Subclassing registers a new type; see Add custom types.

Parameters:
value=UNINITIALISED

The Python value to wrap. The default, UNINITIALISED, creates an empty instance that from_bytes() fills with encoded bytes.

CHILD_TYPES : ClassVar[Collection[type[X690Type[Any]]]] = ()

The types of the values inside this one. Their tags are looked up here before the global registry, and context-specific tags only here. Assign a new collection to change it after the class statement.

NATURE = [TypeNature.CONSTRUCTED]

The x690 “private/constructed” information

TAG : int = -1

The x690 identifier for the type

TYPECLASS : TypeClass = 'universal'

The x690 type-class (universal, application, context or private)

static all()

Returns all globally registered classes

Return type:

list[type[X690Type[Any]]]

classmethod child_lookup()

Return CHILD_TYPES as a read-only lookup keyed by (TYPECLASS, TAG, nature).

The lookup is built once, and again only after a new collection is assigned to CHILD_TYPES.

Raises:

ValueError – If two child types share the same key.

Return type:

Mapping[tuple[TypeClass, int, TypeNature], type[X690Type[Any]]]

classmethod decode(data)

Decode a complete encoded value, starting at its type octet, into a new instance of this class.

The type octet is not checked; call validate() first for that.

>>> Integer.decode(b"\x02\x01\x05")
Integer(5)
Parameters:
data

The encoded value including type and length octets.

Return type:

TConcreteType

Returns:

A new instance holding the decoded value.

Raises:

X690Error – If the length exceeds the available data.

static decode_raw(data, slc=slice(None, None, None))

Converts the raw byte-value (without type & length header) into a pure Python type

>>> Integer.decode_raw(b"\x05")
5
Parameters:
data

A data-block containing the byte-information

slc=slice(None, None, None)

A slice of the data-block that contains the exact raw-bytes.

Return type:

TWrappedPyType

Returns:

The value that should be wrapped by the current x690 type.

detach()

Copy the value’s own content bytes and drop the reference to the buffer it was decoded from.

Use this to keep a few values from a large document without keeping the whole document alive. Values that were not created from a buffer are left unchanged.

>>> data = b"\x02\x01\x05" + bytes(1000)
>>> value, _ = decode(data)
>>> value.detach() is value
True
>>> value.raw_bytes
b'\x05'
Return type:

Self

Returns:

This instance.

encode_raw()

Convert this instance into raw x690 bytes (excluding the type and length header)

>>> import x690.types as t
>>> Integer(5).encode_raw()
b'\x05'
>>> Boolean(True).encode_raw()
b'\x01'
>>> X690Type(t.UNINITIALISED).encode_raw()
b''
Return type:

bytes

classmethod from_bytes(data, slc=slice(None, None, None))

Creates a new x690.types.X690Type instance from raw-bytes (without type nor length bytes)

>>> Integer.from_bytes(b"\x01")
Integer(1)
>>> OctetString.from_bytes(b"hello-world")
OctetString(b'hello-world')
>>> Boolean.from_bytes(b"\x00")
Boolean(False)
Parameters:
data

A buffer containing the content octets. It is shared, not copied.

slc=slice(None, None, None)

The location of the content octets within data.

Return type:

TConcreteType

Returns:

A new instance that decodes its value on first access.

Raises:

X690Error – If the class cannot be created without arguments.

static get(typeclass, typeid, nature=TypeNature.CONSTRUCTED)

Retrieve a globally registered class by x690 type information.

Subclassing x690.types.X690Type registers universal, application and private types. Context-specific types are never registered: they are declared in CHILD_TYPES of the enclosing type.

>>> X690Type.get("universal", 2, TypeNature.PRIMITIVE)
<class 'x690.types.Integer'>
Parameters:
typeclass

The value of a TypeClass: "universal", "application" or "private".

typeid

The tag number of the type.

nature=TypeNature.CONSTRUCTED

Whether the type is primitive or constructed.

Return type:

type[X690Type[Any]]

Returns:

The registered class.

Raises:
  • KeyError – If no class is registered for the type.

  • ValueError – If typeclass is not a valid type class.

property length : int

Return the x690 byte-length of this instance

pretty(depth=0)

Returns a readable representation (possibly multiline) of the value.

The value is indented by depth levels of indentation

By default this simply returns the string representation. But more complex values may override this.

Parameters:
depth=0

The number of indentation levels to prepend.

Return type:

str

Returns:

The text to display.

pythonize()

Convert this instance to an appropriate pure Python object.

Return type:

TWrappedPyType

pyvalue : TWrappedPyType | Uninitialised

The decoded (or to-be encoded) Python value

property raw_bytes : bytes

The value’s own content bytes, without the type and length header.

For decoded values this is a copy of the bytes at the value’s location in the input buffer.

classmethod validate(data)

Given a bytes object, checks if the given class cls supports decoding this object. If not, raises a ValueError.

Only the type class and the tag are compared, not the nature.

>>> Integer.validate(b"\x02\x01\x05")
>>> Integer.validate(b"\x04\x01\x05")
Traceback (most recent call last):
...
ValueError: Invalid type header! Expected a ...
Parameters:
data

A complete encoded value, starting with the type octet.

Raises:
Return type:

None

property value : TWrappedPyType

Returns the value as a pure Python type

x690.types.decode(data, start_index=0, enforce_type=None, strict=False, types=())

Convert a X.690 bytes object into a Python instance, and the location of the next object.

Given a bytes object and any start-index, inspects and parses the octets starting at the given index (as many as required) to determine variable type (and corresponding Python class), and length. That class is then used to parse the object located in data at the given index. The location of the start of the next (subsequent) object is also determined.

The return value is a tuple with the decoded object and the start-index of the next object.

Example:

>>> data = b'\x02\x01\x05\x11'
>>> decode(data)
(Integer(5), 3)
>>> data = b'some-skippable-bytes\x02\x01\x05\x11'
>>> decode(data, 20)
(Integer(5), 23)
Parameters:
data

The buffer to read from. It is never copied.

start_index=0

The position of the value in data.

enforce_type=None

Raise UnexpectedType unless the value is an instance of this class.

strict=False

Raise IncompleteDecoding if data is left after the value.

types=()

Classes to try before the global registry for this value, as CHILD_TYPES does for the items of a constructed type. Use it to decode a context-specific value on its own.

Return type:

tuple[TPopType, int]

Returns:

The value and the index of the next value.