|
3 | 3 | ASN.1 Reference |
4 | 4 | =============== |
5 | 5 |
|
6 | | -.. currentmodule:: cryptography.hazmat.asn1 |
| 6 | +.. module:: cryptography.hazmat.asn1 |
7 | 7 |
|
8 | 8 | This module provides a declarative interface for defining ASN.1 structures |
9 | 9 | and serializing/deserializing them to/from DER-encoded data. |
@@ -46,7 +46,7 @@ Serialization |
46 | 46 | Serialize an ASN.1 object into DER-encoded bytes. |
47 | 47 |
|
48 | 48 | :param value: The ASN.1 object to encode. Must be an instance of a |
49 | | - class decorated with :func:`sequence`, or a primitive ASN.1 type |
| 49 | + class decorated with :func:`sequence` or :func:`set`, or a primitive ASN.1 type |
50 | 50 | (``int``, ``bool``, ``bytes``, ``str``, |
51 | 51 | :class:`~cryptography.x509.ObjectIdentifier`, |
52 | 52 | :class:`PrintableString`, :class:`IA5String`, :class:`UTCTime`, |
@@ -102,6 +102,40 @@ that have no direct Python equivalent: |
102 | 102 | >>> asn1.decode_der(AlgorithmIdentifier, encoded).algorithm |
103 | 103 | 9 |
104 | 104 |
|
| 105 | +.. decorator:: set |
| 106 | + |
| 107 | + A class decorator that registers a class as an ASN.1 ``SET``. Fields |
| 108 | + are defined as class-level type annotations. The decorator adds an |
| 109 | + ``__init__`` method with keyword-only parameters. |
| 110 | + |
| 111 | + ``SET`` is similar to ``SEQUENCE``, but the fields are encoded in |
| 112 | + ascending order by tag, rather than in definition order. When |
| 113 | + decoding, fields must appear in the correct ascending order. |
| 114 | + |
| 115 | + Fields can be annotated with :class:`Explicit`, :class:`Implicit`, |
| 116 | + :class:`Default`, and :class:`Size` using :class:`typing.Annotated`. |
| 117 | + |
| 118 | + .. doctest:: |
| 119 | + |
| 120 | + >>> from cryptography.hazmat import asn1 |
| 121 | + >>> @asn1.set |
| 122 | + ... class Example: |
| 123 | + ... x: int |
| 124 | + ... y: int |
| 125 | + >>> encoded = asn1.encode_der(Example(x=1, y=2)) |
| 126 | + >>> decoded = asn1.decode_der(Example, encoded) |
| 127 | + >>> decoded.x |
| 128 | + 1 |
| 129 | + >>> decoded.y |
| 130 | + 2 |
| 131 | + >>> # Decoding DER data where fields are not in sorted order |
| 132 | + >>> # raises an error: |
| 133 | + >>> wrong_order = b'\x31\x06\x02\x01\x02\x02\x01\x01' |
| 134 | + >>> asn1.decode_der(Example, wrong_order) |
| 135 | + Traceback (most recent call last): |
| 136 | + ... |
| 137 | + ValueError: error parsing asn1 value: ... |
| 138 | + |
105 | 139 | .. class:: PrintableString(value) |
106 | 140 |
|
107 | 141 | Wraps ASN.1 ``PrintableString`` values. ``PrintableString`` is a restricted |
|
0 commit comments