API Reference

This section provides detailed API documentation for all hsmkey modules.

JWCrypto Integration

HSMJWK

class hsmkey.jwk_integration.HSMJWK(session=None, key_id=None, key_label=None, **kwargs)[source]

Bases: JWK

JWK backed by HSM keys.

This class extends jwcrypto’s JWK to support HSM-backed keys. All cryptographic operations (signing, decryption) are performed on the HSM, while public key parameters are extracted for JWK representation.

The private key material never leaves the HSM.

Parameters:
  • session (Session | None)

  • key_id (bytes | None)

  • key_label (str | None)

  • kwargs (Any)

_hsm_private_key

The HSM private key object

_hsm_public_key

The HSM public key object

_session

The PKCS#11 session

_key_id

PKCS#11 key ID

_key_label

PKCS#11 key label

classmethod from_hsm(session, key_id=None, key_label=None, kid=None, use=None, key_ops=None)[source]

Create a JWK from an HSM key.

This factory method loads a key from the HSM and creates a JWK representation with the public key parameters.

Parameters:
  • session (Session) – PKCS#11 session

  • key_id (bytes | None) – Key ID (CKA_ID)

  • key_label (str | None) – Key label (CKA_LABEL)

  • kid (str | None) – JWK Key ID to assign

  • use (str | None) – Key use (‘sig’ or ‘enc’)

  • key_ops (list[str] | None) – Allowed key operations

Return type:

HSMJWK

Returns:

HSMJWK instance backed by the HSM key

Raises:
get_op_key(operation=None, arg=None)[source]

Return the key object for the specified operation.

This method is called by jwcrypto’s JWS and JWE implementations to get the actual key for cryptographic operations.

For HSM keys: - Sign, decrypt, unwrapKey: Returns HSM private key - Verify, encrypt, wrapKey: Returns HSM public key

Parameters:
  • operation (str | None) – The operation to perform (‘sign’, ‘verify’, etc.)

  • arg (Any) – Optional argument (algorithm, etc.)

Return type:

Any

Returns:

HSM key object (compatible with cryptography library interfaces)

has_private()[source]

Check if this JWK has a private key.

For HSM keys, the private key exists on the HSM but cannot be exported.

Return type:

bool

Returns:

True (HSM keys always have private key)

export_private(as_dict=False)[source]

Export private key.

For HSM keys, this raises an error since private keys cannot leave the HSM.

Raises:

HSMSessionError – Always raised for HSM keys

Return type:

dict | str

Parameters:

as_dict (bool)

export_public(as_dict=False)[source]

Export public key.

Returns the public key parameters in JWK format.

Parameters:

as_dict (bool) – If True, return as dictionary; otherwise return JSON string

Return type:

dict | str

Returns:

Public key in JWK format

HSMJWKSet

class hsmkey.jwk_integration.HSMJWKSet(session)[source]

Bases: object

JWK Set backed by HSM keys.

Manages a collection of HSM-backed JWKs for use with jwcrypto.

Parameters:

session (Session)

add_key(key_id=None, key_label=None, kid=None, use=None, key_ops=None)[source]

Add an HSM key to the set.

Parameters:
  • key_id (bytes | None) – PKCS#11 key ID

  • key_label (str | None) – PKCS#11 key label

  • kid (str | None) – JWK Key ID to assign

  • use (str | None) – Key use (‘sig’ or ‘enc’)

  • key_ops (list[str] | None) – Allowed key operations

Return type:

HSMJWK

Returns:

The created HSMJWK

Raises:

ValueError – If kid is not unique

get_key(kid)[source]

Get key by Key ID.

Parameters:

kid (str) – JWK Key ID

Return type:

HSMJWK | None

Returns:

HSMJWK if found, None otherwise

hsm_session

hsmkey.jwk_integration.hsm_session(module_path, token_label, pin)[source]

Context manager for HSM session.

Convenience function for managing HSM sessions.

Parameters:
  • module_path (str) – Path to PKCS#11 library

  • token_label (str) – Token label

  • pin (str) – User PIN

Yields:

PKCS#11 session

Return type:

Iterator[Session]

Example

with hsm_session(“/usr/lib/softhsm/libsofthsm2.so”, “my-token”, “1234”) as session:

key = jwk_from_hsm(session, key_label=”my-key”)

jwk_from_hsm

hsmkey.jwk_integration.jwk_from_hsm(session, key_id=None, key_label=None, kid=None, use=None, key_ops=None)[source]

Create a JWK from an HSM key.

Convenience function that wraps HSMJWK.from_hsm().

Parameters:
  • session (Session) – PKCS#11 session

  • key_id (bytes | None) – Key ID (CKA_ID)

  • key_label (str | None) – Key label (CKA_LABEL)

  • kid (str | None) – JWK Key ID to assign

  • use (str | None) – Key use (‘sig’ or ‘enc’)

  • key_ops (list[str] | None) – Allowed key operations

Return type:

HSMJWK

Returns:

