management.pkcs11_util

PKCS#11 Utility Functions.

Classes

Pkcs11Utilities

Utility class for general PKCS#11 operations not specific to private keys.

Pkcs11PrivateKey

Base class for PKCS#11-backed private keys (RSA, EC).

Pkcs11AESKey

PKCS#11 AES symmetric key implementation using python-pkcs11.

Pkcs11RSAPrivateKey

PKCS#11-backed RSA private key implementation.

Pkcs11ECPrivateKey

PKCS#11-backed Elliptic Curve (EC) private key implementation.

Module Contents

class management.pkcs11_util.Pkcs11Utilities(lib_path)[source]

Bases: trustpoint.logger.LoggerMixin

Utility class for general PKCS#11 operations not specific to private keys.

Provides functions for slot/token management, random generation, object destruction, and mechanism listing.

Parameters:

lib_path (str)

_lib[source]
_slots_cache = None[source]
_tokens_cache: list[pkcs11.Token] = [][source]
_raise_value_error(message)[source]
Parameters:

message (str)

Return type:

Never

_raise_runtime_error(message)[source]
Parameters:

message (str)

Return type:

Never

_raise_type_error(message)[source]
Parameters:

message (str)

Return type:

Never

get_slots()[source]

Get all available slots in the PKCS#11 library with caching.

Returns:

List of available slots.

Return type:

List[pkcs11.Slot]

get_tokens()[source]

Get all available tokens in the PKCS#11 library with caching.

Returns:

List of available tokens.

Return type:

List[pkcs11.Token]

get_token_by_label(token_label)[source]

Get a token by its label with optimized lookup.

Parameters:

token_label (str) – Label of the token to find.

Returns:

The found token.

Return type:

pkcs11.Token

Raises:

ValueError – If no token with the specified label is found.

get_slot_id_for_pkcs11_tool_slot(pkcs11_tool_slot)[source]

Convert pkcs11-tool slot number to Python slot ID.

Parameters:

pkcs11_tool_slot (int) – Slot number as used by pkcs11-tool (0, 1, 2, etc.)

Returns:

Actual slot ID for use with Python pkcs11 library.

Return type:

int

Raises:

ValueError – If slot not found.

get_mechanisms(token_label)[source]

Get all mechanisms supported by the specified token.

Parameters:

token_label (str) – Label of the token to check.

Returns:

List of supported mechanisms.

Return type:

List[Mechanism]

open_session(token_label, user_pin)[source]

Open a session with the specified token.

Parameters:
  • token_label (str) – Label of the token to open a session with.

  • user_pin (str) – User PIN for authentication.

Returns:

The opened session.

Return type:

pkcs11.Session

generate_random(token_label, user_pin, length)[source]

Generate cryptographically secure random bytes using the HSM.

Parameters:
  • token_label (str) – Label of the token to use.

  • user_pin (str) – User PIN for the session.

  • length (int) – Number of random bytes to generate.

Returns:

Randomly generated bytes.

Return type:

bytes

seed_random(token_label, user_pin, seed_data)[source]

Seed the HSM’s random number generator with provided entropy.

Parameters:
  • token_label (str) – Label of the token to use.

  • user_pin (str) – User PIN for the session.

  • seed_data (bytes) – Entropy data to seed the RNG.

Return type:

None

destroy_object(token_label, user_pin, label, key_type, object_class)[source]

Destroy a cryptographic object on the token.

Parameters:
  • token_label (str) – Label of the token containing the object.

  • user_pin (str) – User PIN for the session.

  • label (str) – Label of the object to destroy.

  • key_type (KeyType) – Type of the key (RSA, EC, etc.).

  • object_class (ObjectClass) – Class of the object (PRIVATE_KEY, PUBLIC_KEY, etc.).

Raises:

ValueError – If the object doesn’t exist.

Return type:

None

