API Reference

Classes

pkcs11 defines a high-level, “Pythonic” interface to PKCS#11.

class pkcs11.lib(so)

Initialises the PKCS#11 library.

Only one PKCS#11 library can be initialised.

Parameters:so (str) – Path to the PKCS#11 library to initialise.
get_slots(token_present=False)

Returns a list of PKCS#11 device slots known to this library.

Parameters:token_present – If true, will limit the results to slots with a token present.
Return type:list(Slot)
get_tokens(token_label=None, token_serial=None, token_flags=None, slot_flags=None, mechanisms=None)

Generator yielding PKCS#11 tokens matching the provided parameters.

See also get_token().

Parameters:
  • token_label (str) – Optional token label.
  • token_serial (bytes) – Optional token serial.
  • token_flags (TokenFlag) – Optional bitwise token flags.
  • slot_flags (SlotFlag) – Optional bitwise slot flags.
  • mechanisms (iter(Mechanism)) – Optional required mechanisms.
Return type:

iter(Token)

get_token(token_label=None, token_serial=None, token_flags=None, slot_flags=None, mechanisms=None)

Returns a single token or raises either pkcs11.exceptions.NoSuchToken or pkcs11.exceptions.MultipleTokensReturned.

See also get_tokens().

Parameters:
  • token_label (str) – Optional token label.
  • token_serial (bytes) – Optional token serial.
  • token_flags (TokenFlag) – Optional bitwise token flags.
  • slot_flags (SlotFlag) – Optional bitwise slot flags.
  • mechanisms (iter(Mechanism)) – Optional required mechanisms.
Return type:

Token

cryptoki_version

PKCS#11 Cryptoki standard version (tuple).

manufacturer_id

Library vendor’s name (str).

library_description

Description of the vendor’s library (str).

library_version

Vendor’s library version (tuple).

class pkcs11.Slot

A PKCS#11 device slot.

This object represents a physical or software slot exposed by PKCS#11. A slot has hardware capabilities, e.g. supported mechanisms and may has a physical or software Token installed.

slot_id = None

Slot identifier (opaque).

slot_description = None

Slot name (str).

manufacturer_id = None

Slot/device manufacturer’s name (str).

hardware_version = None

Hardware version (tuple).

firmware_version = None

Firmware version (tuple).

flags = None

Capabilities of this slot (SlotFlag).

get_token()

Returns the token loaded into this slot.

Return type:Token
get_mechanisms()

Returns the mechanisms supported by this device.

Return type:set(Mechanism)
get_mechanism_info(mechanism)

Returns information about the mechanism.

Parameters:mechanism (Mechanism) – mechanism to learn about
Return type:MechanismInfo
class pkcs11.Token

A PKCS#11 token.

A token can be physically installed in a Slot, or a software token, depending on your PKCS#11 library.

slot = None

The Slot this token is installed in.

label = None

Label of this token (str).

serial = None

Serial number of this token (bytes).

manufacturer_id = None

Manufacturer ID.

model = None

Model name.

hardware_version = None

Hardware version (tuple).

firmware_version = None

Firmware version (tuple).

flags = None

Capabilities of this token (pkcs11.flags.TokenFlag).

open(rw=False, user_pin=None, so_pin=None)

Open a session on the token and optionally log in as a user or security officer (pass one of user_pin or so_pin).

Can be used as a context manager or close with Session.close().

with token.open() as session:

    print(session)
Parameters:
  • rw – True to create a read/write session.
  • user_pin (bytes) – Authenticate to this session as a user.
  • so_pin (bytes) – Authenticate to this session as a security officer.
Return type:

Session

class pkcs11.Session

A PKCS#11 Token session.

A session is required to do nearly all operations on a token including encryption/signing/keygen etc.

Create a session using Token.open(). Sessions can be used as a context manager or closed with close().

token = None

Token this session is on.

rw = None

True if this is a read/write session.

user_type = None

User type for this session (pkcs11.constants.UserType).

close()

Close the session.

get_key(object_class=None, key_type=None, label=None, id=None)

Search for a key with any of key_type, label and/or id.

Returns a single key or throws pkcs11.exceptions.NoSuchKey or pkcs11.exceptions.MultipleObjectsReturned.

This is a simplified version of get_objects(), which allows searching for any object.

Parameters:
  • object_class (ObjectClass) – Optional object class.
  • key_type (KeyType) – Optional key type.
  • label (str) – Optional key label.
  • id (bytes) – Optional key id.
Return type:

Key

get_objects(attrs=None)

Search for objects matching attrs. Returns a generator.

for obj in session.get_objects({
    Attribute.CLASS: ObjectClass.SECRET_KEY,
    Attribute.LABEL: 'MY LABEL',
}):

    print(obj)

This is the more generic version of get_key().

Parameters:attrs (dict(Attribute,*)) – Attributes to search for.
Return type:iter(Object)
create_object(attrs)

Create a new object on the Token. This is a low-level interface to create any type of object and can be used for importing data onto the Token.

key = session.create_object({
    pkcs11.Attribute.CLASS: pkcs11.ObjectClass.SECRET_KEY,
    pkcs11.Attribute.KEY_TYPE: pkcs11.KeyType.AES,
    pkcs11.Attribute.VALUE: b'SUPER SECRET KEY',
})

For generating keys see generate_key() or generate_keypair(). For importing keys see Importing/Exporting Keys.

Requires a read/write session, unless the object is not to be stored.

Parameters:attrs (dict(Attribute,*)) – attributes of the object to create
Return type:Object
create_domain_parameters(key_type, attrs, local=False, store=False)

Create a domain parameters object from known parameters.

Domain parameters are used for key generation of key types such as DH, DSA and EC.

You can also generate new parameters using generate_domain_parameters().

The local parameter creates a Python object that is not created on the HSM (its object handle will be unset). This is useful if you only need the domain parameters to create another object, and do not need a real PKCS #11 object in the session.

Warning

Domain parameters have no id or labels. Storing them is possible but be aware they may be difficult to retrieve.

Parameters:
  • key_type (KeyType) – Key type these parameters are for
  • attrs (dict(Attribute,*)) – Domain parameters (specific tp key_type)
  • local – if True, do not transfer parameters to the HSM.
  • store – if True, store these parameters permanently in the HSM.
Return type:

DomainParameters

generate_domain_parameters(key_type, param_length, store=False, mechanism=None, mechanism_param=None, template=None)

Generate domain parameters.

See create_domain_parameters() for creating domain parameter objects from known parameters.

See generate_key() for documentation on mechanisms and templates.

Warning

Domain parameters have no id or labels. Storing them is possible but be aware they may be difficult to retrieve.

Parameters:
  • key_type (KeyType) – Key type these parameters are for
  • params_length (int) – Size of the parameters (e.g. prime length) in bits.
  • store – Store these parameters in the HSM
  • mechanism (Mechanism) – Optional generation mechanism (or default)
  • mechanism_param (bytes) – Optional mechanism parameter.
  • template (dict(Attribute,*)) – Optional additional attributes.
Return type:

DomainParameters

generate_key(key_type, key_length=None, id=None, label=None, store=False, capabilities=None, mechanism=None, mechanism_param=None, template=None)

Generate a single key (e.g. AES, DES).

Keys should set at least id or label.

An appropriate mechanism will be chosen for key_type (see DEFAULT_GENERATE_MECHANISMS) or this can be overridden. Similarly for the capabilities (see DEFAULT_KEY_CAPABILITIES).

The template will extend the default template used to make the key.

Possible mechanisms and template attributes are defined by PKCS #11. Invalid mechanisms or attributes should raise pkcs11.exceptions.MechanismInvalid and pkcs11.exceptions.AttributeTypeInvalid respectively.