HSMJWK instance backed by the HSM key

Example

with pool.session() as session:

key = jwk_from_hsm(session, key_label=”rsa-2048”)

Session Management

SessionPool

class hsmkey.session.SessionPool(module_path, token_label, user_pin=None, so_pin=None)[source]

Bases: object

Thread-safe pool for PKCS#11 sessions.

This class manages PKCS#11 library instances and sessions, providing thread-safe access with reference counting.

Parameters:
  • module_path (str)

  • token_label (str)

  • user_pin (str | None)

  • so_pin (str | None)

open_session(rw=False)[source]

Open a new PKCS#11 session.

Parameters:

rw (bool) – Whether to open read-write session

Return type:

Session

Returns:

PKCS#11 session

Raises:
session(rw=False)[source]

Context manager for PKCS#11 session.

Parameters:

rw (bool) – Whether to open read-write session

Yields:

PKCS#11 session

Return type:

Iterator[Session]

Example

with pool.session() as session:

key = session.get_key(…)

get_private_key(session, key_type, key_id=None, key_label=None)[source]

Get private key from HSM.

Parameters:
  • session (Session) – PKCS#11 session

  • key_type (KeyType) – Type of key (RSA, EC, EC_EDWARDS)

  • key_id (bytes | None) – Key ID (CKA_ID)

  • key_label (str | None) – Key label (CKA_LABEL)

Return type:

PrivateKey

Returns:

PKCS#11 private key object

Raises:

HSMKeyNotFoundError – If key not found

get_public_key(session, key_type, key_id=None, key_label=None)[source]

Get public key from HSM.

Parameters:
  • session (Session) – PKCS#11 session

  • key_type (KeyType) – Type of key (RSA, EC, EC_EDWARDS)

  • key_id (bytes | None) – Key ID (CKA_ID)

  • key_label (str | None) – Key label (CKA_LABEL)

Return type:

PublicKey

Returns:

PKCS#11 public key object

Raises:

HSMKeyNotFoundError – If key not found

Keys

PKCS11PrivateKeyMixin

class hsmkey.keys.base.PKCS11PrivateKeyMixin(session, key_id=None, key_label=None)[source]

Bases: object

Mixin class for PKCS#11-backed private keys.

This mixin provides common functionality for all HSM-backed private keys, including lazy loading of PKCS#11 key objects and session management.

Parameters:
  • session (Session)

  • key_id (bytes | None)

  • key_label (str | None)

property pkcs11_private_key: PrivateKey

Get PKCS#11 private key object (lazy-loaded).

property pkcs11_public_key: PublicKey

Get PKCS#11 public key object (lazy-loaded).

RSA Keys

class hsmkey.keys.rsa.PKCS11RSAPrivateKey(session, key_id=None, key_label=None)[source]

Bases: PKCS11PrivateKeyMixin, RSAPrivateKey

RSA private key backed by HSM.

This class implements the cryptography library’s RSAPrivateKey interface while performing all cryptographic operations on the HSM.

Parameters:
  • session (Session)

  • key_id (bytes | None)

  • key_label (str | None)

property key_size: int

Return key size in bits.

public_key()[source]

Return the public key corresponding to this private key.

Return type:

PKCS11RSAPublicKey

sign(data, padding_instance, algorithm)[source]

Sign data using this key.

Parameters:
  • data (bytes) – Data to sign

  • padding_instance (AsymmetricPadding) – Padding scheme (PKCS1v15 or PSS)

  • algorithm (HashAlgorithm | Prehashed) – Hash algorithm or Prehashed instance

Return type:

bytes

Returns:

Signature bytes

Raises:
  • HSMOperationError – If signing fails

  • ValueError – If unsupported padding or algorithm

decrypt(ciphertext, padding_instance)[source]

Decrypt data using this key.

Parameters:
  • ciphertext (bytes) – Data to decrypt

  • padding_instance (AsymmetricPadding) – Padding scheme (PKCS1v15 or OAEP)

Return type:

bytes

Returns:

Decrypted plaintext

Raises:
private_numbers()[source]

Not supported for HSM keys.

Return type:

RSAPrivateNumbers

private_bytes(encoding, format, encryption_algorithm)[source]

Not supported for HSM keys.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PrivateFormat)

  • encryption_algorithm (KeySerializationEncryption)

private_bytes_raw()[source]

Not supported for HSM keys.

Return type:

bytes

class hsmkey.keys.rsa.PKCS11RSAPublicKey(modulus, public_exponent, key_size)[source]

Bases: RSAPublicKey

RSA public key from HSM.

This class wraps the public key data extracted from HSM and provides the standard cryptography library interface.

Parameters:
  • modulus (int)

  • public_exponent (int)

  • key_size (int)

classmethod from_pkcs11_key(session, pkcs11_key, key_id=None, key_label=None)[source]

Create public key from PKCS#11 public key object.

Parameters:
  • session (Session) – PKCS#11 session

  • pkcs11_key – PKCS#11 public key object

  • key_id (bytes | None) – Key ID

  • key_label (str | None) – Key label