class management.pkcs11_util.Pkcs11PrivateKey(lib_path, token_label, user_pin, key_label, slot_id=None)[source]

Bases: abc.ABC, trustpoint.logger.LoggerMixin

Base class for PKCS#11-backed private keys (RSA, EC).

Parameters:
  • lib_path (str)

  • token_label (str)

  • user_pin (str)

  • key_label (str)

  • slot_id (int | None)

DIGEST_MECHANISMS: ClassVar[dict[type[cryptography.hazmat.primitives.hashes.HashAlgorithm], pkcs11.Mechanism]][source]
_lib_path[source]
_token_label[source]
_user_pin[source]
_key_label[source]
_slot_id = None[source]
_lib = None[source]
_token = None[source]
_session: pkcs11.Session | None = None[source]
_key = None[source]
_raise_value_error(message)[source]
Parameters:

message (str)

Return type:

Never

_raise_type_error(message)[source]
Parameters:

message (str)

Return type:

Never

_raise_runtime_error(message)[source]
Parameters:

message (str)

Return type:

Never

_initialize()[source]

Initialize the PKCS#11 library and create a session.

Return type:

None

copy_key(source_label, target_label, key_type, object_class, template=None)[source]

Copy a cryptographic key with a new label and attributes.

Parameters:
  • source_label (str) – Label of the source key.

  • target_label (str) – Label for the copied key.

  • key_type (KeyType) – Type of the key (RSA, EC, etc.).

  • object_class (ObjectClass) – Class of the object to copy.

  • template (Optional[Dict[Attribute, Any]]) – Optional template for new attributes.

Raises:

ValueError – If source key doesn’t exist.

Return type:

None

destroy_object(label, key_type, object_class)[source]

Destroy a cryptographic object on the token.

Parameters:
  • label (str) – Label of the object to destroy.

  • key_type (KeyType) – Type of the key (RSA, EC, etc.).

  • object_class (ObjectClass) – Class of the object (PRIVATE_KEY, PUBLIC_KEY, etc.).

Raises:

ValueError – If the object doesn’t exist.

Return type:

None

digest_data(data, algorithm)[source]

Perform a cryptographic digest operation on the provided data using the HSM.

Parameters:
  • data (bytes) – Data to be hashed.

  • algorithm (hashes.HashAlgorithm) – Hash algorithm to use.

Returns:

The resulting hash.

Return type:

bytes

Raises:

ValueError – If the algorithm is not supported.

_key_exists(key_type, object_class)[source]

Check if a key with the specified type and object class exists on the token.

Parameters:
  • key_type (KeyType) – The key type (e.g., RSA, EC).

  • object_class (ObjectClass) – The object class (PRIVATE_KEY or PUBLIC_KEY).

Returns:

True if the key exists, False otherwise.

Return type:

bool

abstractmethod sign(data, *args, **kwargs)[source]

Sign the provided data using the private key.

Parameters:
  • data (bytes) – Data to be signed.

  • *args (Any) – Additional positional arguments.

  • **kwargs (Any) – Additional keyword arguments.

Returns:

The signature.

Return type:

bytes

abstractmethod public_key()[source]

Return the public key associated with this private key.

Returns:

The public key object.

Return type:

Union[RSAPublicKey, ec.EllipticCurvePublicKey]

property key_size: int[source]
Abstractmethod:

Return type:

int

Return the key size in bits.

Returns:

The key size.

Return type:

int

destroy_key()[source]

Destroy the current private key and associated public key.

Raises:

ValueError – If the key doesn’t exist.

Return type:

None

close()[source]

Close the session with the token.

Return type:

None

__enter__()[source]

Context manager entry point.

Returns:

The current instance.

Return type:

Pkcs11PrivateKey

__exit__(exc_type, exc_value, traceback)[source]

Context manager exit point, closes the session.