Parameters:
  • key_type (KeyType) – Key type (e.g. KeyType.AES)
  • key_length (int) – Key length in bits (e.g. 256).
  • id (bytes) – Key identifier.
  • label (str) – Key label.
  • store – Store key on token (requires R/W session).
  • capabilities (MechanismFlag) – Key capabilities (or default).
  • mechanism (Mechanism) – Generation mechanism (or default).
  • mechanism_param (bytes) – Optional vector to the mechanism.
  • template (dict(Attribute,*)) – Additional attributes.
Return type:

SecretKey

generate_keypair(key_type, key_length=None, **kwargs)

Generate a asymmetric keypair (e.g. RSA).

See generate_key() for more information.

Parameters:
  • key_type (KeyType) – Key type (e.g. KeyType.DSA)
  • key_length (int) – Key length in bits (e.g. 256).
  • id (bytes) – Key identifier.
  • label (str) – Key label.
  • store – Store key on token (requires R/W session).
  • capabilities (MechanismFlag) – Key capabilities (or default).
  • mechanism (Mechanism) – Generation mechanism (or default).
  • mechanism_param (bytes) – Optional vector to the mechanism.
  • template (dict(Attribute,*)) – Additional attributes.
Return type:

(PublicKey, PrivateKey)

seed_random(seed)

Mix additional seed material into the RNG (if supported).

Parameters:seed (bytes) – Bytes of random to seed.
generate_random(nbits)

Generate length bits of random or pseudo-random data (if supported).

Parameters:nbits (int) – Number of bits to generate.
Return type:bytes
digest(data, **kwargs)

Digest data using mechanism.

data can be a single value or an iterator.

Key objects can also be digested, optionally interspersed with bytes.

Parameters:
Return type:

bytes

Token Objects

The following classes relate to Object objects on the Token.

class pkcs11.Object

A PKCS#11 object residing on a Token.

Objects implement __getitem__() and __setitem__() to retrieve pkcs11.constants.Attribute values on the object. Valid attributes for an object are given in PKCS #11. Invalid attributes should raise pkcs11.exceptions.AttributeTypeInvalid.

object_class = None

pkcs11.constants.ObjectClass of this Object.

session = None

Session this object is valid for.

copy(attrs)

Make a copy of the object with new attributes attrs.

Requires a read/write session, unless the object is not to be stored.

new = key.copy({
    Attribute.LABEL: 'MY NEW KEY',
})

Certain objects may not be copied. Calling copy() on such objects will result in an exception.

Parameters:attrs (dict(Attribute,*)) – attributes for the new Object
Return type:Object
destroy()

Destroy the object.

Requires a read/write session, unless the object is not stored.

Certain objects may not be destroyed. Calling destroy() on such objects will result in an exception.

The Object is no longer valid.

class pkcs11.Key(Object)

Base class for all key Object types.

id

Key id (bytes).

label

Key label (str).

key_type

Key type (pkcs11.mechanisms.KeyType).

class pkcs11.SecretKey(Key)

A PKCS#11 pkcs11.constants.ObjectClass.SECRET_KEY object (symmetric encryption key).

key_length

Key length in bits.

class pkcs11.PublicKey(Key)

A PKCS#11 pkcs11.constants.ObjectClass.PUBLIC_KEY object (asymmetric public key).

RSA private keys can be imported and exported from PKCS#1 DER-encoding using pkcs11.util.rsa.decode_rsa_public_key() and pkcs11.util.rsa.encode_rsa_public_key() respectively.

key_length

Key length in bits.

class pkcs11.PrivateKey(Key)

A PKCS#11 pkcs11.constants.ObjectClass.PRIVATE_KEY object (asymmetric private key).

RSA private keys can be imported from PKCS#1 DER-encoding using pkcs11.util.rsa.decode_rsa_private_key().

Warning

Private keys imported directly, rather than unwrapped from a trusted private key should be considered insecure.

key_length

Key length in bits.

class pkcs11.DomainParameters(Object)

PKCS#11 Domain Parameters.

Used to store domain parameters as part of the key generation step, e.g. in DSA and Diffie-Hellman.

key_type

Key type (pkcs11.mechanisms.KeyType) these parameters can be used to generate.

generate_keypair(id=None, label=None, store=False, capabilities=None, mechanism=None, mechanism_param=None, public_template=None, private_template=None)