Return type:

PKCS11RSAPublicKey

Returns:

PKCS11RSAPublicKey instance

property key_size: int

Return key size in bits.

public_numbers()[source]

Return RSA public numbers.

Return type:

RSAPublicNumbers

public_bytes(encoding, format)[source]

Serialize public key.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PublicFormat)

public_bytes_raw()[source]

Not applicable for RSA keys.

Return type:

bytes

verify(signature, data, padding_instance, algorithm)[source]

Verify a signature.

Parameters:
  • signature (bytes) – Signature to verify

  • data (bytes) – Original data

  • padding_instance (AsymmetricPadding) – Padding scheme

  • algorithm (HashAlgorithm | Prehashed) – Hash algorithm

Raises:

InvalidSignature – If verification fails

Return type:

None

encrypt(plaintext, padding_instance)[source]

Encrypt data using this public key.

Parameters:
  • plaintext (bytes) – Data to encrypt

  • padding_instance (AsymmetricPadding) – Padding scheme

Return type:

bytes

Returns:

Ciphertext

recover_data_from_signature(signature, padding_instance, algorithm)[source]

Recover data from a signature (signature recovery).

Parameters:
  • signature (bytes) – The signature

  • padding_instance (AsymmetricPadding) – Padding scheme

  • algorithm (HashAlgorithm | None) – Hash algorithm (or None for no hashing)

Return type:

bytes

Returns:

Recovered data

Elliptic Curve Keys

class hsmkey.keys.ec.PKCS11EllipticCurvePrivateKey(session, key_id=None, key_label=None)[source]

Bases: PKCS11PrivateKeyMixin, EllipticCurvePrivateKey

Elliptic Curve private key backed by HSM.

This class implements the cryptography library’s EllipticCurvePrivateKey interface while performing all cryptographic operations on the HSM.

Parameters:
  • session (Session)

  • key_id (bytes | None)

  • key_label (str | None)

property curve: EllipticCurve

Return the curve used by this key.

property key_size: int

Return key size in bits.

public_key()[source]

Return the public key corresponding to this private key.

Return type:

PKCS11EllipticCurvePublicKey

sign(data, signature_algorithm)[source]

Sign data using ECDSA.

Parameters:
  • data (bytes) – Data to sign

  • signature_algorithm (EllipticCurveSignatureAlgorithm) – Signature algorithm (ECDSA with hash)

Return type:

bytes

Returns:

DER-encoded signature

Raises:

HSMOperationError – If signing fails

exchange(algorithm, peer_public_key)[source]

Perform ECDH key exchange.

Parameters:
  • algorithm (ECDH) – ECDH algorithm

  • peer_public_key (EllipticCurvePublicKey) – Peer’s public key

Return type:

bytes

Returns:

Shared secret

Raises:

HSMOperationError – If key exchange fails

private_numbers()[source]

Not supported for HSM keys.

Return type:

EllipticCurvePrivateNumbers

private_bytes(encoding, format, encryption_algorithm)[source]

Not supported for HSM keys.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PrivateFormat)

  • encryption_algorithm (KeySerializationEncryption)

private_bytes_raw()[source]

Not supported for HSM keys.

Return type:

bytes

class hsmkey.keys.ec.PKCS11EllipticCurvePublicKey(curve, x, y)[source]

Bases: EllipticCurvePublicKey

Elliptic Curve public key from HSM.

This class wraps the public key data extracted from HSM and provides the standard cryptography library interface.

Parameters:
  • curve (ec.EllipticCurve)

  • x (int)

  • y (int)

classmethod from_pkcs11_key(session, pkcs11_key, key_id=None, key_label=None)[source]

Create public key from PKCS#11 public key object.

Parameters:
  • session (Session) – PKCS#11 session

  • pkcs11_key – PKCS#11 public key object

  • key_id (bytes | None) – Key ID

  • key_label (str | None) – Key label

Return type:

PKCS11EllipticCurvePublicKey

Returns:

PKCS11EllipticCurvePublicKey instance

property curve: EllipticCurve

Return the curve.

property key_size: int

Return key size in bits.

public_numbers()[source]

Return EC public numbers.

Return type:

EllipticCurvePublicNumbers

public_bytes(encoding, format)[source]

Serialize public key.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PublicFormat)

public_bytes_raw()[source]

Return raw public key bytes (uncompressed point without 0x04 prefix).

Return type:

bytes

verify(signature, data, signature_algorithm)[source]

Verify a signature.

Parameters:
  • signature (bytes) – DER-encoded signature

  • data (bytes) – Original data

  • signature_algorithm (EllipticCurveSignatureAlgorithm) – Signature algorithm

Raises:

InvalidSignature – If verification fails

Return type:

None

Ed25519 Keys

class hsmkey.keys.ed25519.PKCS11Ed25519PrivateKey(session, key_id=None, key_label=None)[source]

Bases: PKCS11PrivateKeyMixin, Ed25519PrivateKey