Parameters:
  • exc_type (Optional[Type[BaseException]]) – Exception type if an error occurred.

  • exc_value (Optional[BaseException]]) – Exception instance if an error occurred.

  • traceback (Optional[types.TracebackType]) – Traceback if an error occurred.

Return type:

None

class management.pkcs11_util.Pkcs11AESKey(lib_path, token_label, user_pin, key_label)[source]

PKCS#11 AES symmetric key implementation using python-pkcs11.

Parameters:
  • lib_path (str)

  • token_label (str)

  • user_pin (str)

  • key_label (str)

SUPPORTED_KEY_LENGTHS: ClassVar[list[int]] = [128, 192, 256][source]
_lib_path: str[source]
_token_label: str[source]
_user_pin: str[source]
_key_label: str[source]
_lib: pkcs11.lib | None = None[source]
_slot_id: int | None = None[source]
_token: pkcs11.token | None = None[source]
_session: pkcs11.session | None = None[source]
_key: pkcs11.key | None = None[source]
_key_length: int | None = None[source]
_initialize()[source]

Initialize PKCS#11 library and session (copied from parent logic).

Return type:

None

load_key()[source]

Load an existing AES key from the PKCS#11 token.

Raises:

RuntimeError – If the key cannot be loaded or does not exist.

Return type:

None

generate_key(key_length=256)[source]

Generate an AES key in the PKCS#11 token.

Parameters:

key_length (int) – Length of the AES key in bits (default: 256).

Raises:
  • ValueError – If the key length is not supported.

  • RuntimeError – If key generation fails.

Return type:

None

close()[source]

Close PKCS#11 session.

Return type:

None

__enter__()[source]

Context manager entry.

Return type:

Pkcs11AESKey

__exit__(exc_type, exc_val, exc_tb)[source]

Context manager exit.

Parameters:
  • exc_type (type[BaseException] | None)

  • exc_val (BaseException | None)

  • exc_tb (types.TracebackType | None)

Return type:

None

class management.pkcs11_util.Pkcs11RSAPrivateKey(lib_path, token_label, user_pin, key_label, slot_id=None)[source]

Bases: Pkcs11PrivateKey, cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey

PKCS#11-backed RSA private key implementation.

This class provides methods for generating, importing, and using RSA private keys stored on a PKCS#11 token. It implements the cryptography RSAPrivateKey interface and supports signing, encryption, and key management operations.

Parameters:
  • lib_path (str)

  • token_label (str)

  • user_pin (str)

  • key_label (str)

  • slot_id (int | None)

DEFAULT_PUBLIC_TEMPLATE: ClassVar[dict[pkcs11.Attribute, Any]][source]
DEFAULT_PRIVATE_TEMPLATE: ClassVar[dict[pkcs11.Attribute, Any]][source]
_public_key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey | None = None[source]
load_key()[source]

Load RSA private key from token using the specified label.

Raises:

ValueError – If the RSA private key is not found.

Return type:

None

generate_key(key_length=2048, public_template=None, private_template=None)[source]

Generate RSA key pair and store handles on the token.

Parameters:
  • key_length (int) – Length of the RSA key in bits (default 2048).

  • public_template (Optional[Dict[Attribute, Any]]) – Template for public key attributes.

  • private_template (Optional[Dict[Attribute, Any]]) – Template for private key attributes.

Raises:

ValueError – If a key with the same label already exists.

Return type:

None

_raise(msg, exc_type=Exception)[source]
Parameters:
  • msg (str)

  • exc_type (type[Exception])

Return type:

Never

import_private_key_from_crypto(private_key)[source]

Import an RSA private key from cryptography RSAPrivateKey object into the HSM.

Parameters:

private_key (cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateKey) – The RSA private key object from cryptography library

Returns:

True if import was successful, False otherwise

Return type:

bool

sign(data, padding, algorithm)[source]

Sign the provided data using the RSA private key with PKCS#1 v1.5 padding.

