Skip to content

Commit 1604b8c

Browse files
authored
asn1: Add docs for SET (#14657)
1 parent 099a711 commit 1604b8c

File tree

1 file changed

+35
-1
lines changed

1 file changed

+35
-1
lines changed

docs/hazmat/asn1/reference.rst

Lines changed: 35 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ Serialization
4646
Serialize an ASN.1 object into DER-encoded bytes.
4747

4848
: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
5050
(``int``, ``bool``, ``bytes``, ``str``,
5151
:class:`~cryptography.x509.ObjectIdentifier`,
5252
:class:`PrintableString`, :class:`IA5String`, :class:`UTCTime`,
@@ -102,6 +102,40 @@ that have no direct Python equivalent:
102102
>>> asn1.decode_der(AlgorithmIdentifier, encoded).algorithm
103103
9
104104

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+
105139
.. class:: PrintableString(value)
106140

107141
Wraps ASN.1 ``PrintableString`` values. ``PrintableString`` is a restricted

0 commit comments

Comments
 (0)