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