Parameters:
  • data (bytes) – Data to be signed.

  • padding (asym_padding.AsymmetricPadding) – Padding scheme to use (must be PKCS1v15).

  • algorithm (hashes.HashAlgorithm) – Hash algorithm to use for signing.

Returns:

The RSA signature.

Return type:

bytes

Raises:
  • NotImplementedError – If padding is not PKCS1v15.

  • ValueError – If Prehashed digest is used.

public_key()[source]

Return the cached or retrieved RSA public key.

Returns:

The RSA public key.

Return type:

RSAPublicKey

Raises:

ValueError – If the public key is not found or invalid.

property key_size: int[source]

Return the RSA key size in bits.

Returns:

The key size.

Return type:

int

encrypt(plaintext)[source]

Encrypt the given plaintext using the RSA public key with PKCS#1 v1.5 padding.

Parameters:

plaintext (bytes) – Data to be encrypted.

Returns:

The encrypted ciphertext.

Return type:

bytes

Raises:

NoSuchKey – If the public key is not found.

decrypt(ciphertext, padding)[source]

Decrypt the given ciphertext using the RSA private key.

Parameters:
  • ciphertext (bytes) – Data to be decrypted.

  • padding (asym_padding.AsymmetricPadding) – Padding scheme to use (PKCS1v15 or OAEP).

Returns:

The decrypted plaintext.

Return type:

bytes

Raises:

NotImplementedError – If the padding is not supported.

private_numbers()[source]

Not implemented for PKCS#11 private keys.

Raises:

NotImplementedError – Always.

Return type:

cryptography.hazmat.primitives.asymmetric.rsa.RSAPrivateNumbers

private_bytes(encoding, key_format, encryption_algorithm)[source]

Not implemented for PKCS#11 private keys.

Raises:

NotImplementedError – Always.

Parameters:
  • encoding (cryptography.hazmat.primitives.serialization.Encoding)

  • key_format (cryptography.hazmat.primitives.serialization.PrivateFormat)

  • encryption_algorithm (cryptography.hazmat.primitives.serialization.KeySerializationEncryption)

Return type:

bytes

__copy__()[source]

Return the same instance since copying is not supported for PKCS#11 keys.

Returns:

The current instance.

Return type:

Pkcs11RSAPrivateKey

class management.pkcs11_util.Pkcs11ECPrivateKey(lib_path, token_label, user_pin, key_label, slot_id=None)[source]

Bases: Pkcs11PrivateKey, cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey

PKCS#11-backed Elliptic Curve (EC) private key implementation.

This class provides methods for generating, importing, and using EC private keys stored on a PKCS#11 token. It implements the cryptography EllipticCurvePrivateKey interface and supports signing and key management operations.

Parameters:
  • lib_path (str)

  • token_label (str)

  • user_pin (str)

  • key_label (str)

  • slot_id (int | None)

CURVE_KEY_LENGTHS: ClassVar[dict[trustpoint_core.oid.NamedCurve, int]][source]
EC_MECHANISMS: ClassVar[dict[type[cryptography.hazmat.primitives.hashes.HashAlgorithm], pkcs11.Mechanism]][source]
DEFAULT_PUBLIC_TEMPLATE: ClassVar[dict[pkcs11.Attribute, Any]][source]
DEFAULT_PRIVATE_TEMPLATE: ClassVar[dict[pkcs11.Attribute, Any]][source]
_public_key: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicKey | None = None[source]
load_key()[source]

Load EC private key from token using the specified label.

Raises:

ValueError – If the EC private key is not found.

Return type:

None

generate_key(curve=None, public_template=None, private_template=None)[source]

Generate EC key pair and store it on the token.

Parameters:
  • curve (ec.EllipticCurve) – The elliptic curve to use (default SECP256R1).

  • public_template (Optional[Dict[Attribute, Any]]) – Template for public key attributes.

  • private_template (Optional[Dict[Attribute, Any]]) – Template for private key attributes.

