python-pkcs11 0.10.1__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pkcs11/__init__.py +50 -0
- pkcs11/_pkcs11.cp315-win_amd64.pyd +0 -0
- pkcs11/_pkcs11.pxd +964 -0
- pkcs11/_pkcs11.pyi +35 -0
- pkcs11/_pkcs11.pyx +2327 -0
- pkcs11/attributes.py +272 -0
- pkcs11/constants.py +559 -0
- pkcs11/defaults.py +121 -0
- pkcs11/exceptions.py +410 -0
- pkcs11/mechanisms.py +862 -0
- pkcs11/py.typed +0 -0
- pkcs11/types.py +1457 -0
- pkcs11/util/__init__.py +17 -0
- pkcs11/util/dh.py +79 -0
- pkcs11/util/dsa.py +108 -0
- pkcs11/util/ec.py +143 -0
- pkcs11/util/rsa.py +95 -0
- pkcs11/util/x509.py +136 -0
- python_pkcs11-0.10.1.dist-info/METADATA +399 -0
- python_pkcs11-0.10.1.dist-info/RECORD +23 -0
- python_pkcs11-0.10.1.dist-info/WHEEL +5 -0
- python_pkcs11-0.10.1.dist-info/licenses/LICENSE +21 -0
- python_pkcs11-0.10.1.dist-info/top_level.txt +1 -0
pkcs11/types.py
ADDED
|
@@ -0,0 +1,1457 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Types for high level PKCS#11 wrapper.
|
|
3
|
+
|
|
4
|
+
This module provides stubs that are overrideen in pkcs11._pkcs11.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from binascii import hexlify
|
|
10
|
+
from collections.abc import Iterator
|
|
11
|
+
from functools import cached_property
|
|
12
|
+
from typing import TYPE_CHECKING, Any, Final
|
|
13
|
+
|
|
14
|
+
from pkcs11 import CancelStrategy
|
|
15
|
+
from pkcs11.constants import (
|
|
16
|
+
Attribute,
|
|
17
|
+
CertificateType,
|
|
18
|
+
MechanismFlag,
|
|
19
|
+
ObjectClass,
|
|
20
|
+
SlotFlag,
|
|
21
|
+
TokenFlag,
|
|
22
|
+
UserType,
|
|
23
|
+
)
|
|
24
|
+
from pkcs11.exceptions import (
|
|
25
|
+
ArgumentsBad,
|
|
26
|
+
AttributeTypeInvalid,
|
|
27
|
+
MultipleObjectsReturned,
|
|
28
|
+
NoSuchKey,
|
|
29
|
+
SignatureInvalid,
|
|
30
|
+
SignatureLenRange,
|
|
31
|
+
)
|
|
32
|
+
from pkcs11.mechanisms import KeyType, Mechanism
|
|
33
|
+
|
|
34
|
+
if TYPE_CHECKING:
|
|
35
|
+
from typing_extensions import Self
|
|
36
|
+
|
|
37
|
+
from pkcs11.attributes import AttributeMapper
|
|
38
|
+
|
|
39
|
+
PROTECTED_AUTH: Final[object] = object()
|
|
40
|
+
"""Indicate the pin should be supplied via an external mechanism (e.g. pin pad)"""
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class IdentifiedBy:
|
|
44
|
+
__slots__ = ()
|
|
45
|
+
|
|
46
|
+
def _identity(self) -> Any:
|
|
47
|
+
raise NotImplementedError()
|
|
48
|
+
|
|
49
|
+
def __eq__(self, other: object) -> bool:
|
|
50
|
+
return isinstance(other, IdentifiedBy) and self._identity() == other._identity()
|
|
51
|
+
|
|
52
|
+
def __hash__(self) -> int:
|
|
53
|
+
return hash(self._identity())
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _CK_UTF8CHAR_to_str(data: bytes) -> str:
|
|
57
|
+
"""
|
|
58
|
+
Convert CK_UTF8CHAR to string.
|
|
59
|
+
|
|
60
|
+
Substitutes invalid bytes with the replacement character to make usage more
|
|
61
|
+
robust with non-compliant tokens.
|
|
62
|
+
"""
|
|
63
|
+
return data.rstrip(b"\0").decode("utf-8", errors="replace").rstrip()
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _CK_VERSION_to_tuple(data: dict[str, int]) -> tuple[int, int]:
|
|
67
|
+
"""Convert CK_VERSION to tuple."""
|
|
68
|
+
return (data["major"], data["minor"])
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _CK_MECHANISM_TYPE_to_enum(mechanism: int) -> Mechanism | int:
|
|
72
|
+
"""Convert CK_MECHANISM_TYPE to enum or be okay."""
|
|
73
|
+
try:
|
|
74
|
+
return Mechanism(mechanism)
|
|
75
|
+
except ValueError:
|
|
76
|
+
return mechanism
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class MechanismInfo:
|
|
80
|
+
"""
|
|
81
|
+
Information about a mechanism.
|
|
82
|
+
|
|
83
|
+
See :meth:`pkcs11.Slot.get_mechanism_info`.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
slot: Slot
|
|
87
|
+
mechanism: Mechanism | int
|
|
88
|
+
min_key_length: int | None
|
|
89
|
+
max_key_length: int | None
|
|
90
|
+
flags: MechanismFlag
|
|
91
|
+
|
|
92
|
+
def __init__(
|
|
93
|
+
self,
|
|
94
|
+
slot: Slot,
|
|
95
|
+
mechanism: Mechanism | int,
|
|
96
|
+
ulMinKeySize: int | None = None,
|
|
97
|
+
ulMaxKeySize: int | None = None,
|
|
98
|
+
flags: int | None = None,
|
|
99
|
+
**kwargs: Any,
|
|
100
|
+
) -> None:
|
|
101
|
+
self.slot = slot
|
|
102
|
+
""":class:`pkcs11.Slot` this information is for."""
|
|
103
|
+
self.mechanism = mechanism
|
|
104
|
+
""":class:`pkcs11.mechanisms.Mechanism` this information is for."""
|
|
105
|
+
self.min_key_length = ulMinKeySize
|
|
106
|
+
"""Minimum key length in bits (:class:`int`)."""
|
|
107
|
+
self.max_key_length = ulMaxKeySize
|
|
108
|
+
"""Maximum key length in bits (:class:`int`)."""
|
|
109
|
+
self.flags = MechanismFlag(flags) if flags is not None else MechanismFlag(0)
|
|
110
|
+
"""Mechanism capabilities (:class:`pkcs11.constants.MechanismFlag`)."""
|
|
111
|
+
|
|
112
|
+
def __str__(self) -> str:
|
|
113
|
+
return "\n".join(
|
|
114
|
+
(
|
|
115
|
+
f"Supported key lengths: [{self.min_key_length}, {self.max_key_length}]",
|
|
116
|
+
f"Flags: {self.flags}",
|
|
117
|
+
)
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
def __repr__(self) -> str:
|
|
121
|
+
return f"<{type(self).__name__} (mechanism={self.mechanism!s}, flags={self.flags!s})>"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
class Slot(IdentifiedBy):
|
|
125
|
+
"""
|
|
126
|
+
A PKCS#11 device slot.
|
|
127
|
+
|
|
128
|
+
This object represents a physical or software slot exposed by PKCS#11.
|
|
129
|
+
A slot has hardware capabilities, e.g. supported mechanisms and may has
|
|
130
|
+
a physical or software :class:`Token` installed.
|
|
131
|
+
"""
|
|
132
|
+
|
|
133
|
+
__slots__ = ()
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def flags(self) -> SlotFlag:
|
|
137
|
+
"""Capabilities of this slot (:class:`SlotFlag`)."""
|
|
138
|
+
raise NotImplementedError()
|
|
139
|
+
|
|
140
|
+
@property
|
|
141
|
+
def hardware_version(self) -> tuple[int, int]:
|
|
142
|
+
"""Hardware version (:class:`tuple`)."""
|
|
143
|
+
raise NotImplementedError()
|
|
144
|
+
|
|
145
|
+
@property
|
|
146
|
+
def firmware_version(self) -> tuple[int, int]:
|
|
147
|
+
"""Firmware version (:class:`tuple`)."""
|
|
148
|
+
raise NotImplementedError()
|
|
149
|
+
|
|
150
|
+
@property
|
|
151
|
+
def cryptoki_version(self) -> tuple[int, int]:
|
|
152
|
+
"""PKCS#11 API version (:class: `tuple`)"""
|
|
153
|
+
raise NotImplementedError()
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def slot_id(self) -> int:
|
|
157
|
+
"""Slot identifier (opaque)."""
|
|
158
|
+
raise NotImplementedError()
|
|
159
|
+
|
|
160
|
+
@property
|
|
161
|
+
def slot_description(self) -> str:
|
|
162
|
+
"""Slot name (:class:`str`)."""
|
|
163
|
+
raise NotImplementedError()
|
|
164
|
+
|
|
165
|
+
@property
|
|
166
|
+
def manufacturer_id(self) -> str:
|
|
167
|
+
"""Slot/device manufacturer's name (:class:`str`)."""
|
|
168
|
+
raise NotImplementedError()
|
|
169
|
+
|
|
170
|
+
def get_token(self) -> Token:
|
|
171
|
+
"""
|
|
172
|
+
Returns the token loaded into this slot.
|
|
173
|
+
|
|
174
|
+
:rtype: Token
|
|
175
|
+
"""
|
|
176
|
+
raise NotImplementedError()
|
|
177
|
+
|
|
178
|
+
def get_mechanisms(self) -> set[Mechanism]:
|
|
179
|
+
"""
|
|
180
|
+
Returns the mechanisms supported by this device.
|
|
181
|
+
|
|
182
|
+
:rtype: set(Mechanism)
|
|
183
|
+
"""
|
|
184
|
+
raise NotImplementedError()
|
|
185
|
+
|
|
186
|
+
def get_mechanism_info(self, mechanism: Mechanism) -> MechanismInfo:
|
|
187
|
+
"""
|
|
188
|
+
Returns information about the mechanism.
|
|
189
|
+
|
|
190
|
+
:param Mechanism mechanism: mechanism to learn about
|
|
191
|
+
:rtype: MechanismInfo
|
|
192
|
+
"""
|
|
193
|
+
raise NotImplementedError()
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class Token(IdentifiedBy):
|
|
197
|
+
"""
|
|
198
|
+
A PKCS#11 token.
|
|
199
|
+
|
|
200
|
+
A token can be physically installed in a :class:`Slot`, or a software
|
|
201
|
+
token, depending on your PKCS#11 library.
|
|
202
|
+
"""
|
|
203
|
+
|
|
204
|
+
__slots__ = ()
|
|
205
|
+
|
|
206
|
+
@property
|
|
207
|
+
def flags(self) -> TokenFlag:
|
|
208
|
+
"""Capabilities of this token (:class:`TokenFlag`)."""
|
|
209
|
+
raise NotImplementedError()
|
|
210
|
+
|
|
211
|
+
@property
|
|
212
|
+
def hardware_version(self) -> tuple[int, int]:
|
|
213
|
+
"""Hardware version (:class:`tuple`)."""
|
|
214
|
+
raise NotImplementedError()
|
|
215
|
+
|
|
216
|
+
@property
|
|
217
|
+
def firmware_version(self) -> tuple[int, int]:
|
|
218
|
+
"""Firmware version (:class:`tuple`)."""
|
|
219
|
+
raise NotImplementedError()
|
|
220
|
+
|
|
221
|
+
@property
|
|
222
|
+
def slot(self) -> Slot:
|
|
223
|
+
"""The :class:`Slot` this token is installed in."""
|
|
224
|
+
raise NotImplementedError()
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def label(self) -> str:
|
|
228
|
+
"""Label of this token (:class:`str`)."""
|
|
229
|
+
raise NotImplementedError()
|
|
230
|
+
|
|
231
|
+
@property
|
|
232
|
+
def serial(self) -> bytes:
|
|
233
|
+
"""Serial number of this token (:class:`bytes`)."""
|
|
234
|
+
raise NotImplementedError()
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def manufacturer_id(self) -> str:
|
|
238
|
+
"""Manufacturer ID (:class:`str`)."""
|
|
239
|
+
raise NotImplementedError()
|
|
240
|
+
|
|
241
|
+
@property
|
|
242
|
+
def model(self) -> str:
|
|
243
|
+
"""Model name (:class:`str`)."""
|
|
244
|
+
raise NotImplementedError()
|
|
245
|
+
|
|
246
|
+
def open(
|
|
247
|
+
self,
|
|
248
|
+
rw: bool = False,
|
|
249
|
+
user_pin: str | bytes | object | None = None,
|
|
250
|
+
so_pin: str | bytes | object | None = None,
|
|
251
|
+
user_type: UserType | None = None,
|
|
252
|
+
attribute_mapper: AttributeMapper | None = None,
|
|
253
|
+
cancel_strategy: CancelStrategy = CancelStrategy.DEFAULT,
|
|
254
|
+
) -> Session:
|
|
255
|
+
"""
|
|
256
|
+
Open a session on the token and optionally log in as a user or
|
|
257
|
+
security officer (pass one of `user_pin` or `so_pin`). Pass PROTECTED_AUTH to
|
|
258
|
+
indicate the pin should be supplied via an external mechanism (e.g. pin pad).
|
|
259
|
+
|
|
260
|
+
Can be used as a context manager or close with :meth:`Session.close`.
|
|
261
|
+
|
|
262
|
+
::
|
|
263
|
+
|
|
264
|
+
with token.open() as session:
|
|
265
|
+
|
|
266
|
+
print(session)
|
|
267
|
+
|
|
268
|
+
:param rw: True to create a read/write session.
|
|
269
|
+
:param bytes user_pin: Authenticate to this session as a user.
|
|
270
|
+
:param bytes so_pin: Authenticate to this session as a
|
|
271
|
+
security officer.
|
|
272
|
+
:param user_type: Sets the userType parameter to C_Login.
|
|
273
|
+
Allows for vendor-defined values. Defaults to UserType.SO if
|
|
274
|
+
so_pin is set, otherwise UserType.USER.
|
|
275
|
+
:param attribute_mapper:
|
|
276
|
+
Optionally pass in a custom :class:`pkcs11.attributes.AttributeMapper`.
|
|
277
|
+
:param cancel_strategy:
|
|
278
|
+
Cancellation strategy for interrupted cryptographic operations.
|
|
279
|
+
|
|
280
|
+
:rtype: Session
|
|
281
|
+
"""
|
|
282
|
+
raise NotImplementedError()
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
class Session(IdentifiedBy):
|
|
286
|
+
"""
|
|
287
|
+
A PKCS#11 :class:`Token` session.
|
|
288
|
+
|
|
289
|
+
A session is required to do nearly all operations on a token including
|
|
290
|
+
encryption/signing/keygen etc.
|
|
291
|
+
|
|
292
|
+
Create a session using :meth:`Token.open`. Sessions can be used as a
|
|
293
|
+
context manager or closed with :meth:`close`.
|
|
294
|
+
"""
|
|
295
|
+
|
|
296
|
+
__slots__ = ()
|
|
297
|
+
|
|
298
|
+
def __enter__(self) -> Self:
|
|
299
|
+
return self
|
|
300
|
+
|
|
301
|
+
def __exit__(
|
|
302
|
+
self,
|
|
303
|
+
type_: type[BaseException] | None,
|
|
304
|
+
value: BaseException | None,
|
|
305
|
+
traceback: object,
|
|
306
|
+
) -> None:
|
|
307
|
+
self.close()
|
|
308
|
+
|
|
309
|
+
@property
|
|
310
|
+
def token(self) -> Token:
|
|
311
|
+
""":class:`Token` this session is on."""
|
|
312
|
+
raise NotImplementedError()
|
|
313
|
+
|
|
314
|
+
@property
|
|
315
|
+
def rw(self) -> bool:
|
|
316
|
+
"""True if this is a read/write session."""
|
|
317
|
+
raise NotImplementedError()
|
|
318
|
+
|
|
319
|
+
def close(self) -> None:
|
|
320
|
+
"""Close the session."""
|
|
321
|
+
raise NotImplementedError()
|
|
322
|
+
|
|
323
|
+
def reaffirm_credentials(self, pin: str | bytes) -> None:
|
|
324
|
+
raise NotImplementedError()
|
|
325
|
+
|
|
326
|
+
def get_key(
|
|
327
|
+
self,
|
|
328
|
+
object_class: ObjectClass | None = None,
|
|
329
|
+
key_type: KeyType | None = None,
|
|
330
|
+
label: str | None = None,
|
|
331
|
+
id: bytes | None = None,
|
|
332
|
+
) -> Key:
|
|
333
|
+
"""
|
|
334
|
+
Search for a key with any of `key_type`, `label` and/or `id`.
|
|
335
|
+
|
|
336
|
+
Returns a single key or throws :class:`pkcs11.exceptions.NoSuchKey` or
|
|
337
|
+
:class:`pkcs11.exceptions.MultipleObjectsReturned`.
|
|
338
|
+
|
|
339
|
+
This is a simplified version of :meth:`get_objects`, which allows
|
|
340
|
+
searching for any object.
|
|
341
|
+
|
|
342
|
+
:param ObjectClass object_class: Optional object class.
|
|
343
|
+
:param KeyType key_type: Optional key type.
|
|
344
|
+
:param str label: Optional key label.
|
|
345
|
+
:param bytes id: Optional key id.
|
|
346
|
+
|
|
347
|
+
:rtype: Key
|
|
348
|
+
"""
|
|
349
|
+
|
|
350
|
+
if object_class is None and key_type is None and label is None and id is None:
|
|
351
|
+
raise ArgumentsBad("Must specify at least one search parameter.")
|
|
352
|
+
|
|
353
|
+
attrs: dict[Attribute, Any] = {}
|
|
354
|
+
|
|
355
|
+
if object_class is not None:
|
|
356
|
+
attrs[Attribute.CLASS] = object_class
|
|
357
|
+
|
|
358
|
+
if key_type is not None:
|
|
359
|
+
attrs[Attribute.KEY_TYPE] = key_type
|
|
360
|
+
|
|
361
|
+
if label is not None:
|
|
362
|
+
attrs[Attribute.LABEL] = label
|
|
363
|
+
|
|
364
|
+
if id is not None:
|
|
365
|
+
attrs[Attribute.ID] = id
|
|
366
|
+
|
|
367
|
+
iterator = self.get_objects(attrs)
|
|
368
|
+
try:
|
|
369
|
+
obj = next(iterator)
|
|
370
|
+
except StopIteration as ex:
|
|
371
|
+
raise NoSuchKey(f"No key matching {attrs}") from ex
|
|
372
|
+
|
|
373
|
+
try:
|
|
374
|
+
next(iterator)
|
|
375
|
+
raise MultipleObjectsReturned(f"More than 1 key matches {attrs}")
|
|
376
|
+
except StopIteration:
|
|
377
|
+
pass
|
|
378
|
+
# The caller expects a Key, but get_objects returns Object
|
|
379
|
+
# This is a runtime assumption that the returned object is a Key
|
|
380
|
+
return obj # type: ignore
|
|
381
|
+
|
|
382
|
+
def get_objects(self, attrs: dict[Attribute, Any] | None = None) -> Iterator[Object]:
|
|
383
|
+
"""
|
|
384
|
+
Search for objects matching `attrs`. Returns a generator.
|
|
385
|
+
|
|
386
|
+
::
|
|
387
|
+
|
|
388
|
+
for obj in session.get_objects({
|
|
389
|
+
Attribute.CLASS: ObjectClass.SECRET_KEY,
|
|
390
|
+
Attribute.LABEL: 'MY LABEL',
|
|
391
|
+
}):
|
|
392
|
+
|
|
393
|
+
print(obj)
|
|
394
|
+
|
|
395
|
+
This is the more generic version of :meth:`get_key`.
|
|
396
|
+
|
|
397
|
+
:param dict(Attribute,*) attrs: Attributes to search for.
|
|
398
|
+
|
|
399
|
+
:rtype: iter(Object)
|
|
400
|
+
"""
|
|
401
|
+
raise NotImplementedError()
|
|
402
|
+
|
|
403
|
+
def create_object(self, attrs: dict[Attribute, Any]) -> Object:
|
|
404
|
+
"""
|
|
405
|
+
Create a new object on the :class:`Token`. This is a low-level
|
|
406
|
+
interface to create any type of object and can be used for importing
|
|
407
|
+
data onto the Token.
|
|
408
|
+
|
|
409
|
+
::
|
|
410
|
+
|
|
411
|
+
key = session.create_object({
|
|
412
|
+
pkcs11.Attribute.CLASS: pkcs11.ObjectClass.SECRET_KEY,
|
|
413
|
+
pkcs11.Attribute.KEY_TYPE: pkcs11.KeyType.AES,
|
|
414
|
+
pkcs11.Attribute.VALUE: b'SUPER SECRET KEY',
|
|
415
|
+
})
|
|
416
|
+
|
|
417
|
+
For generating keys see :meth:`generate_key` or
|
|
418
|
+
:meth:`generate_keypair`.
|
|
419
|
+
For importing keys see :ref:`importing-keys`.
|
|
420
|
+
|
|
421
|
+
Requires a read/write session, unless the object is not to be
|
|
422
|
+
stored. To permanently store the object in the HSM add **pkcs.Attribute.TOKEN: True**,
|
|
423
|
+
see :meth:`pkcs11.Attribute` for more available object attributes.
|
|
424
|
+
|
|
425
|
+
:param dict(Attribute,*) attrs: attributes of the object to create
|
|
426
|
+
:rtype: Object
|
|
427
|
+
"""
|
|
428
|
+
raise NotImplementedError()
|
|
429
|
+
|
|
430
|
+
def create_domain_parameters(
|
|
431
|
+
self,
|
|
432
|
+
key_type: KeyType,
|
|
433
|
+
attrs: dict[Attribute, Any],
|
|
434
|
+
local: bool = False,
|
|
435
|
+
store: bool = False,
|
|
436
|
+
) -> DomainParameters:
|
|
437
|
+
"""
|
|
438
|
+
Create a domain parameters object from known parameters.
|
|
439
|
+
|
|
440
|
+
Domain parameters are used for key generation of key types such
|
|
441
|
+
as DH, DSA and EC.
|
|
442
|
+
|
|
443
|
+
You can also generate new parameters using
|
|
444
|
+
:meth:`generate_domain_parameters`.
|
|
445
|
+
|
|
446
|
+
The `local` parameter creates a Python object that is not created on
|
|
447
|
+
the HSM (its object handle will be unset). This is useful if you only
|
|
448
|
+
need the domain parameters to create another object, and do not need a
|
|
449
|
+
real PKCS #11 object in the session.
|
|
450
|
+
|
|
451
|
+
.. warning::
|
|
452
|
+
|
|
453
|
+
Domain parameters have no id or labels. Storing them is possible
|
|
454
|
+
but be aware they may be difficult to retrieve.
|
|
455
|
+
|
|
456
|
+
:param KeyType key_type: Key type these parameters are for
|
|
457
|
+
:param dict(Attribute,*) attrs: Domain parameters
|
|
458
|
+
(specific tp `key_type`)
|
|
459
|
+
:param local: if True, do not transfer parameters to the HSM.
|
|
460
|
+
:param store: if True, store these parameters permanently in the HSM.
|
|
461
|
+
:rtype: DomainParameters
|
|
462
|
+
"""
|
|
463
|
+
|
|
464
|
+
raise NotImplementedError()
|
|
465
|
+
|
|
466
|
+
def generate_domain_parameters(
|
|
467
|
+
self,
|
|
468
|
+
key_type: KeyType,
|
|
469
|
+
param_length: int,
|
|
470
|
+
store: bool = False,
|
|
471
|
+
mechanism: Mechanism | None = None,
|
|
472
|
+
mechanism_param: bytes | None = None,
|
|
473
|
+
template: dict[Attribute, Any] | None = None,
|
|
474
|
+
) -> DomainParameters:
|
|
475
|
+
"""
|
|
476
|
+
Generate domain parameters.
|
|
477
|
+
|
|
478
|
+
See :meth:`create_domain_parameters` for creating domain parameter
|
|
479
|
+
objects from known parameters.
|
|
480
|
+
|
|
481
|
+
See :meth:`generate_key` for documentation on mechanisms and templates.
|
|
482
|
+
|
|
483
|
+
.. warning::
|
|
484
|
+
|
|
485
|
+
Domain parameters have no id or labels. Storing them is possible
|
|
486
|
+
but be aware they may be difficult to retrieve.
|
|
487
|
+
|
|
488
|
+
:param KeyType key_type: Key type these parameters are for
|
|
489
|
+
:param int param_length: Size of the parameters (e.g. prime length)
|
|
490
|
+
in bits.
|
|
491
|
+
:param store: Store these parameters in the HSM
|
|
492
|
+
:param Mechanism mechanism: Optional generation mechanism (or default)
|
|
493
|
+
:param bytes mechanism_param: Optional mechanism parameter.
|
|
494
|
+
:param dict(Attribute,*) template: Optional additional attributes.
|
|
495
|
+
:rtype: DomainParameters
|
|
496
|
+
"""
|
|
497
|
+
|
|
498
|
+
raise NotImplementedError()
|
|
499
|
+
|
|
500
|
+
def generate_key(
|
|
501
|
+
self,
|
|
502
|
+
key_type: KeyType,
|
|
503
|
+
key_length: int | None = None,
|
|
504
|
+
id: bytes | None = None,
|
|
505
|
+
label: str | None = None,
|
|
506
|
+
store: bool = False,
|
|
507
|
+
capabilities: MechanismFlag | None = None,
|
|
508
|
+
mechanism: Mechanism | None = None,
|
|
509
|
+
mechanism_param: bytes | None = None,
|
|
510
|
+
template: dict[Attribute, Any] | None = None,
|
|
511
|
+
) -> SecretKey:
|
|
512
|
+
"""
|
|
513
|
+
Generate a single key (e.g. AES, DES).
|
|
514
|
+
|
|
515
|
+
Keys should set at least `id` or `label`.
|
|
516
|
+
|
|
517
|
+
An appropriate `mechanism` will be chosen for `key_type`
|
|
518
|
+
(see :attr:`DEFAULT_GENERATE_MECHANISMS`) or this can be overridden.
|
|
519
|
+
Similarly for the `capabilities` (see
|
|
520
|
+
:attr:`DEFAULT_KEY_CAPABILITIES`).
|
|
521
|
+
|
|
522
|
+
The `template` will extend the default template used to make the
|
|
523
|
+
key.
|
|
524
|
+
|
|
525
|
+
Possible mechanisms and template attributes are defined by `PKCS #11
|
|
526
|
+
<http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/pkcs11-curr-v2.40.html>`_.
|
|
527
|
+
Invalid mechanisms or attributes should raise
|
|
528
|
+
:exc:`pkcs11.exceptions.MechanismInvalid` and
|
|
529
|
+
:exc:`pkcs11.exceptions.AttributeTypeInvalid` respectively.
|
|
530
|
+
|
|
531
|
+
:param KeyType key_type: Key type (e.g. KeyType.AES)
|
|
532
|
+
:param int key_length: Key length in bits (e.g. 256).
|
|
533
|
+
:param bytes id: Key identifier.
|
|
534
|
+
:param str label: Key label.
|
|
535
|
+
:param store: Store key on token (requires R/W session).
|
|
536
|
+
:param MechanismFlag capabilities: Key capabilities (or default).
|
|
537
|
+
:param Mechanism mechanism: Generation mechanism (or default).
|
|
538
|
+
:param bytes mechanism_param: Optional vector to the mechanism.
|
|
539
|
+
:param dict(Attribute,*) template: Additional attributes.
|
|
540
|
+
|
|
541
|
+
:rtype: SecretKey
|
|
542
|
+
"""
|
|
543
|
+
raise NotImplementedError()
|
|
544
|
+
|
|
545
|
+
def generate_keypair(
|
|
546
|
+
self,
|
|
547
|
+
key_type: KeyType,
|
|
548
|
+
key_length: int | None = None,
|
|
549
|
+
**kwargs: Any,
|
|
550
|
+
) -> tuple[PublicKey, PrivateKey]:
|
|
551
|
+
"""
|
|
552
|
+
Generate a asymmetric keypair (e.g. RSA).
|
|
553
|
+
|
|
554
|
+
See :meth:`generate_key` for more information.
|
|
555
|
+
|
|
556
|
+
:param KeyType key_type: Key type (e.g. KeyType.DSA)
|
|
557
|
+
:param int key_length: Key length in bits (e.g. 256).
|
|
558
|
+
:param bytes id: Key identifier.
|
|
559
|
+
:param str label: Key label.
|
|
560
|
+
:param bool store: Store key on token (requires R/W session).
|
|
561
|
+
:param MechanismFlag capabilities: Key capabilities (or default).
|
|
562
|
+
:param Mechanism mechanism: Generation mechanism (or default).
|
|
563
|
+
:param bytes mechanism_param: Optional vector to the mechanism.
|
|
564
|
+
:param dict(Attribute,*) private_template: Additional attributes for private key.
|
|
565
|
+
:param dict(Attribute,*) public_template: Additional attributes for public key.
|
|
566
|
+
|
|
567
|
+
:rtype: (PublicKey, PrivateKey)
|
|
568
|
+
"""
|
|
569
|
+
if key_type is KeyType.DSA:
|
|
570
|
+
if key_length is None:
|
|
571
|
+
raise ArgumentsBad("Must specify `key_length`")
|
|
572
|
+
|
|
573
|
+
params = self.generate_domain_parameters(key_type, key_length)
|
|
574
|
+
|
|
575
|
+
return params.generate_keypair(**kwargs)
|
|
576
|
+
else:
|
|
577
|
+
return self._generate_keypair(key_type, key_length=key_length, **kwargs)
|
|
578
|
+
|
|
579
|
+
def _generate_keypair(
|
|
580
|
+
self,
|
|
581
|
+
key_type: KeyType,
|
|
582
|
+
key_length: int | None = None,
|
|
583
|
+
**kwargs: Any,
|
|
584
|
+
) -> tuple[PublicKey, PrivateKey]:
|
|
585
|
+
raise NotImplementedError()
|
|
586
|
+
|
|
587
|
+
def seed_random(self, seed: bytes) -> None:
|
|
588
|
+
"""
|
|
589
|
+
Mix additional seed material into the RNG (if supported).
|
|
590
|
+
|
|
591
|
+
:param bytes seed: Bytes of random to seed.
|
|
592
|
+
"""
|
|
593
|
+
raise NotImplementedError()
|
|
594
|
+
|
|
595
|
+
def generate_random(self, nbits: int) -> bytes:
|
|
596
|
+
"""
|
|
597
|
+
Generate `length` bits of random or pseudo-random data (if supported).
|
|
598
|
+
|
|
599
|
+
:param int nbits: Number of bits to generate.
|
|
600
|
+
:rtype: bytes
|
|
601
|
+
"""
|
|
602
|
+
raise NotImplementedError()
|
|
603
|
+
|
|
604
|
+
def digest(self, data: str | bytes | Key | Iterator[bytes | Key], **kwargs: Any) -> bytes:
|
|
605
|
+
"""
|
|
606
|
+
Digest `data` using `mechanism`.
|
|
607
|
+
|
|
608
|
+
`data` can be a single value or an iterator.
|
|
609
|
+
|
|
610
|
+
:class:`Key` objects can also be digested, optionally interspersed
|
|
611
|
+
with :class:`bytes`.
|
|
612
|
+
|
|
613
|
+
:param data: Data to digest
|
|
614
|
+
:type data: str, bytes, Key or iter(bytes, Key)
|
|
615
|
+
:param Mechanism mechanism: digest mechanism
|
|
616
|
+
:param bytes mechanism_param: optional mechanism parameter
|
|
617
|
+
|
|
618
|
+
:rtype: bytes
|
|
619
|
+
"""
|
|
620
|
+
|
|
621
|
+
# If data is a string, encode it now as UTF-8.
|
|
622
|
+
if isinstance(data, str):
|
|
623
|
+
data = data.encode("utf-8")
|
|
624
|
+
|
|
625
|
+
if isinstance(data, bytes):
|
|
626
|
+
return self._digest(data, **kwargs)
|
|
627
|
+
|
|
628
|
+
elif isinstance(data, Key):
|
|
629
|
+
return self._digest_generator(iter((data,)), **kwargs)
|
|
630
|
+
|
|
631
|
+
return self._digest_generator(data, **kwargs)
|
|
632
|
+
|
|
633
|
+
def set_pin(self, old_pin: str | bytes, new_pin: str | bytes) -> None:
|
|
634
|
+
"""Change the user pin."""
|
|
635
|
+
raise NotImplementedError()
|
|
636
|
+
|
|
637
|
+
def init_pin(self, pin: str | bytes) -> None:
|
|
638
|
+
"""
|
|
639
|
+
Initializes the user PIN.
|
|
640
|
+
|
|
641
|
+
Differs from set_pin in that it sets the user PIN for the first time.
|
|
642
|
+
Once set, the pin can be changed using set_pin.
|
|
643
|
+
"""
|
|
644
|
+
raise NotImplementedError()
|
|
645
|
+
|
|
646
|
+
def _digest(
|
|
647
|
+
self,
|
|
648
|
+
data: bytes,
|
|
649
|
+
mechanism: Mechanism | None = None,
|
|
650
|
+
mechanism_param: bytes | None = None,
|
|
651
|
+
) -> bytes:
|
|
652
|
+
raise NotImplementedError()
|
|
653
|
+
|
|
654
|
+
def _digest_generator(
|
|
655
|
+
self,
|
|
656
|
+
data: Iterator[bytes | Key],
|
|
657
|
+
mechanism: Mechanism | None = None,
|
|
658
|
+
mechanism_param: bytes | None = None,
|
|
659
|
+
) -> bytes:
|
|
660
|
+
raise NotImplementedError()
|
|
661
|
+
|
|
662
|
+
|
|
663
|
+
class Object(IdentifiedBy):
|
|
664
|
+
"""
|
|
665
|
+
A PKCS#11 object residing on a :class:`Token`.
|
|
666
|
+
|
|
667
|
+
Objects implement :meth:`__getitem__` and :meth:`__setitem__` to
|
|
668
|
+
retrieve :class:`pkcs11.constants.Attribute` values on the object.
|
|
669
|
+
Valid attributes for an object are given in `PKCS #11
|
|
670
|
+
<http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/pkcs11-curr-v2.40.html>`_.
|
|
671
|
+
Invalid attributes should raise
|
|
672
|
+
:exc:`pkcs11.exceptions.AttributeTypeInvalid`.
|
|
673
|
+
"""
|
|
674
|
+
|
|
675
|
+
object_class: ObjectClass | None = None
|
|
676
|
+
""":class:`pkcs11.constants.ObjectClass` of this Object."""
|
|
677
|
+
|
|
678
|
+
@property
|
|
679
|
+
def session(self) -> Session:
|
|
680
|
+
raise NotImplementedError()
|
|
681
|
+
|
|
682
|
+
@property
|
|
683
|
+
def handle(self) -> int | None:
|
|
684
|
+
raise NotImplementedError()
|
|
685
|
+
|
|
686
|
+
def __getitem__(self, key: Attribute) -> Any:
|
|
687
|
+
raise NotImplementedError()
|
|
688
|
+
|
|
689
|
+
def __setitem__(self, key: Attribute, value: Any) -> None:
|
|
690
|
+
raise NotImplementedError()
|
|
691
|
+
|
|
692
|
+
def get_attributes(self, keys: list[Attribute]) -> dict[Attribute, Any]:
|
|
693
|
+
raise NotImplementedError()
|
|
694
|
+
|
|
695
|
+
def copy(self, attrs: dict[Attribute, Any]) -> Object:
|
|
696
|
+
"""
|
|
697
|
+
Make a copy of the object with new attributes `attrs`.
|
|
698
|
+
|
|
699
|
+
Requires a read/write session, unless the object is not to be
|
|
700
|
+
stored.
|
|
701
|
+
|
|
702
|
+
::
|
|
703
|
+
|
|
704
|
+
new = key.copy({
|
|
705
|
+
Attribute.LABEL: 'MY NEW KEY',
|
|
706
|
+
})
|
|
707
|
+
|
|
708
|
+
Certain objects may not be copied. Calling :meth:`copy` on such
|
|
709
|
+
objects will result in an exception.
|
|
710
|
+
|
|
711
|
+
:param dict(Attribute,*) attrs: attributes for the new :class:`Object`
|
|
712
|
+
:rtype: Object
|
|
713
|
+
"""
|
|
714
|
+
raise NotImplementedError()
|
|
715
|
+
|
|
716
|
+
def destroy(self) -> None:
|
|
717
|
+
"""
|
|
718
|
+
Destroy the object.
|
|
719
|
+
|
|
720
|
+
Requires a read/write session, unless the object is not stored.
|
|
721
|
+
|
|
722
|
+
Certain objects may not be destroyed. Calling :meth:`destroy` on such
|
|
723
|
+
objects will result in an exception.
|
|
724
|
+
|
|
725
|
+
The :class:`Object` is no longer valid.
|
|
726
|
+
"""
|
|
727
|
+
raise NotImplementedError()
|
|
728
|
+
|
|
729
|
+
|
|
730
|
+
class DomainParameters(Object):
|
|
731
|
+
"""
|
|
732
|
+
PKCS#11 Domain Parameters.
|
|
733
|
+
|
|
734
|
+
Used to store domain parameters as part of the key generation step, e.g.
|
|
735
|
+
in DSA and Diffie-Hellman.
|
|
736
|
+
"""
|
|
737
|
+
|
|
738
|
+
@cached_property
|
|
739
|
+
def key_type(self) -> KeyType:
|
|
740
|
+
"""
|
|
741
|
+
Key type (:class:`pkcs11.mechanisms.KeyType`) these parameters
|
|
742
|
+
can be used to generate.
|
|
743
|
+
"""
|
|
744
|
+
return self[Attribute.KEY_TYPE]
|
|
745
|
+
|
|
746
|
+
def generate_keypair(
|
|
747
|
+
self,
|
|
748
|
+
id: bytes | None = None,
|
|
749
|
+
label: str | None = None,
|
|
750
|
+
store: bool = False,
|
|
751
|
+
capabilities: MechanismFlag | None = None,
|
|
752
|
+
mechanism: Mechanism | None = None,
|
|
753
|
+
mechanism_param: bytes | None = None,
|
|
754
|
+
public_template: dict[Attribute, Any] | None = None,
|
|
755
|
+
private_template: dict[Attribute, Any] | None = None,
|
|
756
|
+
) -> tuple[PublicKey, PrivateKey]:
|
|
757
|
+
"""
|
|
758
|
+
Generate a key pair from these domain parameters (e.g. for
|
|
759
|
+
Diffie-Hellman.
|
|
760
|
+
|
|
761
|
+
See :meth:`Session.generate_key` for more information.
|
|
762
|
+
|
|
763
|
+
:param bytes id: Key identifier.
|
|
764
|
+
:param str label: Key label.
|
|
765
|
+
:param store: Store key on token (requires R/W session).
|
|
766
|
+
:param MechanismFlag capabilities: Key capabilities (or default).
|
|
767
|
+
:param Mechanism mechanism: Generation mechanism (or default).
|
|
768
|
+
:param bytes mechanism_param: Optional vector to the mechanism.
|
|
769
|
+
:param dict(Attribute,*) template: Additional attributes.
|
|
770
|
+
|
|
771
|
+
:rtype: (PublicKey, PrivateKey)
|
|
772
|
+
"""
|
|
773
|
+
raise NotImplementedError()
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
class LocalDomainParameters(DomainParameters):
|
|
777
|
+
_session: Session
|
|
778
|
+
params: dict[Attribute, Any]
|
|
779
|
+
|
|
780
|
+
def __init__(self, session: Session, params: dict[Attribute, Any]) -> None:
|
|
781
|
+
self._session = session
|
|
782
|
+
self.params = params
|
|
783
|
+
|
|
784
|
+
@property
|
|
785
|
+
def session(self) -> Session:
|
|
786
|
+
return self._session
|
|
787
|
+
|
|
788
|
+
@property
|
|
789
|
+
def handle(self) -> None:
|
|
790
|
+
return None
|
|
791
|
+
|
|
792
|
+
def __getitem__(self, key: Attribute) -> Any:
|
|
793
|
+
try:
|
|
794
|
+
return self.params[key]
|
|
795
|
+
except KeyError as ex:
|
|
796
|
+
raise AttributeTypeInvalid from ex
|
|
797
|
+
|
|
798
|
+
def get_attributes(self, keys: list[Attribute]) -> dict[Attribute, Any]:
|
|
799
|
+
return {key: self.params[key] for key in keys if key in self.params}
|
|
800
|
+
|
|
801
|
+
def __setitem__(self, key: Attribute, value: Any) -> None:
|
|
802
|
+
self.params[key] = value
|
|
803
|
+
|
|
804
|
+
|
|
805
|
+
class HasKeyType(Object):
|
|
806
|
+
@cached_property
|
|
807
|
+
def key_type(self) -> KeyType:
|
|
808
|
+
"""Key type (:class:`pkcs11.mechanisms.KeyType`)."""
|
|
809
|
+
return self[Attribute.KEY_TYPE]
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
class Key(HasKeyType):
|
|
813
|
+
"""Base class for all key :class:`Object` types."""
|
|
814
|
+
|
|
815
|
+
@property
|
|
816
|
+
def key_length(self) -> int:
|
|
817
|
+
"""Key length in bits."""
|
|
818
|
+
raise NotImplementedError
|
|
819
|
+
|
|
820
|
+
@cached_property
|
|
821
|
+
def id(self) -> bytes:
|
|
822
|
+
"""Key id (:class:`bytes`)."""
|
|
823
|
+
return self[Attribute.ID]
|
|
824
|
+
|
|
825
|
+
@cached_property
|
|
826
|
+
def label(self) -> str:
|
|
827
|
+
"""Key label (:class:`str`)."""
|
|
828
|
+
return self[Attribute.LABEL]
|
|
829
|
+
|
|
830
|
+
@cached_property
|
|
831
|
+
def _key_description(self) -> str:
|
|
832
|
+
"""A description of the key."""
|
|
833
|
+
try:
|
|
834
|
+
return f"{self.key_length}-bit {self.key_type.name}"
|
|
835
|
+
except AttributeTypeInvalid:
|
|
836
|
+
return self.key_type.name
|
|
837
|
+
|
|
838
|
+
def __repr__(self) -> str:
|
|
839
|
+
return "<{} label='{}' id='{}' {}>".format(
|
|
840
|
+
type(self).__name__,
|
|
841
|
+
self.label,
|
|
842
|
+
hexlify(self.id).decode("ascii"),
|
|
843
|
+
self._key_description,
|
|
844
|
+
)
|
|
845
|
+
|
|
846
|
+
|
|
847
|
+
class SecretKey(Key):
|
|
848
|
+
"""
|
|
849
|
+
A PKCS#11 :attr:`pkcs11.constants.ObjectClass.SECRET_KEY` object
|
|
850
|
+
(symmetric encryption key).
|
|
851
|
+
"""
|
|
852
|
+
|
|
853
|
+
object_class: ObjectClass = ObjectClass.SECRET_KEY
|
|
854
|
+
|
|
855
|
+
@cached_property
|
|
856
|
+
def key_length(self) -> int:
|
|
857
|
+
"""Key length in bits."""
|
|
858
|
+
return self[Attribute.VALUE_LEN] * 8
|
|
859
|
+
|
|
860
|
+
|
|
861
|
+
class PublicKey(Key):
|
|
862
|
+
"""
|
|
863
|
+
A PKCS#11 :attr:`pkcs11.constants.ObjectClass.PUBLIC_KEY` object
|
|
864
|
+
(asymmetric public key).
|
|
865
|
+
|
|
866
|
+
RSA private keys can be imported and exported from PKCS#1 DER-encoding
|
|
867
|
+
using :func:`pkcs11.util.rsa.decode_rsa_public_key` and
|
|
868
|
+
:func:`pkcs11.util.rsa.encode_rsa_public_key` respectively.
|
|
869
|
+
"""
|
|
870
|
+
|
|
871
|
+
object_class: ObjectClass = ObjectClass.PUBLIC_KEY
|
|
872
|
+
|
|
873
|
+
@cached_property
|
|
874
|
+
def key_length(self) -> int:
|
|
875
|
+
"""Key length in bits."""
|
|
876
|
+
return self[Attribute.MODULUS_BITS]
|
|
877
|
+
|
|
878
|
+
|
|
879
|
+
class PrivateKey(Key):
|
|
880
|
+
"""
|
|
881
|
+
A PKCS#11 :attr:`pkcs11.constants.ObjectClass.PRIVATE_KEY` object
|
|
882
|
+
(asymmetric private key).
|
|
883
|
+
|
|
884
|
+
RSA private keys can be imported from PKCS#1 DER-encoding using
|
|
885
|
+
:func:`pkcs11.util.rsa.decode_rsa_private_key`.
|
|
886
|
+
|
|
887
|
+
.. warning::
|
|
888
|
+
|
|
889
|
+
Private keys imported directly, rather than unwrapped from a trusted
|
|
890
|
+
private key should be considered insecure.
|
|
891
|
+
"""
|
|
892
|
+
|
|
893
|
+
object_class: ObjectClass = ObjectClass.PRIVATE_KEY
|
|
894
|
+
|
|
895
|
+
@cached_property
|
|
896
|
+
def key_length(self) -> int:
|
|
897
|
+
"""Key length in bits."""
|
|
898
|
+
return len(self[Attribute.MODULUS]) * 8
|
|
899
|
+
|
|
900
|
+
|
|
901
|
+
class Certificate(Object):
|
|
902
|
+
"""
|
|
903
|
+
A PKCS#11 :attr:`pkcs11.constants.ObjectClass.CERTIFICATE` object.
|
|
904
|
+
|
|
905
|
+
PKCS#11 is limited in its handling of certificates, and does not
|
|
906
|
+
provide features like parsing of X.509 etc. These should be handled in
|
|
907
|
+
an external library. PKCS#11 will not set attributes on the certificate
|
|
908
|
+
based on the `VALUE`.
|
|
909
|
+
|
|
910
|
+
:func:`pkcs11.util.x509.decode_x509_certificate` will extract attributes
|
|
911
|
+
from a certificate to create the object.
|
|
912
|
+
"""
|
|
913
|
+
|
|
914
|
+
object_class: ObjectClass = ObjectClass.CERTIFICATE
|
|
915
|
+
|
|
916
|
+
@cached_property
|
|
917
|
+
def certificate_type(self) -> CertificateType:
|
|
918
|
+
"""
|
|
919
|
+
The type of certificate.
|
|
920
|
+
|
|
921
|
+
:rtype: CertificateType
|
|
922
|
+
"""
|
|
923
|
+
return self[Attribute.CERTIFICATE_TYPE]
|
|
924
|
+
|
|
925
|
+
|
|
926
|
+
class EncryptMixin(HasKeyType):
|
|
927
|
+
"""
|
|
928
|
+
This :class:`Object` supports the encrypt capability.
|
|
929
|
+
"""
|
|
930
|
+
|
|
931
|
+
def encrypt(
|
|
932
|
+
self,
|
|
933
|
+
data: str | bytes | Iterator[bytes],
|
|
934
|
+
buffer_size: int = 8192,
|
|
935
|
+
**kwargs: Any,
|
|
936
|
+
) -> bytes | Iterator[bytes]:
|
|
937
|
+
"""
|
|
938
|
+
Encrypt some `data`.
|
|
939
|
+
|
|
940
|
+
Data can be either :class:`str` or :class:`bytes`, in which case it
|
|
941
|
+
will return :class:`bytes`; or an iterable of :class:`bytes` in
|
|
942
|
+
which case it will return a generator yielding :class:`bytes`
|
|
943
|
+
(be aware, more chunks will be output than input).
|
|
944
|
+
|
|
945
|
+
If you do not specify `mechanism` then the default from
|
|
946
|
+
:attr:`DEFAULT_ENCRYPT_MECHANISMS` will be used. If an iterable
|
|
947
|
+
is passed and the mechanism chosen does not support handling data
|
|
948
|
+
in chunks, an exception will be raised.
|
|
949
|
+
|
|
950
|
+
Some mechanisms (including the default CBC mechanisms) require
|
|
951
|
+
additional parameters, e.g. an initialisation vector [#]_, to
|
|
952
|
+
the mechanism. Pass this as `mechanism_param`.
|
|
953
|
+
Documentation of these parameters is given specified in `PKCS #11
|
|
954
|
+
<http://docs.oasis-open.org/pkcs11/pkcs11-curr/v2.40/pkcs11-curr-v2.40.html>`_.
|
|
955
|
+
|
|
956
|
+
When passing an iterable for data
|
|
957
|
+
`buffer_size` must be sufficient to store the working buffer. An
|
|
958
|
+
integer number of blocks and greater than or equal to the largest
|
|
959
|
+
input chunk is recommended.
|
|
960
|
+
|
|
961
|
+
The returned generator obtains a lock on the :class:`Session`
|
|
962
|
+
to prevent other threads from starting a simultaneous operation.
|
|
963
|
+
The lock is released when you consume/destroy the generator.
|
|
964
|
+
See :ref:`concurrency`.
|
|
965
|
+
|
|
966
|
+
.. warning::
|
|
967
|
+
|
|
968
|
+
It's not currently possible to cancel an encryption operation
|
|
969
|
+
by deleting the generator. You must consume the generator to
|
|
970
|
+
complete the operation.
|
|
971
|
+
|
|
972
|
+
An example of streaming a file is as follows:
|
|
973
|
+
|
|
974
|
+
::
|
|
975
|
+
|
|
976
|
+
def encrypt_file(file_in, file_out, buffer_size=8192):
|
|
977
|
+
|
|
978
|
+
with \\
|
|
979
|
+
open(file_in, 'rb') as input_, \\
|
|
980
|
+
open(file_out, 'wb') as output:
|
|
981
|
+
|
|
982
|
+
chunks = iter(lambda: input_.read(buffer_size), '')
|
|
983
|
+
|
|
984
|
+
for chunk in key.encrypt(chunks,
|
|
985
|
+
mechanism_param=iv,
|
|
986
|
+
buffer_size=buffer_size):
|
|
987
|
+
output.write(chunk)
|
|
988
|
+
|
|
989
|
+
:param data: data to encrypt
|
|
990
|
+
:type data: str, bytes or iter(bytes)
|
|
991
|
+
:param Mechanism mechanism: optional encryption mechanism
|
|
992
|
+
(or None for default)
|
|
993
|
+
:param bytes mechanism_param: optional mechanism parameter
|
|
994
|
+
(e.g. initialisation vector).
|
|
995
|
+
:param int buffer_size: size of the working buffer (for generators)
|
|
996
|
+
|
|
997
|
+
:rtype: bytes or iter(bytes)
|
|
998
|
+
|
|
999
|
+
.. [#] The initialisation vector should contain quality random,
|
|
1000
|
+
e.g. from :meth:`Session.generate_random`.
|
|
1001
|
+
This method will not return the value of the initialisation
|
|
1002
|
+
vector as part of the encryption. You must store that yourself.
|
|
1003
|
+
"""
|
|
1004
|
+
|
|
1005
|
+
# If data is a string, encode it now as UTF-8.
|
|
1006
|
+
if isinstance(data, str):
|
|
1007
|
+
data = data.encode("utf-8")
|
|
1008
|
+
|
|
1009
|
+
if isinstance(data, bytes):
|
|
1010
|
+
return self._encrypt(data, **kwargs)
|
|
1011
|
+
|
|
1012
|
+
else:
|
|
1013
|
+
return self._encrypt_generator(data, buffer_size=buffer_size, **kwargs)
|
|
1014
|
+
|
|
1015
|
+
def _encrypt(
|
|
1016
|
+
self,
|
|
1017
|
+
data: bytes,
|
|
1018
|
+
mechanism: Mechanism | None = None,
|
|
1019
|
+
mechanism_param: bytes | None = None,
|
|
1020
|
+
buffer_size: int = 8192,
|
|
1021
|
+
) -> bytes:
|
|
1022
|
+
raise NotImplementedError()
|
|
1023
|
+
|
|
1024
|
+
def _encrypt_generator(
|
|
1025
|
+
self,
|
|
1026
|
+
data: Iterator[bytes],
|
|
1027
|
+
mechanism: Mechanism | None = None,
|
|
1028
|
+
mechanism_param: bytes | None = None,
|
|
1029
|
+
buffer_size: int = 8192,
|
|
1030
|
+
) -> Iterator[bytes]:
|
|
1031
|
+
raise NotImplementedError()
|
|
1032
|
+
|
|
1033
|
+
|
|
1034
|
+
class DecryptMixin(HasKeyType):
|
|
1035
|
+
"""
|
|
1036
|
+
This :class:`Object` supports the decrypt capability.
|
|
1037
|
+
"""
|
|
1038
|
+
|
|
1039
|
+
def decrypt(
|
|
1040
|
+
self,
|
|
1041
|
+
data: bytes | Iterator[bytes],
|
|
1042
|
+
buffer_size: int = 8192,
|
|
1043
|
+
**kwargs: Any,
|
|
1044
|
+
) -> bytes | Iterator[bytes]:
|
|
1045
|
+
"""
|
|
1046
|
+
Decrypt some `data`.
|
|
1047
|
+
|
|
1048
|
+
See :meth:`EncryptMixin.encrypt` for more information.
|
|
1049
|
+
|
|
1050
|
+
:param data: data to decrypt
|
|
1051
|
+
:type data: bytes or iter(bytes)
|
|
1052
|
+
:param Mechanism mechanism: optional encryption mechanism
|
|
1053
|
+
(or None for default).
|
|
1054
|
+
:param bytes mechanism_param: optional mechanism parameter
|
|
1055
|
+
(e.g. initialisation vector).
|
|
1056
|
+
:param pin: optional user pin for keys that require it (e.g. YubiKey)
|
|
1057
|
+
:param int buffer_size: size of the working buffer (for generators).
|
|
1058
|
+
|
|
1059
|
+
:rtype: bytes or iter(bytes)
|
|
1060
|
+
"""
|
|
1061
|
+
|
|
1062
|
+
# If we're not an iterable, call into our generator with an iterable
|
|
1063
|
+
# version and join the result at the end.
|
|
1064
|
+
if isinstance(data, bytes):
|
|
1065
|
+
return self._decrypt(data, **kwargs)
|
|
1066
|
+
|
|
1067
|
+
else:
|
|
1068
|
+
return self._decrypt_generator(data, buffer_size=buffer_size, **kwargs)
|
|
1069
|
+
|
|
1070
|
+
def _decrypt(
|
|
1071
|
+
self,
|
|
1072
|
+
data: bytes,
|
|
1073
|
+
mechanism: Mechanism | None = None,
|
|
1074
|
+
mechanism_param: bytes | None = None,
|
|
1075
|
+
pin: str | bytes | None = None,
|
|
1076
|
+
buffer_size: int = 8192,
|
|
1077
|
+
) -> bytes:
|
|
1078
|
+
raise NotImplementedError()
|
|
1079
|
+
|
|
1080
|
+
def _decrypt_generator(
|
|
1081
|
+
self,
|
|
1082
|
+
data: Iterator[bytes],
|
|
1083
|
+
mechanism: Mechanism | None = None,
|
|
1084
|
+
mechanism_param: bytes | None = None,
|
|
1085
|
+
pin: str | bytes | None = None,
|
|
1086
|
+
buffer_size: int = 8192,
|
|
1087
|
+
) -> Iterator[bytes]:
|
|
1088
|
+
raise NotImplementedError()
|
|
1089
|
+
|
|
1090
|
+
|
|
1091
|
+
class SignMixin(HasKeyType):
|
|
1092
|
+
"""
|
|
1093
|
+
This :class:`Object` supports the sign capability.
|
|
1094
|
+
"""
|
|
1095
|
+
|
|
1096
|
+
def sign(self, data: str | bytes | Iterator[bytes], **kwargs: Any) -> bytes:
|
|
1097
|
+
"""
|
|
1098
|
+
Sign some `data`.
|
|
1099
|
+
|
|
1100
|
+
See :meth:`EncryptMixin.encrypt` for more information.
|
|
1101
|
+
|
|
1102
|
+
For DSA and ECDSA keys, PKCS #11 outputs the two parameters (r & s)
|
|
1103
|
+
as two concatenated `biginteger` of the same length. To convert these
|
|
1104
|
+
into other formats, such as the format used by OpenSSL, use
|
|
1105
|
+
:func:`pkcs11.util.dsa.encode_dsa_signature` or
|
|
1106
|
+
:func:`pkcs11.util.ec.encode_ecdsa_signature`.
|
|
1107
|
+
|
|
1108
|
+
:param data: data to sign
|
|
1109
|
+
:type data: str, bytes or iter(bytes)
|
|
1110
|
+
:param Mechanism mechanism: optional signing mechanism
|
|
1111
|
+
:param bytes mechanism_param: optional mechanism parameter
|
|
1112
|
+
:param pin: optional user pin for keys that require it (e.g. YubiKey)
|
|
1113
|
+
|
|
1114
|
+
:rtype: bytes
|
|
1115
|
+
"""
|
|
1116
|
+
|
|
1117
|
+
# If data is a string, encode it now as UTF-8.
|
|
1118
|
+
if isinstance(data, str):
|
|
1119
|
+
data = data.encode("utf-8")
|
|
1120
|
+
|
|
1121
|
+
if isinstance(data, bytes):
|
|
1122
|
+
return self._sign(data, **kwargs)
|
|
1123
|
+
|
|
1124
|
+
else:
|
|
1125
|
+
return self._sign_generator(data, **kwargs)
|
|
1126
|
+
|
|
1127
|
+
def _sign(
|
|
1128
|
+
self,
|
|
1129
|
+
data: bytes,
|
|
1130
|
+
mechanism: Mechanism | None = None,
|
|
1131
|
+
mechanism_param: bytes | None = None,
|
|
1132
|
+
pin: str | bytes | None = None,
|
|
1133
|
+
buffer_size: int = 8192,
|
|
1134
|
+
) -> bytes:
|
|
1135
|
+
raise NotImplementedError()
|
|
1136
|
+
|
|
1137
|
+
def _sign_generator(
|
|
1138
|
+
self,
|
|
1139
|
+
data: Iterator[bytes],
|
|
1140
|
+
mechanism: Mechanism | None = None,
|
|
1141
|
+
mechanism_param: bytes | None = None,
|
|
1142
|
+
pin: str | bytes | None = None,
|
|
1143
|
+
) -> bytes:
|
|
1144
|
+
raise NotImplementedError()
|
|
1145
|
+
|
|
1146
|
+
|
|
1147
|
+
class VerifyMixin(HasKeyType):
|
|
1148
|
+
"""
|
|
1149
|
+
This :class:`Object` supports the verify capability.
|
|
1150
|
+
"""
|
|
1151
|
+
|
|
1152
|
+
def verify(
|
|
1153
|
+
self,
|
|
1154
|
+
data: str | bytes | Iterator[bytes],
|
|
1155
|
+
signature: bytes,
|
|
1156
|
+
**kwargs: Any,
|
|
1157
|
+
) -> bool:
|
|
1158
|
+
"""
|
|
1159
|
+
Verify some `data`.
|
|
1160
|
+
|
|
1161
|
+
See :meth:`EncryptMixin.encrypt` for more information.
|
|
1162
|
+
|
|
1163
|
+
Returns True if `signature` is valid for `data`.
|
|
1164
|
+
|
|
1165
|
+
For DSA and ECDSA keys, PKCS #11 expects the two parameters (r & s)
|
|
1166
|
+
as two concatenated `biginteger` of the same length. To convert these
|
|
1167
|
+
from other formats, such as the format used by OpenSSL, use
|
|
1168
|
+
:func:`pkcs11.util.dsa.decode_dsa_signature` or
|
|
1169
|
+
:func:`pkcs11.util.ec.decode_ecdsa_signature`.
|
|
1170
|
+
|
|
1171
|
+
:param data: data to sign
|
|
1172
|
+
:type data: str, bytes or iter(bytes)
|
|
1173
|
+
:param bytes signature: signature
|
|
1174
|
+
:param Mechanism mechanism: optional signing mechanism
|
|
1175
|
+
:param bytes mechanism_param: optional mechanism parameter
|
|
1176
|
+
|
|
1177
|
+
:rtype: bool
|
|
1178
|
+
"""
|
|
1179
|
+
|
|
1180
|
+
# If data is a string, encode it now as UTF-8.
|
|
1181
|
+
if isinstance(data, str):
|
|
1182
|
+
data = data.encode("utf-8")
|
|
1183
|
+
|
|
1184
|
+
try:
|
|
1185
|
+
if isinstance(data, bytes):
|
|
1186
|
+
self._verify(data, signature, **kwargs)
|
|
1187
|
+
else:
|
|
1188
|
+
self._verify_generator(data, signature, **kwargs)
|
|
1189
|
+
|
|
1190
|
+
return True
|
|
1191
|
+
|
|
1192
|
+
except (SignatureInvalid, SignatureLenRange):
|
|
1193
|
+
return False
|
|
1194
|
+
|
|
1195
|
+
def _verify(
|
|
1196
|
+
self,
|
|
1197
|
+
data: bytes,
|
|
1198
|
+
signature: bytes,
|
|
1199
|
+
mechanism: Mechanism | None = None,
|
|
1200
|
+
mechanism_param: bytes | None = None,
|
|
1201
|
+
) -> None:
|
|
1202
|
+
raise NotImplementedError()
|
|
1203
|
+
|
|
1204
|
+
def _verify_generator(
|
|
1205
|
+
self,
|
|
1206
|
+
data: Iterator[bytes],
|
|
1207
|
+
signature: bytes,
|
|
1208
|
+
mechanism: Mechanism | None = None,
|
|
1209
|
+
mechanism_param: bytes | None = None,
|
|
1210
|
+
) -> None:
|
|
1211
|
+
raise NotImplementedError()
|
|
1212
|
+
|
|
1213
|
+
|
|
1214
|
+
class WrapMixin(HasKeyType):
|
|
1215
|
+
"""
|
|
1216
|
+
This :class:`Object` supports the wrap capability.
|
|
1217
|
+
"""
|
|
1218
|
+
|
|
1219
|
+
def wrap_key(
|
|
1220
|
+
self,
|
|
1221
|
+
key: Key,
|
|
1222
|
+
mechanism: Mechanism | None = None,
|
|
1223
|
+
mechanism_param: bytes | None = None,
|
|
1224
|
+
) -> bytes:
|
|
1225
|
+
"""
|
|
1226
|
+
Use this key to wrap (i.e. encrypt) `key` for export. Returns
|
|
1227
|
+
an encrypted version of `key`.
|
|
1228
|
+
|
|
1229
|
+
`key` must have :attr:`Attribute.EXTRACTABLE` = True.
|
|
1230
|
+
|
|
1231
|
+
:param Key key: key to export
|
|
1232
|
+
:param Mechanism mechanism: wrapping mechanism (or None for default).
|
|
1233
|
+
:param bytes mechanism_param: mechanism parameter (if required)
|
|
1234
|
+
|
|
1235
|
+
:rtype: bytes
|
|
1236
|
+
"""
|
|
1237
|
+
raise NotImplementedError()
|
|
1238
|
+
|
|
1239
|
+
|
|
1240
|
+
class UnwrapMixin(HasKeyType):
|
|
1241
|
+
"""
|
|
1242
|
+
This :class:`Object` supports the unwrap capability.
|
|
1243
|
+
"""
|
|
1244
|
+
|
|
1245
|
+
def unwrap_key(
|
|
1246
|
+
self,
|
|
1247
|
+
object_class: ObjectClass,
|
|
1248
|
+
key_type: KeyType,
|
|
1249
|
+
key_data: bytes,
|
|
1250
|
+
id: bytes | None = None,
|
|
1251
|
+
label: str | None = None,
|
|
1252
|
+
mechanism: Mechanism | None = None,
|
|
1253
|
+
mechanism_param: bytes | None = None,
|
|
1254
|
+
store: bool = False,
|
|
1255
|
+
capabilities: MechanismFlag | None = None,
|
|
1256
|
+
template: dict[Attribute, Any] | None = None,
|
|
1257
|
+
) -> Key:
|
|
1258
|
+
"""
|
|
1259
|
+
Use this key to unwrap (i.e. decrypt) and import `key_data`.
|
|
1260
|
+
|
|
1261
|
+
See :class:`Session.generate_key` for more information.
|
|
1262
|
+
|
|
1263
|
+
:param ObjectClass object_class: Object class to import as
|
|
1264
|
+
:param KeyType key_type: Key type (e.g. KeyType.AES)
|
|
1265
|
+
:param bytes key_data: Encrypted key to unwrap
|
|
1266
|
+
:param bytes id: Key identifier.
|
|
1267
|
+
:param str label: Key label.
|
|
1268
|
+
:param store: Store key on token (requires R/W session).
|
|
1269
|
+
:param MechanismFlag capabilities: Key capabilities (or default).
|
|
1270
|
+
:param Mechanism mechanism: Generation mechanism (or default).
|
|
1271
|
+
:param bytes mechanism_param: Optional vector to the mechanism.
|
|
1272
|
+
:param dict(Attribute,*) template: Additional attributes.
|
|
1273
|
+
|
|
1274
|
+
:rtype: Key
|
|
1275
|
+
"""
|
|
1276
|
+
raise NotImplementedError()
|
|
1277
|
+
|
|
1278
|
+
|
|
1279
|
+
class DeriveMixin(HasKeyType):
|
|
1280
|
+
"""
|
|
1281
|
+
This :class:`Object` supports the derive capability.
|
|
1282
|
+
"""
|
|
1283
|
+
|
|
1284
|
+
def derive_key(
|
|
1285
|
+
self,
|
|
1286
|
+
key_type: KeyType,
|
|
1287
|
+
key_length: int,
|
|
1288
|
+
id: bytes | None = None,
|
|
1289
|
+
label: str | None = None,
|
|
1290
|
+
store: bool = False,
|
|
1291
|
+
capabilities: MechanismFlag | None = None,
|
|
1292
|
+
mechanism: Mechanism | None = None,
|
|
1293
|
+
mechanism_param: bytes | tuple[Any, ...] | None = None,
|
|
1294
|
+
template: dict[Attribute, Any] | None = None,
|
|
1295
|
+
) -> SecretKey:
|
|
1296
|
+
"""
|
|
1297
|
+
Derive a new key from this key. Used to create session
|
|
1298
|
+
keys from a PKCS key exchange.
|
|
1299
|
+
|
|
1300
|
+
Typically the mechanism, e.g. Diffie-Hellman, requires you
|
|
1301
|
+
to specify the other party's piece of shared information as
|
|
1302
|
+
the `mechanism_param`. Some mechanisms require a tuple of data (see
|
|
1303
|
+
:class:`pkcs11.mechanisms.Mechanism`).
|
|
1304
|
+
|
|
1305
|
+
See :class:`Session.generate_key` for more documentation on key
|
|
1306
|
+
generation.
|
|
1307
|
+
|
|
1308
|
+
Diffie-Hellman example:
|
|
1309
|
+
|
|
1310
|
+
::
|
|
1311
|
+
|
|
1312
|
+
# Diffie-Hellman domain parameters
|
|
1313
|
+
# e.g. from RFC 3526, RFC 5114 or `openssl dhparam`
|
|
1314
|
+
prime = [0xFF, ...]
|
|
1315
|
+
base = [0x02]
|
|
1316
|
+
|
|
1317
|
+
parameters = session.create_domain_parameters(KeyType.DH, {
|
|
1318
|
+
Attribute.PRIME: prime,
|
|
1319
|
+
Attribute.BASE: base,
|
|
1320
|
+
}, local=True)
|
|
1321
|
+
|
|
1322
|
+
# Alice generates a DH key pair from the public
|
|
1323
|
+
# Diffie-Hellman parameters
|
|
1324
|
+
public, private = parameters.generate_keypair()
|
|
1325
|
+
alices_value = public[Attribute.VALUE]
|
|
1326
|
+
|
|
1327
|
+
# Bob generates a DH key pair from the same parameters.
|
|
1328
|
+
|
|
1329
|
+
# Alice exchanges public values with Bob...
|
|
1330
|
+
# She sends `alices_value` and receives `bobs_value`.
|
|
1331
|
+
# (Assuming Alice is doing AES CBC, she also needs to send an IV)
|
|
1332
|
+
|
|
1333
|
+
# Alice generates a session key with Bob's public value
|
|
1334
|
+
# Bob will generate the same session key using Alice's value.
|
|
1335
|
+
session_key = private.derive_key(
|
|
1336
|
+
KeyType.AES, 128,
|
|
1337
|
+
mechanism_param=bobs_value)
|
|
1338
|
+
|
|
1339
|
+
Elliptic-Curve Diffie-Hellman example:
|
|
1340
|
+
|
|
1341
|
+
::
|
|
1342
|
+
|
|
1343
|
+
# DER encoded EC params, e.g. from OpenSSL
|
|
1344
|
+
# openssl ecparam -outform der -name prime192v1 | base64
|
|
1345
|
+
#
|
|
1346
|
+
# Check what EC parameters the module supports with
|
|
1347
|
+
# slot.get_module_info()
|
|
1348
|
+
parameters = session.create_domain_parameters(KeyType.EC, {
|
|
1349
|
+
Attribute.EC_PARAMS: b'...',
|
|
1350
|
+
}, local=True)
|
|
1351
|
+
|
|
1352
|
+
# Alice generates a EC key pair, and gets her public value
|
|
1353
|
+
public, private = parameters.generate_keypair()
|
|
1354
|
+
alices_value = public[Attribute.EC_POINT]
|
|
1355
|
+
|
|
1356
|
+
# Bob generates a DH key pair from the same parameters.
|
|
1357
|
+
|
|
1358
|
+
# Alice exchanges public values with Bob...
|
|
1359
|
+
# She sends `alices_value` and receives `bobs_value`.
|
|
1360
|
+
|
|
1361
|
+
# Alice generates a session key with Bob's public value
|
|
1362
|
+
# Bob will generate the same session key using Alice's value.
|
|
1363
|
+
session_key = private.derive_key(
|
|
1364
|
+
KeyType.AES, 128,
|
|
1365
|
+
mechanism_param=(KDF.NULL, None, bobs_value))
|
|
1366
|
+
|
|
1367
|
+
:param KeyType key_type: Key type (e.g. KeyType.AES)
|
|
1368
|
+
:param int key_length: Key length in bits (e.g. 256).
|
|
1369
|
+
:param bytes id: Key identifier.
|
|
1370
|
+
:param str label: Key label.
|
|
1371
|
+
:param store: Store key on token (requires R/W session).
|
|
1372
|
+
:param MechanismFlag capabilities: Key capabilities (or default).
|
|
1373
|
+
:param Mechanism mechanism: Generation mechanism (or default).
|
|
1374
|
+
:param bytes mechanism_param: Optional vector to the mechanism.
|
|
1375
|
+
:param dict(Attribute,*) template: Additional attributes.
|
|
1376
|
+
|
|
1377
|
+
:rtype: SecretKey
|
|
1378
|
+
"""
|
|
1379
|
+
raise NotImplementedError()
|
|
1380
|
+
|
|
1381
|
+
|
|
1382
|
+
class EncapsulateMixin(HasKeyType):
|
|
1383
|
+
"""
|
|
1384
|
+
This :class:`Object` supports the encapsulate capability (ML-KEM).
|
|
1385
|
+
"""
|
|
1386
|
+
|
|
1387
|
+
def encapsulate_key(
|
|
1388
|
+
self,
|
|
1389
|
+
key_type: KeyType,
|
|
1390
|
+
key_length: int | None = None,
|
|
1391
|
+
id: bytes | None = None,
|
|
1392
|
+
label: str | None = None,
|
|
1393
|
+
store: bool = False,
|
|
1394
|
+
capabilities: MechanismFlag | None = None,
|
|
1395
|
+
mechanism: Mechanism | None = None,
|
|
1396
|
+
mechanism_param: bytes | None = None,
|
|
1397
|
+
template: dict[Attribute, Any] | None = None,
|
|
1398
|
+
) -> tuple[bytes, SecretKey]:
|
|
1399
|
+
"""
|
|
1400
|
+
Use this ML-KEM public key to encapsulate a fresh shared secret.
|
|
1401
|
+
|
|
1402
|
+
Returns ``(ciphertext, shared_secret)`` where *ciphertext* is the
|
|
1403
|
+
KEM ciphertext to be transmitted to the decapsulating party, and
|
|
1404
|
+
*shared_secret* is the newly-created secret key object on the token.
|
|
1405
|
+
|
|
1406
|
+
:param KeyType key_type: Key type for the shared secret (e.g. KeyType.GENERIC_SECRET).
|
|
1407
|
+
:param int key_length: Shared secret length in bits.
|
|
1408
|
+
:param bytes id: Key identifier.
|
|
1409
|
+
:param str label: Key label.
|
|
1410
|
+
:param store: Store key on token (requires R/W session).
|
|
1411
|
+
:param MechanismFlag capabilities: Key capabilities (or default).
|
|
1412
|
+
:param Mechanism mechanism: Encapsulation mechanism (or default).
|
|
1413
|
+
:param bytes mechanism_param: Optional mechanism parameter.
|
|
1414
|
+
:param dict(Attribute,*) template: Additional attributes.
|
|
1415
|
+
|
|
1416
|
+
:rtype: tuple[bytes, SecretKey]
|
|
1417
|
+
"""
|
|
1418
|
+
raise NotImplementedError()
|
|
1419
|
+
|
|
1420
|
+
|
|
1421
|
+
class DecapsulateMixin(HasKeyType):
|
|
1422
|
+
"""
|
|
1423
|
+
This :class:`Object` supports the decapsulate capability (ML-KEM).
|
|
1424
|
+
"""
|
|
1425
|
+
|
|
1426
|
+
def decapsulate_key(
|
|
1427
|
+
self,
|
|
1428
|
+
ciphertext: bytes,
|
|
1429
|
+
key_type: KeyType,
|
|
1430
|
+
key_length: int | None = None,
|
|
1431
|
+
id: bytes | None = None,
|
|
1432
|
+
label: str | None = None,
|
|
1433
|
+
store: bool = False,
|
|
1434
|
+
capabilities: MechanismFlag | None = None,
|
|
1435
|
+
mechanism: Mechanism | None = None,
|
|
1436
|
+
mechanism_param: bytes | None = None,
|
|
1437
|
+
template: dict[Attribute, Any] | None = None,
|
|
1438
|
+
) -> SecretKey:
|
|
1439
|
+
"""
|
|
1440
|
+
Use this ML-KEM private key to decapsulate the shared secret from *ciphertext*.
|
|
1441
|
+
|
|
1442
|
+
Returns the recovered shared secret key object.
|
|
1443
|
+
|
|
1444
|
+
:param bytes ciphertext: KEM ciphertext from the encapsulating party.
|
|
1445
|
+
:param KeyType key_type: Key type for the shared secret (e.g. KeyType.GENERIC_SECRET).
|
|
1446
|
+
:param int key_length: Shared secret length in bits.
|
|
1447
|
+
:param bytes id: Key identifier.
|
|
1448
|
+
:param str label: Key label.
|
|
1449
|
+
:param store: Store key on token (requires R/W session).
|
|
1450
|
+
:param MechanismFlag capabilities: Key capabilities (or default).
|
|
1451
|
+
:param Mechanism mechanism: Decapsulation mechanism (or default).
|
|
1452
|
+
:param bytes mechanism_param: Optional mechanism parameter.
|
|
1453
|
+
:param dict(Attribute,*) template: Additional attributes.
|
|
1454
|
+
|
|
1455
|
+
:rtype: SecretKey
|
|
1456
|
+
"""
|
|
1457
|
+
raise NotImplementedError()
|