Ed25519 private key backed by HSM.

This class implements the cryptography library’s Ed25519PrivateKey interface while performing all cryptographic operations on the HSM.

Parameters:
  • session (Session)

  • key_id (bytes | None)

  • key_label (str | None)

public_key()[source]

Return the public key corresponding to this private key.

Return type:

PKCS11Ed25519PublicKey

sign(data)[source]

Sign data using Ed25519.

Ed25519 does not require pre-hashing; the algorithm handles hashing internally.

Parameters:

data (bytes) – Data to sign

Return type:

bytes

Returns:

64-byte signature

Raises:

HSMOperationError – If signing fails

private_bytes(encoding, format, encryption_algorithm)[source]

Not supported for HSM keys.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PrivateFormat)

  • encryption_algorithm (KeySerializationEncryption)

private_bytes_raw()[source]

Not supported for HSM keys.

Return type:

bytes

class hsmkey.keys.ed25519.PKCS11Ed25519PublicKey(public_key_bytes)[source]

Bases: Ed25519PublicKey

Ed25519 public key from HSM.

This class wraps the public key data extracted from HSM and provides the standard cryptography library interface.

Parameters:

public_key_bytes (bytes)

classmethod from_pkcs11_key(session, pkcs11_key, key_id=None, key_label=None)[source]

Create public key from PKCS#11 public key object.

Parameters:
  • session (Session) – PKCS#11 session

  • pkcs11_key – PKCS#11 public key object

  • key_id (bytes | None) – Key ID

  • key_label (str | None) – Key label

Return type:

PKCS11Ed25519PublicKey

Returns:

PKCS11Ed25519PublicKey instance

public_bytes(encoding, format)[source]

Serialize public key.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PublicFormat)

public_bytes_raw()[source]

Return raw 32-byte public key.

Return type:

bytes

verify(signature, data)[source]

Verify a signature.

Parameters:
  • signature (bytes) – 64-byte signature

  • data (bytes) – Original data

Raises:

InvalidSignature – If verification fails

Return type:

None

Ed448 Keys

class hsmkey.keys.ed448.PKCS11Ed448PrivateKey(session, key_id=None, key_label=None)[source]

Bases: PKCS11PrivateKeyMixin, Ed448PrivateKey

Ed448 private key backed by HSM.

This class implements the cryptography library’s Ed448PrivateKey interface while performing all cryptographic operations on the HSM.

Parameters:
  • session (Session)

  • key_id (bytes | None)

  • key_label (str | None)

public_key()[source]

Return the public key corresponding to this private key.

Return type:

PKCS11Ed448PublicKey

sign(data)[source]

Sign data using Ed448.

Ed448 does not require pre-hashing; the algorithm handles hashing internally.

Parameters:

data (bytes) – Data to sign

Return type:

bytes

Returns:

114-byte signature

Raises:

HSMOperationError – If signing fails

private_bytes(encoding, format, encryption_algorithm)[source]

Not supported for HSM keys.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PrivateFormat)

  • encryption_algorithm (KeySerializationEncryption)

private_bytes_raw()[source]

Not supported for HSM keys.

Return type:

bytes

class hsmkey.keys.ed448.PKCS11Ed448PublicKey(public_key_bytes)[source]

Bases: Ed448PublicKey

Ed448 public key from HSM.

This class wraps the public key data extracted from HSM and provides the standard cryptography library interface.

Parameters:

public_key_bytes (bytes)

classmethod from_pkcs11_key(session, pkcs11_key, key_id=None, key_label=None)[source]

Create public key from PKCS#11 public key object.

Parameters:
  • session (Session) – PKCS#11 session

  • pkcs11_key – PKCS#11 public key object

  • key_id (bytes | None) – Key ID

  • key_label (str | None) – Key label

Return type:

PKCS11Ed448PublicKey

Returns:

PKCS11Ed448PublicKey instance

public_bytes(encoding, format)[source]

Serialize public key.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PublicFormat)

public_bytes_raw()[source]

Return raw 57-byte public key.

Return type:

bytes

verify(signature, data)[source]

Verify a signature.

Parameters:
  • signature (bytes) – 114-byte signature

  • data (bytes) – Original data

Raises:

InvalidSignature – If verification fails

Return type:

None

Exceptions

Custom exceptions for hsmkey module.

exception hsmkey.exceptions.HSMError[source]

Bases: Exception

Base exception for all HSM-related errors.

exception hsmkey.exceptions.HSMSessionError[source]

Bases: HSMError

Error related to HSM session management.

exception hsmkey.exceptions.HSMKeyNotFoundError[source]

Bases: HSMError

Requested key was not found in the HSM.

exception hsmkey.exceptions.HSMPinError[source]

Bases: HSMError

PIN authentication failed.

exception hsmkey.exceptions.HSMOperationError[source]

Bases: HSMError

Cryptographic operation failed on HSM.

exception hsmkey.exceptions.HSMUnsupportedError[source]

Bases: HSMError