Raises:

ValueError – If a key with the same label already exists or unsupported curve.

Return type:

None

sign(data, signature_algorithm)[source]

Sign the provided data using the EC private key with ECDSA.

Parameters:
  • data (bytes) – Data to be signed.

  • signature_algorithm (ec.EllipticCurveSignatureAlgorithm) – The signature algorithm to use for signing.

Returns:

The ECDSA signature.

Return type:

bytes

Raises:
  • ValueError – If unsupported hash algorithm.

  • NotImplementedError – If non-ECDSA algorithm is provided.

public_key()[source]

Return the cached or retrieved EC public key.

Returns:

The EC public key.

Return type:

ec.EllipticCurvePublicKey

Raises:

ValueError – If the public key is not found or invalid.

_get_curve_params(curve)[source]

Get the OID parameters for a given EC curve.

Parameters:

curve (cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve) – The elliptic curve object

Returns:

The curve OID parameters

Return type:

bytes

Raises:

ValueError – If the curve is not supported

_create_ec_key_templates(private_numbers, public_numbers, curve_params)[source]

Create PKCS#11 templates for EC private and public keys.

Parameters:
  • private_numbers (cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateNumbers) – The EC private key numbers

  • public_numbers (cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePublicNumbers) – The EC public key numbers

  • curve_params (bytes) – The curve OID parameters

Returns:

(private_template, public_template)

Return type:

tuple

_create_ec_key_objects(private_template, public_template)[source]

Create EC private and public key objects in the HSM.

Parameters:
  • private_template (dict[pkcs11.Attribute, Any]) – PKCS#11 template for the private key

  • public_template (dict[pkcs11.Attribute, Any]) – PKCS#11 template for the public key

Raises:

ValueError – If key already exists or session not initialized

Return type:

None

import_private_key_from_crypto(private_key)[source]

Import an EC private key from cryptography EllipticCurvePrivateKey object into the HSM.

Parameters:

private_key (cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateKey) – The EC private key object from cryptography library

Returns:

True if import was successful, False otherwise

Return type:

bool

property key_size: int[source]

Return the EC key size in bits.

Returns:

The key size.

Return type:

int

encrypt(plaintext)[source]

Not implemented for EC keys.

Raises:

NotImplementedError – Always.

Parameters:

plaintext (bytes)

Return type:

None

decrypt(ciphertext, padding)[source]

Not implemented for EC keys.

Raises:

NotImplementedError – Always.

Parameters:
  • ciphertext (bytes)

  • padding (cryptography.hazmat.primitives.asymmetric.padding.AsymmetricPadding)

Return type:

None

private_numbers()[source]

Not implemented for PKCS#11 private keys.

Raises:

NotImplementedError – Always.

Return type:

cryptography.hazmat.primitives.asymmetric.ec.EllipticCurvePrivateNumbers

private_bytes(_encoding, _format, _encryption_algorithm)[source]

Not implemented for PKCS#11 private keys.

Raises:

NotImplementedError – Always.

Parameters:
  • _encoding (cryptography.hazmat.primitives.serialization.Encoding)

  • _format (cryptography.hazmat.primitives.serialization.PrivateFormat)

  • _encryption_algorithm (cryptography.hazmat.primitives.serialization.KeySerializationEncryption)

Return type:

bytes

exchange(algorithm, peer_public_key)[source]

Not implemented for EC keys.

Raises:

NotImplementedError – Always.

Parameters:
  • algorithm (Any)

  • peer_public_key (Any)

Return type:

bytes

property curve: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve[source]

Return the elliptic curve used by the private key.

Returns:

The curve object.

Return type:

ec.EllipticCurve

Raises:

ValueError – If the curve parameters cannot be determined or are not supported.

__copy__()[source]

Return the same instance since copying is not supported for PKCS#11 keys.

Returns:

The current instance.

Return type:

Pkcs11ECPrivateKey