Generate a key pair from these domain parameters (e.g. for Diffie-Hellman.

See Session.generate_key() for more information.

Parameters:
  • id (bytes) – Key identifier.
  • label (str) – Key label.
  • store – Store key on token (requires R/W session).
  • capabilities (MechanismFlag) – Key capabilities (or default).
  • mechanism (Mechanism) – Generation mechanism (or default).
  • mechanism_param (bytes) – Optional vector to the mechanism.
  • template (dict(Attribute,*)) – Additional attributes.
Return type:

(PublicKey, PrivateKey)

class pkcs11.Certificate(Object)

A PKCS#11 pkcs11.constants.ObjectClass.CERTIFICATE object.

PKCS#11 is limited in its handling of certificates, and does not provide features like parsing of X.509 etc. These should be handled in an external library. PKCS#11 will not set attributes on the certificate based on the VALUE.

pkcs11.util.x509.decode_x509_certificate() will extract attributes from a certificate to create the object.

certificate_type

The type of certificate.

Return type:CertificateType

Object Capabilities

Capability mixins for Object objects.

class pkcs11.EncryptMixin

This Object supports the encrypt capability.

encrypt(data, buffer_size=8192, **kwargs)

Encrypt some data.

Data can be either str or bytes, in which case it will return bytes; or an iterable of bytes in which case it will return a generator yielding bytes (be aware, more chunks will be output than input).

If you do not specify mechanism then the default from DEFAULT_ENCRYPT_MECHANISMS will be used. If an iterable is passed and the mechanism chosen does not support handling data in chunks, an exception will be raised.

Some mechanisms (including the default CBC mechanisms) require additional parameters, e.g. an initialisation vector [1], to the mechanism. Pass this as mechanism_param. Documentation of these parameters is given specified in PKCS #11.

When passing an iterable for data buffer_size must be sufficient to store the working buffer. An integer number of blocks and greater than or equal to the largest input chunk is recommended.

The returned generator obtains a lock on the Session to prevent other threads from starting a simultaneous operation. The lock is released when you consume/destroy the generator. See Concurrency.

Warning

It’s not currently possible to cancel an encryption operation by deleting the generator. You must consume the generator to complete the operation.

An example of streaming a file is as follows:

def encrypt_file(file_in, file_out, buffer_size=8192):

    with \
            open(file_in, 'rb') as input_, \
            open(file_out, 'wb') as output:

        chunks = iter(lambda: input_.read(buffer_size), '')

        for chunk in key.encrypt(chunks,
                                 mechanism_param=iv,
                                 buffer_size=buffer_size):
            output.write(chunk)
Parameters:
  • data (str, bytes or iter(bytes)) – data to encrypt
  • mechanism (Mechanism) – optional encryption mechanism (or None for default)
  • mechanism_param (bytes) – optional mechanism parameter (e.g. initialisation vector).
  • buffer_size (int) – size of the working buffer (for generators)
Return type:

bytes or iter(bytes)

[1]The initialisation vector should contain quality random, e.g. from Session.generate_random(). This method will not return the value of the initialisation vector as part of the encryption. You must store that yourself.
class pkcs11.DecryptMixin

This Object supports the decrypt capability.

decrypt(data, buffer_size=8192, **kwargs)

Decrypt some data.

See EncryptMixin.encrypt() for more information.

Parameters:
  • data (bytes or iter(bytes)) – data to decrypt
  • mechanism (Mechanism) – optional encryption mechanism (or None for default).
  • mechanism_param (bytes) – optional mechanism parameter (e.g. initialisation vector).
  • buffer_size (int) – size of the working buffer (for generators).
Return type:

bytes or iter(bytes)

class pkcs11.SignMixin

This Object supports the sign capability.

sign(data, **kwargs)

Sign some data.

See EncryptMixin.encrypt() for more information.

For DSA and ECDSA keys, PKCS #11 outputs the two parameters (r & s) as two concatenated biginteger of the same length. To convert these into other formats, such as the format used by OpenSSL, use pkcs11.util.dsa.encode_dsa_signature() or pkcs11.util.ec.encode_ecdsa_signature().

Parameters:
  • data (str, bytes or iter(bytes)) – data to sign
  • mechanism (Mechanism) – optional signing mechanism
  • mechanism_param (bytes) – optional mechanism parameter
Return type:

bytes

class pkcs11.VerifyMixin

This Object supports the verify capability.

verify(data, signature, **kwargs)

Verify some data.

See EncryptMixin.encrypt() for more information.

Returns True if signature is valid for data.

For DSA and ECDSA keys, PKCS #11 expects the two parameters (r & s) as two concatenated biginteger of the same length. To convert these from other formats, such as the format used by OpenSSL, use pkcs11.util.dsa.decode_dsa_signature() or pkcs11.util.ec.decode_ecdsa_signature().

Parameters:
  • data (str, bytes or iter(bytes)) – data to sign
  • signature (bytes) – signature
  • mechanism (Mechanism) – optional signing mechanism
  • mechanism_param (bytes) – optional mechanism parameter
Return type:

bool

class pkcs11.WrapMixin

This Object supports the wrap capability.

wrap_key(key, mechanism=None, mechanism_param=None)

Use this key to wrap (i.e. encrypt) key for export. Returns an encrypted version of key.

key must have Attribute.EXTRACTABLE = True.

Parameters:
  • key (Key) – key to export
  • mechanism (Mechanism) – wrapping mechanism (or None for default).
  • mechanism_param (bytes) – mechanism parameter (if required)
Return type:

bytes

class pkcs11.UnwrapMixin

This Object supports the unwrap capability.

unwrap_key(object_class, key_type, key_data, id=None, label=None, mechanism=None, mechanism_param=None, store=False, capabilities=None, template=None)

Use this key to unwrap (i.e. decrypt) and import key_data.

See Session.generate_key for more information.

Parameters:
  • object_class (ObjectClass) – Object class to import as
  • key_type (KeyType) – Key type (e.g. KeyType.AES)
  • key_data (bytes) – Encrypted key to unwrap
  • id (bytes) – Key identifier.
  • label (str) – Key label.
  • store – Store key on token (requires R/W session).
  • capabilities (MechanismFlag) – Key capabilities (or default).
  • mechanism (Mechanism) – Generation mechanism (or default).
  • mechanism_param (bytes) – Optional vector to the mechanism.
  • template (dict(Attribute,*)) – Additional attributes.
Return type:

Key

class pkcs11.DeriveMixin

This Object supports the derive capability.

derive_key(key_type, key_length, id=None, label=None, store=False, capabilities=None, mechanism=None, mechanism_param=None, template=None)

Derive a new key from this key. Used to create session keys from a PKCS key exchange.

Typically the mechanism, e.g. Diffie-Hellman, requires you to specify the other party’s piece of shared information as the mechanism_param. Some mechanisms require a tuple of data (see pkcs11.mechanisms.Mechanism).

See Session.generate_key for more documentation on key generation.

Diffie-Hellman example:

# Diffie-Hellman domain parameters
# e.g. from RFC 3526, RFC 5114 or `openssl dhparam`
prime = [0xFF, ...]
base = [0x02]

parameters = session.create_domain_parameters(KeyType.DH, {
    Attribute.PRIME: prime,
    Attribute.BASE: base,
}, local=True)

# Alice generates a DH key pair from the public
# Diffie-Hellman parameters
public, private = parameters.generate_keypair()
alices_value = public[Attribute.VALUE]

# Bob generates a DH key pair from the same parameters.

# Alice exchanges public values with Bob...
# She sends `alices_value` and receives `bobs_value`.
# (Assuming Alice is doing AES CBC, she also needs to send an IV)

# Alice generates a session key with Bob's public value
# Bob will generate the same session key using Alice's value.
session_key = private.derive_key(
    KeyType.AES, 128,
    mechanism_param=bobs_value)

Elliptic-Curve Diffie-Hellman example:

# DER encoded EC params, e.g. from OpenSSL
# openssl ecparam -outform der -name prime192v1 | base64
#
# Check what EC parameters the module supports with
# slot.get_module_info()
parameters = session.create_domain_parameters(KeyType.EC, {
    Attribute.EC_PARAMS: b'...',
}, local=True)

# Alice generates a EC key pair, and gets her public value
public, private = parameters.generate_keypair()
alices_value = public[Attribute.EC_POINT]

# Bob generates a DH key pair from the same parameters.

# Alice exchanges public values with Bob...
# She sends `alices_value` and receives `bobs_value`.

# Alice generates a session key with Bob's public value
# Bob will generate the same session key using Alice's value.
session_key = private.derive_key(
    KeyType.AES, 128,
    mechanism_param=(KDF.NULL, None, bobs_value))
Parameters:
  • key_type (KeyType) – Key type (e.g. KeyType.AES)
  • key_length (int) – Key length in bits (e.g. 256).
  • id (bytes) – Key identifier.
  • label (str) – Key label.
  • store – Store key on token (requires R/W session).
  • capabilities (MechanismFlag) – Key capabilities (or default).
  • mechanism (Mechanism) – Generation mechanism (or default).
  • mechanism_param (bytes) – Optional vector to the mechanism.
  • template (dict(Attribute,*)) – Additional attributes.
Return type:

SecretKey

Constants

PKCS#11 constants.

See the Python enum documentation for more information on how to use these classes.

class pkcs11.constants.UserType(*args, **kwds)

PKCS#11 user types.

NOBODY = 999

Not officially in the PKCS#11 spec. Used to represent a session that is not logged in.

SO = 0

Security officer.

USER = 1
class pkcs11.constants.ObjectClass(*args, **kwds)

PKCS#11 Object class.

This is the type of object we have.

DATA = 0
CERTIFICATE = 1

See pkcs11.Certificate.

PUBLIC_KEY = 2

See pkcs11.PublicKey.

PRIVATE_KEY = 3

See pkcs11.PrivateKey.

SECRET_KEY = 4

See pkcs11.SecretKey.

HW_FEATURE = 5
DOMAIN_PARAMETERS = 6

See pkcs11.DomainParameters.

MECHANISM = 7
OTP_KEY = 8
class pkcs11.constants.Attribute(*args, **kwds)

PKCS#11 object attributes.

Not all attributes are relevant to all objects. Relevant attributes for each object type are given in PKCS #11.

CLASS = 0

Object type (ObjectClass).

TOKEN = 1

If True object will be stored to token. Otherwise has session lifetime (bool).

PRIVATE = 2

True if user must be authenticated to access this object (bool).

LABEL = 3

Object label (str).

APPLICATION = 16
VALUE = 17

Object value. Usually represents a secret or private key. For certificates this is the complete certificate in the certificate’s native format (e.g. BER-encoded X.509 or WTLS encoding).

May be SENSITIVE (bytes).

OBJECT_ID = 18
CERTIFICATE_TYPE = 128

Certificate type (CertificateType).

ISSUER = 129

Certificate issuer in certificate’s native format (e.g. X.509 DER-encoding or WTLS encoding) (bytes).

SERIAL_NUMBER = 130

Certificate serial number in certificate’s native format (e.g. X.509 DER-encoding) (bytes).

AC_ISSUER = 131

Attribute Certificate Issuer. Different from ISSUER because the encoding is different (bytes).

OWNER = 132

Attribute Certificate Owner. Different from SUBJECT because the encoding is different (bytes).

ATTR_TYPES = 133

BER-encoding of a sequence of object identifier values corresponding to the attribute types contained in the certificate. When present, this field offers an opportunity for applications to search for a particular attribute certificate without fetching and parsing the certificate itself.

TRUSTED = 134

This key can be used to wrap keys with WRAP_WITH_TRUSTED set; or this certificate can be trusted. (bool).

CERTIFICATE_CATEGORY = 135

Certificate category (CertificateCategory).

JAVA_MIDP_SECURITY_DOMAIN = 136
URL = 137

URL where the complete certificate can be obtained.

HASH_OF_SUBJECT_PUBLIC_KEY = 138

Hash of the certificate subject’s public key.

HASH_OF_ISSUER_PUBLIC_KEY = 139

Hash of the certificate issuer’s public key.

CHECK_VALUE = 144

VALUE checksum. Key Check Value (bytes).

KEY_TYPE = 256

Key type (KeyType).

SUBJECT = 257

Certificate subject in certificate’s native format (e.g. X.509 DER-encoding or WTLS encoding) (bytes).

ID = 258

Key ID (bytes).

SENSITIVE = 259

Sensitive attributes cannot be retrieved from the HSM (e.g. VALUE or PRIVATE_EXPONENT) (bool).

ENCRYPT = 260

Key supports encryption (bool).

DECRYPT = 261

Key supports decryption (bool).

WRAP = 262

Key supports wrapping (bool).

UNWRAP = 263

Key supports unwrapping (bool).

SIGN = 264

Key supports signing (bool).

SIGN_RECOVER = 265
VERIFY = 266

Key supports signature verification (bool).

VERIFY_RECOVER = 267
DERIVE = 268

Key supports key derivation (bool).

START_DATE = 272

Start date for the object’s validity (datetime.date).

END_DATE = 273

End date for the object’s validity (datetime.date).

MODULUS = 288

RSA private key modulus (n) (biginteger as bytes).

MODULUS_BITS = 289

RSA private key modulus length. Use this for private key generation (int).

PUBLIC_EXPONENT = 290

RSA public exponent (e) (biginteger as bytes).

Default is b’’ (65537).

PRIVATE_EXPONENT = 291

RSA private exponent (d) (biginteger as bytes).

PRIME_1 = 292

RSA private key prime #1 (p). May not be stored. (biginteger as bytes).

PRIME_2 = 293

RSA private key prime #2 (q). May not be stored. (biginteger as bytes).

EXPONENT_1 = 294

RSA private key exponent #1 (d mod p-1). May not be stored. (biginteger as bytes).

EXPONENT_2 = 295

RSA private key exponent #2 (d mod q-1). May not be stored. (biginteger as bytes).

COEFFICIENT = 296

RSA private key CRT coefficient (q^-1 mod p). May not be stored. (biginteger as bytes).

PRIME = 304

Prime number ‘q’ (used for DH). (biginteger as bytes).

SUBPRIME = 305

Subprime number ‘q’ (used for DH). (biginteger as bytes).

BASE = 306

Base number ‘g’ (used for DH). (biginteger as bytes).

PRIME_BITS = 307
SUBPRIME_BITS = 308
VALUE_BITS = 352
VALUE_LEN = 353

VALUE length in bytes. Use this for secret key generation (int).

EXTRACTABLE = 354

Key can be extracted wrapped.

LOCAL = 355

True if generated on the token, False if imported.

NEVER_EXTRACTABLE = 356

EXTRACTABLE has always been False.

ALWAYS_SENSITIVE = 357

SENSITIVE has always been True.

KEY_GEN_MECHANISM = 358

Key generation mechanism (pkcs11.mechanisms.Mechanism).

MODIFIABLE = 368

Object can be modified (bool).

EC_PARAMS = 384

DER-encoded ANSI X9.62 Elliptic-Curve domain parameters (bytes).

These can be output by OpenSSL (for named curves):

openssl ecparam -outform der -name <curve name> | base64

Or packed using pyasn1:

from pyasn1_modules.rfc3279 import prime256v1
from pkcs11.ecutils import encode_named_curve_parameters

ecParams = encode_named_curve_parameters(prime256v1)
EC_POINT = 385

DER-encoded ANSI X9.62 Public key for KeyType.EC (bytes).

SECONDARY_AUTH = 512
AUTH_PIN_FLAGS = 513
ALWAYS_AUTHENTICATE = 514

User has to provide pin with each use (sign or decrypt) (bool).

WRAP_WITH_TRUSTED = 528

Key can only be wrapped with a TRUSTED key.

WRAP_TEMPLATE = 1073742353
UNWRAP_TEMPLATE = 1073742354
DERIVE_TEMPLATE = 1073742355
OTP_FORMAT = 544
OTP_LENGTH = 545
OTP_TIME_INTERVAL = 546
OTP_USER_FRIENDLY_MODE = 547
OTP_CHALLENGE_REQUIREMENT = 548
OTP_TIME_REQUIREMENT = 549
OTP_COUNTER_REQUIREMENT = 550
OTP_PIN_REQUIREMENT = 551
OTP_COUNTER = 558
OTP_TIME = 559
OTP_USER_IDENTIFIER = 554
OTP_SERVICE_IDENTIFIER = 555
OTP_SERVICE_LOGO_TYPE = 557
GOSTR3410_PARAMS = 592
GOSTR3411_PARAMS = 593
GOST28147_PARAMS = 594
HW_FEATURE_TYPE = 768
RESET_ON_INIT = 769
HAS_RESET = 770
PIXEL_X = 1024
PIXEL_Y = 1025
RESOLUTION = 1026
CHAR_ROWS = 1027
CHAR_COLUMNS = 1028
COLOR = 1029
BITS_PER_PIXEL = 1030
CHAR_SETS = 1152
ENCODING_METHODS = 1153
MIME_TYPES = 1154
MECHANISM_TYPE = 1280
REQUIRED_CMS_ATTRIBUTES = 1281
DEFAULT_CMS_ATTRIBUTES = 1282
SUPPORTED_CMS_ATTRIBUTES = 1283
ALLOWED_MECHANISMS = 1073743360
class pkcs11.constants.CertificateType(*args, **kwds)

Certificate type of a pkcs11.Certificate.

X_509 = 0
X_509_ATTR_CERT = 1
WTLS = 2
class pkcs11.constants.MechanismFlag(*args, **kwds)

Describes the capabilities of a pkcs11.mechanisms.Mechanism or pkcs11.Object.

Some objects and mechanisms are symmetric (i.e. can be used for encryption and decryption), some are asymmetric (e.g. public key cryptography).

HW = 1

Mechanism is performed in hardware.

ENCRYPT = 256

Can be used for encryption.

DECRYPT = 512

Can be used for decryption.

DIGEST = 1024

Can make a message digest (hash).

SIGN = 2048

Can calculate digital signature.

SIGN_RECOVER = 4096
VERIFY = 8192

Can verify digital signature.

VERIFY_RECOVER = 16384
GENERATE = 32768

Can generate key/object.

GENERATE_KEY_PAIR = 65536

Can generate key pair.

WRAP = 131072

Can wrap a key for export.

UNWRAP = 262144

Can unwrap a key for import.

DERIVE = 524288

Can derive a key from another key.

EC_F_P = 1048576
EC_F_2M = 2097152
EC_ECPARAMETERS = 4194304
EC_NAMEDCURVE = 8388608
EC_UNCOMPRESS = 16777216
EC_COMPRESS = 33554432
EXTENSION = 2147483648
class pkcs11.constants.SlotFlag(*args, **kwds)

pkcs11.Slot flags.

TOKEN_PRESENT = 1

A token is present in the slot (N.B. some hardware known not to set this for soft-tokens.)

REMOVABLE_DEVICE = 2

Removable devices.

HW_SLOT = 4

Hardware slot.

class pkcs11.constants.TokenFlag(*args, **kwds)

pkcs11.Token flags.

RNG = 1

Has random number generator.

WRITE_PROTECTED = 2

Token is write protected.

LOGIN_REQUIRED = 4

User must login.

USER_PIN_INITIALIZED = 8

Normal user’s pin is set.

RESTORE_KEY_NOT_NEEDED = 32

If it is set, that means that every time the state of cryptographic operations of a session is successfully saved, all keys needed to continue those operations are stored in the state.

CLOCK_ON_TOKEN = 64

If it is set, that means that the token has some sort of clock. The time on that clock is returned in the token info structure.

PROTECTED_AUTHENTICATION_PATH = 256

If it is set, that means that there is some way for the user to login without sending a PIN through the Cryptoki library itself.

DUAL_CRYPTO_OPERATIONS = 512

If it is true, that means that a single session with the token can perform dual simultaneous cryptographic operations (digest and encrypt; decrypt and digest; sign and encrypt; and decrypt and sign).

TOKEN_INITIALIZED = 1024

If it is true, the token has been initialized using C_InitializeToken or an equivalent mechanism outside the scope of PKCS #11. Calling C_InitializeToken when this flag is set will cause the token to be reinitialized.

USER_PIN_COUNT_LOW = 65536

If it is true, an incorrect user login PIN has been entered at least once since the last successful authentication.

USER_PIN_FINAL_TRY = 131072

If it is true, supplying an incorrect user PIN will it to become locked.

USER_PIN_LOCKED = 262144

If it is true, the user PIN has been locked. User login to the token is not possible.

USER_PIN_TO_BE_CHANGED = 524288

If it is true, the user PIN value is the default value set by token initialization or manufacturing, or the PIN has been expired by the card.

SO_PIN_COUNT_LOW = 1048576

If it is true, an incorrect SO (security officer) login PIN has been entered at least once since the last successful authentication.

SO_PIN_FINAL_TRY = 2097152

If it is true, supplying an incorrect SO (security officer) PIN will it to become locked.

SO_PIN_LOCKED = 4194304

If it is true, the SO (security officer) PIN has been locked. SO login to the token is not possible.

SO_PIN_TO_BE_CHANGED = 8388608

If it is true, the SO PIN value is the default value set by token initialization or manufacturing, or the PIN has been expired by the card.

ERROR_STATE = 16777216

Key Types & Mechanisms

class pkcs11.mechanisms.KeyType

Key types known by PKCS#11.

Making use of a given key type requires the appropriate Mechanism to be available.

Key types beginning with an underscore are historic and are best avoided.

RSA = 0

See the RSA section of the PKCS #11 specification for valid Mechanism and pkcs11.constants.Attribute types.

DSA = 1

See the DSA section of the PKCS #11 specification for valid Mechanism and pkcs11.constants.Attribute types.

DH = 2

PKCS #3 Diffie-Hellman key. See the Diffie-Hellman section of the PKCS #11 specification for valid Mechanism and pkcs11.constants.Attribute types.

EC = 3

See the Elliptic Curve section of the PKCS #11 specification for valid Mechanism and pkcs11.constants.Attribute types.

X9_42_DH = 4

X9.42 Diffie-Hellman key.

GENERIC_SECRET = 16
DES2 = 20

Warning

Considered insecure. Use AES where possible.

DES3 = 21

Warning

Considered insecure. Use AES where possible.

AES = 31

See the AES section of PKCS#11 for valid Mechanism and pkcs11.constants.Attribute types.

BLOWFISH = 32
TWOFISH = 33
SECURID = 34
HOTP = 35
ACTI = 36
CAMELLIA = 37
ARIA = 38
SHA_1_HMAC = 40

Warning

SHA-1 is no longer considered secure.

SHA256_HMAC = 43
SHA384_HMAC = 44
SHA512_HMAC = 45
SHA224_HMAC = 46
SEED = 47
GOSTR3410 = 48
GOSTR3411 = 49
GOST28147 = 50
class pkcs11.mechanisms.Mechanism

Cryptographic mechanisms known by PKCS#11.

The list of supported cryptographic mechanisms for a pkcs11.Slot can be retrieved with pkcs11.Slot.get_mechanisms().

Mechanisms beginning with an underscore are historic and best avoided. Descriptions of the current and historical mechanisms, including their valid pkcs11.constants.Attribute types and mechanism_param can be found in the PKCS#11 specification.

Additionally, while still in the current spec, a number of mechanisms including cryptographic hash functions and certain block modes are no longer considered secure, and should not be used for new applications, e.g. MD2, MD5, SHA1, ECB.

RSA_PKCS_KEY_PAIR_GEN = 0

RSA PKCS #1 v1.5 key generation.

Note

Default for generating KeyType.RSA keys.

RSA_PKCS = 1

RSA PKCS #1 v1.5 general purpose mechanism.

Warning

Consider using the more robust PKCS#1 OAEP.

RSA_PKCS_TPM_1_1 = 16385

Warning

Consider using the more robust PKCS#1 OAEP.

RSA_PKCS_OAEP = 9

RSA PKCS #1 OAEP (v2.0+)

Note

Default for encrypting/decrypting with KeyType.RSA keys.

Optionally takes a mechanism_param which is a tuple of:

  • message digest algorithm used to calculate the digest of the encoding parameter (Mechanism), default is Mechanism.SHA_1;
  • mask generation function to use on the encoded block (MGF), default is MGF.SHA1;
  • data used as the input for the encoding parameter source (bytes), default is None.
RSA_PKCS_OAEP_TPM_1_1 = 16386
RSA_X_509 = 3

X.509 (raw) RSA.

No padding, supply your own.

RSA_9796 = 2

ISO/IEC 9796 RSA.

Warning

DS1 and DS3 are considered broken. The PKCS #11 spec doesn’t specify which scheme is used. Use PSS instead.

MD2_RSA_PKCS = 4

Warning

Not considered secure.

MD5_RSA_PKCS = 5

Warning

Not considered secure.

SHA1_RSA_PKCS = 6

Warning

SHA-1 is no longer considered secure.

SHA224_RSA_PKCS = 70
SHA256_RSA_PKCS = 64
SHA384_RSA_PKCS = 65
SHA512_RSA_PKCS = 66

Note

Default for signing/verification with KeyType.RSA keys.

RSA_PKCS_PSS = 13

RSA PSS without hashing.

PSS schemes optionally take a tuple of:

  • message digest algorithm used to calculate the digest of the encoding parameter (Mechanism), default is Mechanism.SHA_1;
  • mask generation function to use on the encoded block (MGF), default is MGF.SHA1; and
  • salt length, default is 20
SHA1_RSA_PKCS_PSS = 14

Warning

SHA-1 is no longer considered secure.

SHA224_RSA_PKCS_PSS = 71
SHA256_RSA_PKCS_PSS = 67
SHA384_RSA_PKCS_PSS = 68
SHA512_RSA_PKCS_PSS = 69
RSA_X9_31_KEY_PAIR_GEN = 10
RSA_X9_31 = 11
SHA1_RSA_X9_31 = 12

Warning

SHA-1 is no longer considered secure.

DSA_KEY_PAIR_GEN = 16

Note

Default mechanism for generating KeyType.DSA keypairs

Requires pkcs11.DomainParameters.

DSA = 17

DSA without hashing.

DSA_SHA1 = 18

Warning

SHA-1 is no longer considered secure.

DSA_SHA224 = 19
DSA_SHA256 = 20
DSA_SHA384 = 21
DSA_SHA512 = 22

DSA with SHA512 hashing.

Note

Default for signing/verification with KeyType.DSA keys.

DH_PKCS_KEY_PAIR_GEN = 32

Note

Default mechanism for generating KeyType.DH key pairs.

This is the mechanism defined in PKCS #3.

Requires pkcs11.DomainParameters of pkcs11.constants.Attribute.BASE and pkcs11.constants.Attribute.PRIME.

DH_PKCS_DERIVE = 33

Note

Default mechanism for deriving shared keys from KeyType.DH private keys.

This is the mechanism defined in PKCS #3.

Takes the other participant’s public key pkcs11.constants.Attribute.VALUE as the mechanism_param.

X9_42_DH_KEY_PAIR_GEN = 48
X9_42_DH_DERIVE = 49
X9_42_DH_HYBRID_DERIVE = 50
X9_42_MQV_DERIVE = 51
DES2_KEY_GEN = 304

Note

Default for generating DES2 keys.

Warning

Considered insecure. Use AES where possible.

DES3_KEY_GEN = 305

Note

Default for generating DES3 keys.

Warning

Considered insecure. Use AES where possible.

DES3_ECB = 306

Note

Default for key wrapping with DES2/3.

Warning

Identical blocks will encipher to the same result. Considered insecure. Use AES where possible.

DES3_CBC = 307
DES3_MAC = 308

Note

This is the default for signing/verification with KeyType.DES2 and KeyType.DES3.

Warning

Considered insecure. Use AES where possible.

DES3_MAC_GENERAL = 309
DES3_CBC_PAD = 310

Note

Default for encryption/decryption with DES2/3.

Warning

Considered insecure. Use AES where possible.

DES3_CMAC_GENERAL = 311
DES3_CMAC = 312
SHA_1 = 544

Warning

SHA-1 is no longer considered secure.

SHA_1_HMAC = 545

Warning

SHA-1 is no longer considered secure.

SHA_1_HMAC_GENERAL = 546

Warning

SHA-1 is no longer considered secure.

SHA256 = 592
SHA256_HMAC = 593
SHA256_HMAC_GENERAL = 594
SHA224 = 597
SHA224_HMAC = 598
SHA224_HMAC_GENERAL = 599
SHA384 = 608
SHA384_HMAC = 609
SHA384_HMAC_GENERAL = 610
SHA512 = 624
SHA512_HMAC = 625
SHA512_HMAC_GENERAL = 626
SECURID_KEY_GEN = 640
SECURID = 642
HOTP_KEY_GEN = 656
HOTP = 657
ACTI = 672
ACTI_KEY_GEN = 673
GENERIC_SECRET_KEY_GEN = 848
CONCATENATE_BASE_AND_KEY = 864
CONCATENATE_BASE_AND_DATA = 866
CONCATENATE_DATA_AND_BASE = 867
XOR_BASE_AND_DATA = 868
EXTRACT_KEY_FROM_KEY = 869
SSL3_PRE_MASTER_KEY_GEN = 880
SSL3_MASTER_KEY_DERIVE = 881
SSL3_KEY_AND_MAC_DERIVE = 882
SSL3_MASTER_KEY_DERIVE_DH = 883
SSL3_MD5_MAC = 896
SSL3_SHA1_MAC = 897
TLS_PRE_MASTER_KEY_GEN = 884
TLS_MASTER_KEY_DERIVE = 885
TLS_KEY_AND_MAC_DERIVE = 886
TLS_MASTER_KEY_DERIVE_DH = 887
TLS_PRF = 888
SHA1_KEY_DERIVATION = 914
SHA256_KEY_DERIVATION = 915
SHA384_KEY_DERIVATION = 916
SHA512_KEY_DERIVATION = 917
SHA224_KEY_DERIVATION = 918
PKCS5_PBKD2 = 944
WTLS_PRE_MASTER_KEY_GEN = 976
WTLS_MASTER_KEY_DERIVE = 977
WTLS_MASTER_KEY_DERIVE_DH_ECC = 978
WTLS_PRF = 979
WTLS_SERVER_KEY_AND_MAC_DERIVE = 980
WTLS_CLIENT_KEY_AND_MAC_DERIVE = 981
CMS_SIG = 1280
KIP_DERIVE = 1296
KIP_WRAP = 1297
KIP_MAC = 1298
SEED_KEY_GEN = 1616
SEED_ECB = 1617

Warning

Identical blocks will encipher to the same result.

SEED_CBC = 1618
SEED_MAC = 1619
SEED_MAC_GENERAL = 1620
SEED_CBC_PAD = 1621
SEED_ECB_ENCRYPT_DATA = 1622
SEED_CBC_ENCRYPT_DATA = 1623
EC_KEY_PAIR_GEN = 4160

Note

Default mechanism for generating KeyType.EC key pairs

Requires pkcs11.DomainParameters of pkcs11.constants.Attribute.EC_PARAMS.

ECDSA = 4161

ECDSA with no hashing. Input truncated to 1024-bits.

ECDSA_SHA1 = 4162

Warning

SHA-1 is no longer considered secure.

ECDSA_SHA224 = 4163
ECDSA_SHA256 = 4164
ECDSA_SHA384 = 4165
ECDSA_SHA512 = 4166

ECDSA with SHA512 hashing.

Note

Default for signing/verification with KeyType.EC keys.

ECDH1_DERIVE = 4176

Note

Default mechanism for deriving shared keys from KeyType.EC private keys.

Takes a tuple of:

as the mechanism_param.

ECDH1_COFACTOR_DERIVE = 4177
ECMQV_DERIVE = 4178
AES_KEY_GEN = 4224

Note

Default for generating KeyType.AES keys.

AES_ECB = 4225

Note

Default wrapping mechanism for KeyType.AES keys.

Warning

Identical blocks will encipher to the same result.

AES_CBC = 4226
AES_CBC_PAD = 4229

CBC with PKCS#7 padding to pad files to a whole number of blocks.

Note

Default for encrypting/decrypting with KeyType.AES keys.

Requires a 128-bit initialisation vector passed as mechanism_param.

AES_CTR = 4230
AES_CTS = 4233
AES_MAC = 4227

Note

This is the default for signing/verification with KeyType.AES.

AES_MAC_GENERAL = 4228
AES_CMAC = 4234
AES_CMAC_GENERAL = 4235
BLOWFISH_KEY_GEN = 4240
BLOWFISH_CBC = 4241
BLOWFISH_CBC_PAD = 4244
TWOFISH_KEY_GEN = 4242
TWOFISH_CBC = 4243
TWOFISH_CBC_PAD = 4245
AES_GCM = 4231
AES_CCM = 4232
DES_ECB_ENCRYPT_DATA = 4352
DES_CBC_ENCRYPT_DATA = 4353
DES3_ECB_ENCRYPT_DATA = 4354
DES3_CBC_ENCRYPT_DATA = 4355
AES_ECB_ENCRYPT_DATA = 4356
AES_CBC_ENCRYPT_DATA = 4357
GOSTR3410_KEY_PAIR_GEN = 4608
GOSTR3410 = 4609
GOSTR3410_WITH_GOSTR3411 = 4610
GOSTR3410_KEY_WRAP = 4611
GOSTR3410_DERIVE = 4612
GOSTR3411 = 4624
GOSTR3411_HMAC = 4625
GOST28147_KEY_GEN = 4640
GOST28147_ECB = 4641

Warning

Identical blocks will encipher to the same result.

GOST28147 = 4642
GOST28147_MAC = 4643
GOST28147_KEY_WRAP = 4644
DSA_PARAMETER_GEN = 8192

Note

Default mechanism for generating KeyType.DSA domain parameters.

DH_PKCS_PARAMETER_GEN = 8193

Note

Default mechanism for generating KeyType.DH domain parameters.

This is the mechanism defined in PKCS #3.

X9_42_DH_PARAMETER_GEN = 8194

Note

Default mechanism for generating KeyType.X9_42_DH domain parameters (X9.42 DH).

AES_OFB = 8452
AES_CFB64 = 8453
AES_CFB8 = 8454
AES_CFB128 = 8455
class pkcs11.mechanisms.KDF

Key Derivation Functions.

NULL = 1
SHA1 = 2
SHA1_ASN1 = 3
SHA1_CONCATENATE = 4
SHA224 = 5
SHA256 = 6
SHA384 = 7
SHA512 = 8
CPDIVERSIFY = 9
class pkcs11.mechanisms.MGF

RSA PKCS #1 Mask Generation Functions.

SHA1 = 1
SHA256 = 2
SHA384 = 3
SHA512 = 4
SHA224 = 5
class pkcs11.MechanismInfo

Information about a mechanism.

See pkcs11.Slot.get_mechanism_info().

slot = None

pkcs11.Slot this information is for.

mechanism = None

pkcs11.mechanisms.Mechanism this information is for.

min_key_length = None

Minimum key length in bits (int).

max_key_length = None

Maximum key length in bits (int).

flags = None

Mechanism capabilities (pkcs11.constants.MechanismFlag).

Exceptions

PKCS#11 return codes are exposed as Python exceptions inheriting from PKCS11Error.

exception pkcs11.exceptions.PKCS11Error

Base exception for all PKCS#11 exceptions.

exception pkcs11.exceptions.AlreadyInitialized

pkcs11 was already initialized with another library.

exception pkcs11.exceptions.AnotherUserAlreadyLoggedIn
exception pkcs11.exceptions.AttributeTypeInvalid
exception pkcs11.exceptions.AttributeValueInvalid
exception pkcs11.exceptions.AttributeReadOnly

An attempt was made to set a value for an attribute which may not be set by the application, or which may not be modified by the application.

exception pkcs11.exceptions.AttributeSensitive

An attempt was made to obtain the value of an attribute of an object which cannot be satisfied because the object is either sensitive or un-extractable.

exception pkcs11.exceptions.ArgumentsBad

Bad arguments were passed into PKCS#11.

This can indicate missing parameters to a mechanism or some other issue. Consult your PKCS#11 vendor documentation.

exception pkcs11.exceptions.DataInvalid

The plaintext input data to a cryptographic operation is invalid.

exception pkcs11.exceptions.DataLenRange

The plaintext input data to a cryptographic operation has a bad length. Depending on the operation’s mechanism, this could mean that the plaintext data is too short, too long, or is not a multiple of some particular block size.

exception pkcs11.exceptions.DomainParamsInvalid

Invalid or unsupported domain parameters were supplied to the function. Which representation methods of domain parameters are supported by a given mechanism can vary from token to token.

exception pkcs11.exceptions.DeviceError
exception pkcs11.exceptions.DeviceMemory

The token does not have sufficient memory to perform the requested function.

exception pkcs11.exceptions.DeviceRemoved

The token was removed from its slot during the execution of the function.

exception pkcs11.exceptions.EncryptedDataInvalid

The encrypted input to a decryption operation has been determined to be invalid ciphertext.

exception pkcs11.exceptions.EncryptedDataLenRange

The ciphertext input to a decryption operation has been determined to be invalid ciphertext solely on the basis of its length. Depending on the operation’s mechanism, this could mean that the ciphertext is too short, too long, or is not a multiple of some particular block size.

exception pkcs11.exceptions.ExceededMaxIterations

An iterative algorithm (for key pair generation, domain parameter generation etc.) failed because we have exceeded the maximum number of iterations.

exception pkcs11.exceptions.FunctionCancelled
exception pkcs11.exceptions.FunctionFailed
exception pkcs11.exceptions.FunctionRejected
exception pkcs11.exceptions.FunctionNotSupported
exception pkcs11.exceptions.KeyHandleInvalid
exception pkcs11.exceptions.KeyIndigestible
exception pkcs11.exceptions.KeyNeeded
exception pkcs11.exceptions.KeyNotNeeded
exception pkcs11.exceptions.KeyNotWrappable
exception pkcs11.exceptions.KeySizeRange
exception pkcs11.exceptions.KeyTypeInconsistent
exception pkcs11.exceptions.KeyUnextractable
exception pkcs11.exceptions.GeneralError

In unusual (and extremely unpleasant!) circumstances, a function can fail with the return value CKR_GENERAL_ERROR. When this happens, the token and/or host computer may be in an inconsistent state, and the goals of the function may have been partially achieved.

exception pkcs11.exceptions.HostMemory

The computer that the Cryptoki library is running on has insufficient memory to perform the requested function.

exception pkcs11.exceptions.MechanismInvalid

Mechanism can not be used with requested operation.

exception pkcs11.exceptions.MechanismParamInvalid
exception pkcs11.exceptions.MultipleObjectsReturned

Multiple objects matched the search parameters.

exception pkcs11.exceptions.MultipleTokensReturned

Multiple tokens matched the search parameters.

exception pkcs11.exceptions.NoSuchKey

No key matching the parameters was found.

exception pkcs11.exceptions.NoSuchToken

No token matching the parameters was found.

exception pkcs11.exceptions.ObjectHandleInvalid
exception pkcs11.exceptions.OperationActive

There is already an active operation (or combination of active operations) which prevents Cryptoki from activating the specified operation. For example, an active object-searching operation would prevent Cryptoki from activating an encryption operation with C_EncryptInit. Or, an active digesting operation and an active encryption operation would prevent Cryptoki from activating a signature operation. Or, on a token which doesn’t support simultaneous dual cryptographic operations in a session (see the description of the CKF_DUAL_CRYPTO_OPERATIONS flag in the CK_TOKEN_INFO structure), an active signature operation would prevent Cryptoki from activating an encryption operation.

exception pkcs11.exceptions.OperationNotInitialized
exception pkcs11.exceptions.PinExpired
exception pkcs11.exceptions.PinIncorrect
exception pkcs11.exceptions.PinInvalid
exception pkcs11.exceptions.PinLenRange

The specified PIN is too long or too short.

exception pkcs11.exceptions.PinLocked
exception pkcs11.exceptions.PinTooWeak
exception pkcs11.exceptions.PublicKeyInvalid
exception pkcs11.exceptions.RandomNoRNG
exception pkcs11.exceptions.RandomSeedNotSupported
exception pkcs11.exceptions.SessionClosed

The session was closed during the execution of the function.

exception pkcs11.exceptions.SessionCount

An attempt to open a session which does not succeed because there are too many existing sessions.

exception pkcs11.exceptions.SessionExists
exception pkcs11.exceptions.SessionHandleInvalid

The session handle was invalid. This is usually caused by using an old session object that is not known to PKCS#11.

exception pkcs11.exceptions.SessionReadOnly

Attempted to write to a read-only session.

exception pkcs11.exceptions.SessionReadOnlyExists
exception pkcs11.exceptions.SessionReadWriteSOExists

If the application calling Token.open() already has a R/W SO session open with the token, then any attempt to open a R/O session with the token fails with this exception.

exception pkcs11.exceptions.SignatureLenRange
exception pkcs11.exceptions.SignatureInvalid
exception pkcs11.exceptions.SlotIDInvalid
exception pkcs11.exceptions.TemplateIncomplete

Required attributes to create the object were missing.

exception pkcs11.exceptions.TemplateInconsistent

Template values (including vendor defaults) are contradictory.

exception pkcs11.exceptions.TokenNotPresent

The token was not present in its slot at the time that the function was invoked.

exception pkcs11.exceptions.TokenNotRecognised
exception pkcs11.exceptions.TokenWriteProtected
exception pkcs11.exceptions.UnwrappingKeyHandleInvalid
exception pkcs11.exceptions.UnwrappingKeySizeRange
exception pkcs11.exceptions.UnwrappingKeyTypeInconsistent
exception pkcs11.exceptions.UserAlreadyLoggedIn
exception pkcs11.exceptions.UserNotLoggedIn
exception pkcs11.exceptions.UserPinNotInitialized
exception pkcs11.exceptions.UserTooManyTypes

An attempt was made to have more distinct users simultaneously logged into the token than the token and/or library permits. For example, if some application has an open SO session, and another application attempts to log the normal user into a session, the attempt may return this error. It is not required to, however. Only if the simultaneous distinct users cannot be supported does C_Login have to return this value. Note that this error code generalizes to true multi-user tokens.

exception pkcs11.exceptions.WrappedKeyInvalid
exception pkcs11.exceptions.WrappedKeyLenRange
exception pkcs11.exceptions.WrappingKeyHandleInvalid
exception pkcs11.exceptions.WrappingKeySizeRange
exception pkcs11.exceptions.WrappingKeyTypeInconsistent

Utilities

General Utilities

pkcs11.util.biginteger(value)

Returns a PKCS#11 biginteger bytestream from a Python integer or similar type (e.g. pyasn1.type.univ.Integer).

Parameters:value (int) – Value
Return type:bytes

RSA Key Utilities

Key handling utilities for RSA keys (PKCS#1).

These utilities depend on pyasn1 and pyasn1_modules.

pkcs11.util.rsa.decode_rsa_private_key(der, capabilities=None)

Decode a RFC2437 (PKCS#1) DER-encoded RSA private key into a dictionary of attributes able to be passed to pkcs11.Session.create_object().

Parameters:
  • der (bytes) – DER-encoded key
  • capabilities (MechanismFlag) – Optional key capabilities
Return type:

dict(Attribute,*)

pkcs11.util.rsa.decode_rsa_public_key(der, capabilities=None)

Decode a RFC2437 (PKCS#1) DER-encoded RSA public key into a dictionary of attributes able to be passed to pkcs11.Session.create_object().

Parameters:
  • der (bytes) – DER-encoded key
  • capabilities (MechanismFlag) – Optional key capabilities
Return type:

dict(Attribute,*)

pkcs11.util.rsa.encode_rsa_public_key(key)

Encode an RSA public key into PKCS#1 DER-encoded format.

Parameters:key (PublicKey) – RSA public key
Return type:bytes

DSA Key Utilities

Key handling utilities for DSA keys, domain parameters and signatures..

These utilities depend on pyasn1 and pyasn1_modules.

pkcs11.util.dsa.decode_dsa_domain_parameters(der)

Decode RFC 3279 DER-encoded Dss-Params.

Parameters:der (bytes) – DER-encoded parameters
Return type:dict(Attribute,*)
pkcs11.util.dsa.encode_dsa_domain_parameters(obj)

Encode RFC 3279 DER-encoded Dss-Params.

Parameters:obj (DomainParameters) – domain parameters
Return type:bytes
pkcs11.util.dsa.encode_dsa_public_key(key)

Encode DSA public key into RFC 3279 DER-encoded format.

Parameters:key (PublicKey) – public key
Return type:bytes
pkcs11.util.dsa.decode_dsa_public_key(der)

Decode a DSA public key from RFC 3279 DER-encoded format.

Returns a biginteger encoded as bytes.

Parameters:der (bytes) – DER-encoded public key
Return type:bytes
pkcs11.util.dsa.encode_dsa_signature(signature)

Encode a signature (generated by pkcs11.SignMixin.sign()) into DER-encoded ASN.1 (Dss_Sig_Value) format.

Parameters:signature (bytes) – signature as bytes
Return type:bytes
pkcs11.util.dsa.decode_dsa_signature(der)

Decode a DER-encoded ASN.1 (Dss_Sig_Value) signature (as generated by OpenSSL/X.509) into PKCS #11 format.

Parameters:der (bytes) – DER-encoded signature
Rtype bytes:

DH Key Utilities

Key handling utilities for Diffie-Hellman keys.

These utilities depend on pyasn1 and pyasn1_modules.

pkcs11.util.dh.decode_x9_42_dh_domain_parameters(der)

Decode RFC3279 (X9.42) DER-encoded Diffie-Hellman domain parameters.

Parameters:der (bytes) – DER-encoded parameters
Return type:dict(Attribute,*)
pkcs11.util.dh.encode_x9_42_dh_domain_parameters(obj)

Encode DH domain parameters into RFC 3279 (X9.42) DER-encoded format.

Calculates the subprime if it isn’t available.

Parameters:obj (DomainParameters) – domain parameters
Return type:bytes
pkcs11.util.dh.encode_dh_public_key(key)

Encode DH public key into RFC 3279 DER-encoded format.

Parameters:key (PublicKey) – public key
Return type:bytes
pkcs11.util.dh.decode_dh_public_key(der)

Decode a DH public key from RFC 3279 DER-encoded format.

Returns a biginteger encoded as bytes.

Parameters:der (bytes) – DER-encoded public key
Return type:bytes

EC Key Utilities

Key handling utilities for EC keys (ANSI X.62/RFC3279), domain parameter and signatures.

These utilities depend on pyasn1 and pyasn1_modules.

pkcs11.util.ec.encode_named_curve_parameters(oid)

Return DER-encoded ANSI X.62 EC parameters for a named curve.

Curve names are given by object identifier and can be found in pyasn1_modules.rfc3279.

Parameters:oid (pyasn1.type.univ.ObjectIdentifier, str or tuple) – Object identifier for a named curve
Return type:bytes
pkcs11.util.ec.decode_ec_public_key(der, encode_ec_point=True)

Decode a DER-encoded EC public key as stored by OpenSSL into a dictionary of attributes able to be passed to pkcs11.Session.create_object().

Note

encode_ec_point

For use as an attribute EC_POINT should be DER-encoded (True).

For key derivation implementations can vary. Since v2.30 the specification says implementations MUST accept a raw EC_POINT for ECDH (False), however not all implementations follow this yet.

Parameters:
  • der (bytes) – DER-encoded key
  • encode_ec_point – See text.
Return type:

dict(Attribute,*)

pkcs11.util.ec.encode_ec_public_key(key)

Encode a DER-encoded EC public key as stored by OpenSSL.

Parameters:key (PublicKey) – RSA public key
Return type:bytes
pkcs11.util.ec.encode_ecdsa_signature(signature)

Encode a signature (generated by pkcs11.SignMixin.sign()) into DER-encoded ASN.1 (ECDSA_Sig_Value) format.

Parameters:signature (bytes) – signature as bytes
Return type:bytes
pkcs11.util.ec.decode_ecdsa_signature(der)

Decode a DER-encoded ASN.1 (ECDSA_Sig_Value) signature (as generated by OpenSSL/X.509) into PKCS #11 format.

Parameters:der (bytes) – DER-encoded signature
Rtype bytes:

X.509 Certificate Utilities

Certificate handling utilities for X.509 (SSL) certificates.

These utilities depend on pyasn1 and pyasn1_modules.

pkcs11.util.x509.decode_x509_public_key(der)

Decode a DER-encoded X.509 certificate’s public key into a set of attributes able to be passed to pkcs11.Session.create_object().

Warning

Does not verify certificate.

Parameters:der (bytes) – DER-encoded certificate
Return type:dict(Attribute,*)
pkcs11.util.x509.decode_x509_certificate(der, extended_set=False)

Decode a DER-encoded X.509 certificate into a dictionary of attributes able to be passed to pkcs11.Session.create_object().

Optionally pass extended_set to include additional attributes: start date, end date and key identifiers.

Warning

Does not verify certificate.

Parameters:
  • der (bytes) – DER-encoded certificate
  • extended_set – decodes more metadata about the certificate
Return type:

dict(Attribute,*)