Operation is not supported for HSM-backed keys.

exception hsmkey.exceptions.HSMConfigError[source]

Bases: HSMError

Configuration error for HSM.

Module Contents

hsmkey

HSMKey - HSM-backed cryptographic keys for Python.

This module provides cryptography-compatible key implementations that perform all cryptographic operations on a Hardware Security Module (HSM) via PKCS#11.

Example usage:

from hsmkey import SessionPool from hsmkey.keys import PKCS11RSAPrivateKey

# Create session pool pool = SessionPool(

module_path=”/usr/lib/softhsm/libsofthsm2.so”, token_label=”my-token”, user_pin=”123456”,

)

# Use session to access keys with pool.session() as session:

key = PKCS11RSAPrivateKey(session, key_label=”my-rsa-key”) signature = key.sign(b”data”, padding.PKCS1v15(), hashes.SHA256())

class hsmkey.HSMConfig(module_path, token_label, user_pin=None, so_pin=None)[source]

Configuration for HSM connection.

Parameters:
  • module_path (str)

  • token_label (str)

  • user_pin (str | None)

  • so_pin (str | None)

module_path

Path to PKCS#11 library

token_label

Label of the token to use

user_pin

User PIN for authentication

so_pin

Security Officer PIN (optional, for admin operations)

so_pin: str | None = None
user_pin: str | None = None
module_path: str
token_label: str
hsmkey.find_softhsm_module()[source]

Find SoftHSM2 module path.

Return type:

str | None

Returns:

Path to SoftHSM2 library if found, None otherwise.

hsmkey.get_softhsm_conf()[source]

Get SoftHSM2 configuration file path.

Return type:

str | None

Returns:

Path from SOFTHSM2_CONF environment variable or None.

exception hsmkey.HSMError[source]

Base exception for all HSM-related errors.

exception hsmkey.HSMSessionError[source]

Error related to HSM session management.

exception hsmkey.HSMKeyNotFoundError[source]

Requested key was not found in the HSM.

exception hsmkey.HSMPinError[source]

PIN authentication failed.

exception hsmkey.HSMOperationError[source]

Cryptographic operation failed on HSM.

exception hsmkey.HSMUnsupportedError[source]

Operation is not supported for HSM-backed keys.

exception hsmkey.HSMConfigError[source]

Configuration error for HSM.

class hsmkey.SessionPool(module_path, token_label, user_pin=None, so_pin=None)[source]

Thread-safe pool for PKCS#11 sessions.

This class manages PKCS#11 library instances and sessions, providing thread-safe access with reference counting.

Parameters:
  • module_path (str)

  • token_label (str)

  • user_pin (str | None)

  • so_pin (str | None)

get_private_key(session, key_type, key_id=None, key_label=None)[source]

Get private key from HSM.

Parameters:
  • session (Session) – PKCS#11 session

  • key_type (KeyType) – Type of key (RSA, EC, EC_EDWARDS)

  • key_id (bytes | None) – Key ID (CKA_ID)

  • key_label (str | None) – Key label (CKA_LABEL)

Return type:

PrivateKey

Returns:

PKCS#11 private key object

Raises:

HSMKeyNotFoundError – If key not found

get_public_key(session, key_type, key_id=None, key_label=None)[source]

Get public key from HSM.

Parameters:
  • session (Session) – PKCS#11 session

  • key_type (KeyType) – Type of key (RSA, EC, EC_EDWARDS)

  • key_id (bytes | None) – Key ID (CKA_ID)

  • key_label (str | None) – Key label (CKA_LABEL)

Return type:

PublicKey

Returns:

PKCS#11 public key object

Raises:

HSMKeyNotFoundError – If key not found

open_session(rw=False)[source]

Open a new PKCS#11 session.

Parameters:

rw (bool) – Whether to open read-write session

Return type:

Session

Returns:

PKCS#11 session

Raises:
session(rw=False)[source]

Context manager for PKCS#11 session.

Parameters:

rw (bool) – Whether to open read-write session

Yields:

PKCS#11 session

Return type:

Iterator[Session]

Example

with pool.session() as session:

key = session.get_key(…)

class hsmkey.PKCS11RSAPrivateKey(session, key_id=None, key_label=None)[source]

RSA private key backed by HSM.

This class implements the cryptography library’s RSAPrivateKey interface while performing all cryptographic operations on the HSM.

Parameters:
  • session (Session)

  • key_id (bytes | None)

  • key_label (str | None)

decrypt(ciphertext, padding_instance)[source]

Decrypt data using this key.

Parameters:
  • ciphertext (bytes) – Data to decrypt

  • padding_instance (AsymmetricPadding) – Padding scheme (PKCS1v15 or OAEP)

Return type:

bytes

Returns:

Decrypted plaintext

Raises:
property key_size: int

Return key size in bits.

private_bytes(encoding, format, encryption_algorithm)[source]

Not supported for HSM keys.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PrivateFormat)

  • encryption_algorithm (KeySerializationEncryption)

