management.pkcs11_util ====================== .. py:module:: management.pkcs11_util .. autoapi-nested-parse:: PKCS#11 Utility Functions. Module Contents --------------- .. py:class:: Pkcs11Utilities(lib_path) Bases: :py:obj:`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. .. py:method:: get_slots() Get all available slots in the PKCS#11 library with caching. :returns: List of available slots. :rtype: List[pkcs11.Slot] .. py:method:: get_tokens() Get all available tokens in the PKCS#11 library with caching. :returns: List of available tokens. :rtype: List[pkcs11.Token] .. py:method:: get_token_by_label(token_label) Get a token by its label with optimized lookup. :param token_label: Label of the token to find. :type token_label: str :returns: The found token. :rtype: pkcs11.Token :raises ValueError: If no token with the specified label is found. .. py:method:: get_slot_id_for_pkcs11_tool_slot(pkcs11_tool_slot) Convert pkcs11-tool slot number to Python slot ID. :param pkcs11_tool_slot: Slot number as used by pkcs11-tool (0, 1, 2, etc.) :type pkcs11_tool_slot: int :returns: Actual slot ID for use with Python pkcs11 library. :rtype: int :raises ValueError: If slot not found. .. py:method:: get_mechanisms(token_label) Get all mechanisms supported by the specified token. :param token_label: Label of the token to check. :type token_label: str :returns: List of supported mechanisms. :rtype: List[Mechanism] .. py:method:: open_session(token_label, user_pin) Open a session with the specified token. :param token_label: Label of the token to open a session with. :type token_label: str :param user_pin: User PIN for authentication. :type user_pin: str :returns: The opened session. :rtype: pkcs11.Session .. py:method:: generate_random(token_label, user_pin, length) Generate cryptographically secure random bytes using the HSM. :param token_label: Label of the token to use. :type token_label: str :param user_pin: User PIN for the session. :type user_pin: str :param length: Number of random bytes to generate. :type length: int :returns: Randomly generated bytes. :rtype: bytes .. py:method:: seed_random(token_label, user_pin, seed_data) Seed the HSM's random number generator with provided entropy. :param token_label: Label of the token to use. :type token_label: str :param user_pin: User PIN for the session. :type user_pin: str :param seed_data: Entropy data to seed the RNG. :type seed_data: bytes .. py:method:: destroy_object(token_label, user_pin, label, key_type, object_class) Destroy a cryptographic object on the token. :param token_label: Label of the token containing the object. :type token_label: str :param user_pin: User PIN for the session. :type user_pin: str :param label: Label of the object to destroy. :type label: str :param key_type: Type of the key (RSA, EC, etc.). :type key_type: KeyType :param object_class: Class of the object (PRIVATE_KEY, PUBLIC_KEY, etc.). :type object_class: ObjectClass :raises ValueError: If the object doesn't exist. .. py:class:: Pkcs11PrivateKey(lib_path, token_label, user_pin, key_label, slot_id = None) Bases: :py:obj:`abc.ABC`, :py:obj:`trustpoint.logger.LoggerMixin` Base class for PKCS#11-backed private keys (RSA, EC). .. py:attribute:: DIGEST_MECHANISMS :type: ClassVar[dict[type[cryptography.hazmat.primitives.hashes.HashAlgorithm], pkcs11.Mechanism]] .. py:method:: copy_key(source_label, target_label, key_type, object_class, template = None) Copy a cryptographic key with a new label and attributes. :param source_label: Label of the source key. :type source_label: str :param target_label: Label for the copied key. :type target_label: str :param key_type: Type of the key (RSA, EC, etc.). :type key_type: KeyType :param object_class: Class of the object to copy. :type object_class: ObjectClass :param template: Optional template for new attributes. :type template: Optional[Dict[Attribute, Any]] :raises ValueError: If source key doesn't exist. .. py:method:: destroy_object(label, key_type, object_class) Destroy a cryptographic object on the token. :param label: Label of the object to destroy. :type label: str :param key_type: Type of the key (RSA, EC, etc.). :type key_type: KeyType :param object_class: Class of the object (PRIVATE_KEY, PUBLIC_KEY, etc.). :type object_class: ObjectClass :raises ValueError: If the object doesn't exist. .. py:method:: digest_data(data, algorithm) Perform a cryptographic digest operation on the provided data using the HSM. :param data: Data to be hashed. :type data: bytes :param algorithm: Hash algorithm to use. :type algorithm: hashes.HashAlgorithm :returns: The resulting hash. :rtype: bytes :raises ValueError: If the algorithm is not supported. .. py:method:: sign(data, *args, **kwargs) :abstractmethod: Sign the provided data using the private key. :param data: Data to be signed. :type data: bytes :param \*args: Additional positional arguments. :type \*args: Any :param \*\*kwargs: Additional keyword arguments. :type \*\*kwargs: Any :returns: The signature. :rtype: bytes .. py:method:: public_key() :abstractmethod: Return the public key associated with this private key. :returns: The public key object. :rtype: Union[RSAPublicKey, ec.EllipticCurvePublicKey] .. py:property:: key_size :type: int :abstractmethod: Return the key size in bits. :returns: The key size. :rtype: int .. py:method:: destroy_key() Destroy the current private key and associated public key. :raises ValueError: If the key doesn't exist. .. py:method:: close() Close the session with the token. .. py:class:: Pkcs11AESKey(lib_path, token_label, user_pin, key_label) PKCS#11 AES symmetric key implementation using python-pkcs11. .. py:attribute:: SUPPORTED_KEY_LENGTHS :type: ClassVar[list[int]] :value: [128, 192, 256] .. py:method:: load_key() Load an existing AES key from the PKCS#11 token. :raises RuntimeError: If the key cannot be loaded or does not exist. .. py:method:: generate_key(key_length = 256) Generate an AES key in the PKCS#11 token. :param key_length: Length of the AES key in bits (default: 256). :type key_length: int :raises ValueError: If the key length is not supported. :raises RuntimeError: If key generation fails. .. py:method:: close() Close PKCS#11 session. .. py:class:: Pkcs11RSAPrivateKey(lib_path, token_label, user_pin, key_label, slot_id = None) Bases: :py:obj:`Pkcs11PrivateKey`, :py:obj:`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. .. py:attribute:: DEFAULT_PUBLIC_TEMPLATE :type: ClassVar[dict[pkcs11.Attribute, Any]] .. py:attribute:: DEFAULT_PRIVATE_TEMPLATE :type: ClassVar[dict[pkcs11.Attribute, Any]] .. py:method:: load_key() Load RSA private key from token using the specified label. :raises ValueError: If the RSA private key is not found. .. py:method:: generate_key(key_length = 2048, public_template = None, private_template = None) Generate RSA key pair and store handles on the token. :param key_length: Length of the RSA key in bits (default 2048). :type key_length: int :param public_template: Template for public key attributes. :type public_template: Optional[Dict[Attribute, Any]] :param private_template: Template for private key attributes. :type private_template: Optional[Dict[Attribute, Any]] :raises ValueError: If a key with the same label already exists. .. py:method:: import_private_key_from_crypto(private_key) Import an RSA private key from cryptography RSAPrivateKey object into the HSM. :param private_key: The RSA private key object from cryptography library :returns: True if import was successful, False otherwise :rtype: bool .. py:method:: sign(data, padding, algorithm) Sign the provided data using the RSA private key with PKCS#1 v1.5 padding. :param data: Data to be signed. :type data: bytes :param padding: Padding scheme to use (must be PKCS1v15). :type padding: asym_padding.AsymmetricPadding :param algorithm: Hash algorithm to use for signing. :type algorithm: hashes.HashAlgorithm :returns: The RSA signature. :rtype: bytes :raises NotImplementedError: If padding is not PKCS1v15. :raises ValueError: If Prehashed digest is used. .. py:method:: public_key() Return the cached or retrieved RSA public key. :returns: The RSA public key. :rtype: RSAPublicKey :raises ValueError: If the public key is not found or invalid. .. py:property:: key_size :type: int Return the RSA key size in bits. :returns: The key size. :rtype: int .. py:method:: encrypt(plaintext) Encrypt the given plaintext using the RSA public key with PKCS#1 v1.5 padding. :param plaintext: Data to be encrypted. :type plaintext: bytes :returns: The encrypted ciphertext. :rtype: bytes :raises NoSuchKey: If the public key is not found. .. py:method:: decrypt(ciphertext, padding) Decrypt the given ciphertext using the RSA private key. :param ciphertext: Data to be decrypted. :type ciphertext: bytes :param padding: Padding scheme to use (PKCS1v15 or OAEP). :type padding: asym_padding.AsymmetricPadding :returns: The decrypted plaintext. :rtype: bytes :raises NotImplementedError: If the padding is not supported. .. py:method:: private_numbers() Not implemented for PKCS#11 private keys. :raises NotImplementedError: Always. .. py:method:: private_bytes(encoding, key_format, encryption_algorithm) Not implemented for PKCS#11 private keys. :raises NotImplementedError: Always. .. py:class:: Pkcs11ECPrivateKey(lib_path, token_label, user_pin, key_label, slot_id = None) Bases: :py:obj:`Pkcs11PrivateKey`, :py:obj:`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. .. py:attribute:: CURVE_KEY_LENGTHS :type: ClassVar[dict[trustpoint_core.oid.NamedCurve, int]] .. py:attribute:: EC_MECHANISMS :type: ClassVar[dict[type[cryptography.hazmat.primitives.hashes.HashAlgorithm], pkcs11.Mechanism]] .. py:attribute:: DEFAULT_PUBLIC_TEMPLATE :type: ClassVar[dict[pkcs11.Attribute, Any]] .. py:attribute:: DEFAULT_PRIVATE_TEMPLATE :type: ClassVar[dict[pkcs11.Attribute, Any]] .. py:method:: load_key() Load EC private key from token using the specified label. :raises ValueError: If the EC private key is not found. .. py:method:: generate_key(curve = None, public_template = None, private_template = None) Generate EC key pair and store it on the token. :param curve: The elliptic curve to use (default SECP256R1). :type curve: ec.EllipticCurve :param public_template: Template for public key attributes. :type public_template: Optional[Dict[Attribute, Any]] :param private_template: Template for private key attributes. :type private_template: Optional[Dict[Attribute, Any]] :raises ValueError: If a key with the same label already exists or unsupported curve. .. py:method:: sign(data, signature_algorithm) Sign the provided data using the EC private key with ECDSA. :param data: Data to be signed. :type data: bytes :param signature_algorithm: The signature algorithm to use for signing. :type signature_algorithm: ec.EllipticCurveSignatureAlgorithm :returns: The ECDSA signature. :rtype: bytes :raises ValueError: If unsupported hash algorithm. :raises NotImplementedError: If non-ECDSA algorithm is provided. .. py:method:: public_key() Return the cached or retrieved EC public key. :returns: The EC public key. :rtype: ec.EllipticCurvePublicKey :raises ValueError: If the public key is not found or invalid. .. py:method:: import_private_key_from_crypto(private_key) Import an EC private key from cryptography EllipticCurvePrivateKey object into the HSM. :param private_key: The EC private key object from cryptography library :returns: True if import was successful, False otherwise :rtype: bool .. py:property:: key_size :type: int Return the EC key size in bits. :returns: The key size. :rtype: int .. py:method:: encrypt(plaintext) Not implemented for EC keys. :raises NotImplementedError: Always. .. py:method:: decrypt(ciphertext, padding) Not implemented for EC keys. :raises NotImplementedError: Always. .. py:method:: private_numbers() Not implemented for PKCS#11 private keys. :raises NotImplementedError: Always. .. py:method:: private_bytes(_encoding, _format, _encryption_algorithm) Not implemented for PKCS#11 private keys. :raises NotImplementedError: Always. .. py:method:: exchange(algorithm, peer_public_key) Not implemented for EC keys. :raises NotImplementedError: Always. .. py:property:: curve :type: cryptography.hazmat.primitives.asymmetric.ec.EllipticCurve Return the elliptic curve used by the private key. :returns: The curve object. :rtype: ec.EllipticCurve :raises ValueError: If the curve parameters cannot be determined or are not supported.