private_bytes_raw()[source]

Not supported for HSM keys.

Return type:

bytes

private_numbers()[source]

Not supported for HSM keys.

Return type:

RSAPrivateNumbers

public_key()[source]

Return the public key corresponding to this private key.

Return type:

PKCS11RSAPublicKey

sign(data, padding_instance, algorithm)[source]

Sign data using this key.

Parameters:
  • data (bytes) – Data to sign

  • padding_instance (AsymmetricPadding) – Padding scheme (PKCS1v15 or PSS)

  • algorithm (HashAlgorithm | Prehashed) – Hash algorithm or Prehashed instance

Return type:

bytes

Returns:

Signature bytes

Raises:
  • HSMOperationError – If signing fails

  • ValueError – If unsupported padding or algorithm

class hsmkey.PKCS11RSAPublicKey(modulus, public_exponent, key_size)[source]

RSA public key from HSM.

This class wraps the public key data extracted from HSM and provides the standard cryptography library interface.

Parameters:
  • modulus (int)

  • public_exponent (int)

  • key_size (int)

encrypt(plaintext, padding_instance)[source]

Encrypt data using this public key.

Parameters:
  • plaintext (bytes) – Data to encrypt

  • padding_instance (AsymmetricPadding) – Padding scheme

Return type:

bytes

Returns:

Ciphertext

classmethod from_pkcs11_key(session, pkcs11_key, key_id=None, key_label=None)[source]

Create public key from PKCS#11 public key object.

Parameters:
  • session (Session) – PKCS#11 session

  • pkcs11_key – PKCS#11 public key object

  • key_id (bytes | None) – Key ID

  • key_label (str | None) – Key label

Return type:

PKCS11RSAPublicKey

Returns:

PKCS11RSAPublicKey instance

property key_size: int

Return key size in bits.

public_bytes(encoding, format)[source]

Serialize public key.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PublicFormat)

public_bytes_raw()[source]

Not applicable for RSA keys.

Return type:

bytes

public_numbers()[source]

Return RSA public numbers.

Return type:

RSAPublicNumbers

recover_data_from_signature(signature, padding_instance, algorithm)[source]

Recover data from a signature (signature recovery).

Parameters:
  • signature (bytes) – The signature

  • padding_instance (AsymmetricPadding) – Padding scheme

  • algorithm (HashAlgorithm | None) – Hash algorithm (or None for no hashing)

Return type:

bytes

Returns:

Recovered data

verify(signature, data, padding_instance, algorithm)[source]

Verify a signature.

Parameters:
  • signature (bytes) – Signature to verify

  • data (bytes) – Original data

  • padding_instance (AsymmetricPadding) – Padding scheme

  • algorithm (HashAlgorithm | Prehashed) – Hash algorithm

Raises:

InvalidSignature – If verification fails

Return type:

None

class hsmkey.PKCS11EllipticCurvePrivateKey(session, key_id=None, key_label=None)[source]

Elliptic Curve private key backed by HSM.

This class implements the cryptography library’s EllipticCurvePrivateKey interface while performing all cryptographic operations on the HSM.

Parameters:
  • session (Session)

  • key_id (bytes | None)

  • key_label (str | None)

property curve: EllipticCurve

Return the curve used by this key.

exchange(algorithm, peer_public_key)[source]

Perform ECDH key exchange.

Parameters:
  • algorithm (ECDH) – ECDH algorithm

  • peer_public_key (EllipticCurvePublicKey) – Peer’s public key

Return type:

bytes

Returns:

Shared secret

Raises:

HSMOperationError – If key exchange fails

property key_size: int

Return key size in bits.

private_bytes(encoding, format, encryption_algorithm)[source]

Not supported for HSM keys.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PrivateFormat)

  • encryption_algorithm (KeySerializationEncryption)

private_bytes_raw()[source]

Not supported for HSM keys.

Return type:

bytes

private_numbers()[source]

Not supported for HSM keys.

Return type:

EllipticCurvePrivateNumbers

public_key()[source]

Return the public key corresponding to this private key.

Return type:

PKCS11EllipticCurvePublicKey

sign(data, signature_algorithm)[source]

Sign data using ECDSA.

Parameters:
  • data (bytes) – Data to sign

  • signature_algorithm (EllipticCurveSignatureAlgorithm) – Signature algorithm (ECDSA with hash)

Return type:

bytes

Returns:

DER-encoded signature

Raises:

HSMOperationError – If signing fails

class hsmkey.PKCS11EllipticCurvePublicKey(curve, x, y)[source]

Elliptic Curve public key from HSM.

This class wraps the public key data extracted from HSM and provides the standard cryptography library interface.

Parameters:
  • curve (ec.EllipticCurve)

  • x (int)

  • y (int)

property curve: EllipticCurve

Return the curve.

classmethod from_pkcs11_key(session, pkcs11_key, key_id=None, key_label=None)[source]

Create public key from PKCS#11 public key object.

Parameters:
  • session (Session) – PKCS#11 session

  • pkcs11_key – PKCS#11 public key object

  • key_id (bytes | None) – Key ID

  • key_label (str | None) – Key label

Return type:

PKCS11EllipticCurvePublicKey

Returns:

PKCS11EllipticCurvePublicKey instance

property key_size: int

Return key size in bits.

public_bytes(encoding, format)[source]

Serialize public key.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PublicFormat)

public_bytes_raw()[source]

Return raw public key bytes (uncompressed point without 0x04 prefix).

Return type:

bytes

public_numbers()[source]

Return EC public numbers.

Return type:

EllipticCurvePublicNumbers

verify(signature, data, signature_algorithm)[source]

Verify a signature.

Parameters:
  • signature (bytes) – DER-encoded signature

  • data (bytes) – Original data

  • signature_algorithm (EllipticCurveSignatureAlgorithm) – Signature algorithm

Raises:

InvalidSignature – If verification fails

Return type:

None

class hsmkey.PKCS11Ed25519PrivateKey(session, key_id=None, key_label=None)[source]

Ed25519 private key backed by HSM.

This class implements the cryptography library’s Ed25519PrivateKey interface while performing all cryptographic operations on the HSM.

Parameters:
  • session (Session)

  • key_id (bytes | None)

  • key_label (str | None)

private_bytes(encoding, format, encryption_algorithm)[source]

Not supported for HSM keys.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PrivateFormat)

  • encryption_algorithm (KeySerializationEncryption)

private_bytes_raw()[source]

Not supported for HSM keys.

Return type:

bytes

public_key()[source]

Return the public key corresponding to this private key.

Return type:

PKCS11Ed25519PublicKey

sign(data)[source]

Sign data using Ed25519.

Ed25519 does not require pre-hashing; the algorithm handles hashing internally.

Parameters:

data (bytes) – Data to sign

Return type:

bytes

Returns:

64-byte signature

Raises:

HSMOperationError – If signing fails

class hsmkey.PKCS11Ed25519PublicKey(public_key_bytes)[source]

Ed25519 public key from HSM.

This class wraps the public key data extracted from HSM and provides the standard cryptography library interface.

Parameters:

public_key_bytes (bytes)

classmethod from_pkcs11_key(session, pkcs11_key, key_id=None, key_label=None)[source]

Create public key from PKCS#11 public key object.

Parameters:
  • session (Session) – PKCS#11 session

  • pkcs11_key – PKCS#11 public key object

  • key_id (bytes | None) – Key ID

  • key_label (str | None) – Key label

Return type:

PKCS11Ed25519PublicKey

Returns:

PKCS11Ed25519PublicKey instance

public_bytes(encoding, format)[source]

Serialize public key.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PublicFormat)

public_bytes_raw()[source]

Return raw 32-byte public key.

Return type:

bytes

verify(signature, data)[source]

Verify a signature.

Parameters:
  • signature (bytes) – 64-byte signature

  • data (bytes) – Original data

Raises:

InvalidSignature – If verification fails

Return type:

None

class hsmkey.PKCS11Ed448PrivateKey(session, key_id=None, key_label=None)[source]

Ed448 private key backed by HSM.

This class implements the cryptography library’s Ed448PrivateKey interface while performing all cryptographic operations on the HSM.

Parameters:
  • session (Session)

  • key_id (bytes | None)

  • key_label (str | None)

private_bytes(encoding, format, encryption_algorithm)[source]

Not supported for HSM keys.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PrivateFormat)

  • encryption_algorithm (KeySerializationEncryption)

private_bytes_raw()[source]

Not supported for HSM keys.

Return type:

bytes

public_key()[source]

Return the public key corresponding to this private key.

Return type:

PKCS11Ed448PublicKey

sign(data)[source]

Sign data using Ed448.

Ed448 does not require pre-hashing; the algorithm handles hashing internally.

Parameters:

data (bytes) – Data to sign

Return type:

bytes

Returns:

114-byte signature

Raises:

HSMOperationError – If signing fails

class hsmkey.PKCS11Ed448PublicKey(public_key_bytes)[source]

Ed448 public key from HSM.

This class wraps the public key data extracted from HSM and provides the standard cryptography library interface.

Parameters:

public_key_bytes (bytes)

classmethod from_pkcs11_key(session, pkcs11_key, key_id=None, key_label=None)[source]

Create public key from PKCS#11 public key object.

Parameters:
  • session (Session) – PKCS#11 session

  • pkcs11_key – PKCS#11 public key object

  • key_id (bytes | None) – Key ID

  • key_label (str | None) – Key label

Return type:

PKCS11Ed448PublicKey

Returns:

PKCS11Ed448PublicKey instance

public_bytes(encoding, format)[source]

Serialize public key.

Return type:

bytes

Parameters:
  • encoding (Encoding)

  • format (PublicFormat)

public_bytes_raw()[source]

Return raw 57-byte public key.

Return type:

bytes

verify(signature, data)[source]

Verify a signature.

Parameters:
  • signature (bytes) – 114-byte signature

  • data (bytes) – Original data

Raises:

InvalidSignature – If verification fails

Return type:

None

class hsmkey.HSMJWK(session=None, key_id=None, key_label=None, **kwargs)[source]

JWK backed by HSM keys.

This class extends jwcrypto’s JWK to support HSM-backed keys. All cryptographic operations (signing, decryption) are performed on the HSM, while public key parameters are extracted for JWK representation.

The private key material never leaves the HSM.

Parameters:
  • session (Session | None)

  • key_id (bytes | None)

  • key_label (str | None)

  • kwargs (Any)

_hsm_private_key

The HSM private key object

_hsm_public_key

The HSM public key object

_session

The PKCS#11 session

_key_id

PKCS#11 key ID

_key_label

PKCS#11 key label

export_private(as_dict=False)[source]

Export private key.

For HSM keys, this raises an error since private keys cannot leave the HSM.

Raises:

HSMSessionError – Always raised for HSM keys

Return type:

dict | str

Parameters:

as_dict (bool)

export_public(as_dict=False)[source]

Export public key.

Returns the public key parameters in JWK format.

Parameters:

as_dict (bool) – If True, return as dictionary; otherwise return JSON string

Return type:

dict | str

Returns:

Public key in JWK format

classmethod from_hsm(session, key_id=None, key_label=None, kid=None, use=None, key_ops=None)[source]

Create a JWK from an HSM key.

This factory method loads a key from the HSM and creates a JWK representation with the public key parameters.

Parameters:
  • session (Session) – PKCS#11 session

  • key_id (bytes | None) – Key ID (CKA_ID)

  • key_label (str | None) – Key label (CKA_LABEL)

  • kid (str | None) – JWK Key ID to assign

  • use (str | None) – Key use (‘sig’ or ‘enc’)

  • key_ops (list[str] | None) – Allowed key operations

Return type:

HSMJWK

Returns:

HSMJWK instance backed by the HSM key

Raises:
get_op_key(operation=None, arg=None)[source]

Return the key object for the specified operation.

This method is called by jwcrypto’s JWS and JWE implementations to get the actual key for cryptographic operations.

For HSM keys: - Sign, decrypt, unwrapKey: Returns HSM private key - Verify, encrypt, wrapKey: Returns HSM public key

Parameters:
  • operation (str | None) – The operation to perform (‘sign’, ‘verify’, etc.)

  • arg (Any) – Optional argument (algorithm, etc.)

Return type:

Any

Returns:

HSM key object (compatible with cryptography library interfaces)

has_private()[source]

Check if this JWK has a private key.

For HSM keys, the private key exists on the HSM but cannot be exported.

Return type:

bool

Returns:

True (HSM keys always have private key)

class hsmkey.HSMJWKSet(session)[source]

JWK Set backed by HSM keys.

Manages a collection of HSM-backed JWKs for use with jwcrypto.

Parameters:

session (Session)

add_key(key_id=None, key_label=None, kid=None, use=None, key_ops=None)[source]

Add an HSM key to the set.

Parameters:
  • key_id (bytes | None) – PKCS#11 key ID

  • key_label (str | None) – PKCS#11 key label

  • kid (str | None) – JWK Key ID to assign

  • use (str | None) – Key use (‘sig’ or ‘enc’)

  • key_ops (list[str] | None) – Allowed key operations

Return type:

HSMJWK

Returns:

The created HSMJWK

Raises:

ValueError – If kid is not unique

get_key(kid)[source]

Get key by Key ID.

Parameters:

kid (str) – JWK Key ID

Return type:

HSMJWK | None

Returns:

HSMJWK if found, None otherwise

hsmkey.jwk_from_hsm(session, key_id=None, key_label=None, kid=None, use=None, key_ops=None)[source]

Create a JWK from an HSM key.

Convenience function that wraps HSMJWK.from_hsm().

Parameters:
  • session (Session) – PKCS#11 session

  • key_id (bytes | None) – Key ID (CKA_ID)

  • key_label (str | None) – Key label (CKA_LABEL)

  • kid (str | None) – JWK Key ID to assign

  • use (str | None) – Key use (‘sig’ or ‘enc’)

  • key_ops (list[str] | None) – Allowed key operations

Return type:

HSMJWK

Returns:

HSMJWK instance backed by the HSM key

Example

with pool.session() as session:

key = jwk_from_hsm(session, key_label=”rsa-2048”)

hsmkey.hsm_session(module_path, token_label, pin)[source]

Context manager for HSM session.

Convenience function for managing HSM sessions.

Parameters:
  • module_path (str) – Path to PKCS#11 library

  • token_label (str) – Token label

  • pin (str) – User PIN

Yields:

PKCS#11 session

Return type:

Iterator[Session]

Example

with hsm_session(“/usr/lib/softhsm/libsofthsm2.so”, “my-token”, “1234”) as session:

key = jwk_from_hsm(session, key_label=”my-key”)