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:
JWKJWK 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 sessionkey_id (
bytes|None) – Key ID (CKA_ID)key_label (
str|None) – Key label (CKA_LABEL)kid (
str|None) – JWK Key ID to assignuse (
str|None) – Key use (‘sig’ or ‘enc’)key_ops (
list[str] |None) – Allowed key operations
- Return type:
- Returns:
HSMJWK instance backed by the HSM key
- Raises:
HSMKeyNotFoundError – If the key is not found
ValueError – If key type is not supported
- 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)
HSMJWKSet
- class hsmkey.jwk_integration.HSMJWKSet(session)[source]
Bases:
objectJWK 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 IDkey_label (
str|None) – PKCS#11 key labelkid (
str|None) – JWK Key ID to assignuse (
str|None) – Key use (‘sig’ or ‘enc’)key_ops (
list[str] |None) – Allowed key operations
- Return type:
- Returns:
The created HSMJWK
- Raises:
ValueError – If kid is not unique
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 librarytoken_label (
str) – Token labelpin (
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 sessionkey_id (
bytes|None) – Key ID (CKA_ID)key_label (
str|None) – Key label (CKA_LABEL)kid (
str|None) – JWK Key ID to assignuse (
str|None) – Key use (‘sig’ or ‘enc’)key_ops (
list[str] |None) – Allowed key operations
- Return type:
- 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:
objectThread-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:
HSMPinError – If PIN authentication fails
HSMSessionError – If session cannot be opened
- 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 sessionkey_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 sessionkey_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:
objectMixin 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,RSAPrivateKeyRSA 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.
- sign(data, padding_instance, algorithm)[source]
Sign data using this key.
- Parameters:
data (
bytes) – Data to signpadding_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 decryptpadding_instance (
AsymmetricPadding) – Padding scheme (PKCS1v15 or OAEP)
- Return type:
bytes- Returns:
Decrypted plaintext
- Raises:
HSMOperationError – If decryption fails
ValueError – If unsupported padding
- class hsmkey.keys.rsa.PKCS11RSAPublicKey(modulus, public_exponent, key_size)[source]
Bases:
RSAPublicKeyRSA 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 sessionpkcs11_key – PKCS#11 public key object
key_id (
bytes|None) – Key IDkey_label (
str|None) – Key label
- Return type:
- 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)
- verify(signature, data, padding_instance, algorithm)[source]
Verify a signature.
- Parameters:
signature (
bytes) – Signature to verifydata (
bytes) – Original datapadding_instance (
AsymmetricPadding) – Padding schemealgorithm (
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 encryptpadding_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 signaturepadding_instance (
AsymmetricPadding) – Padding schemealgorithm (
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,EllipticCurvePrivateKeyElliptic 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.
- sign(data, signature_algorithm)[source]
Sign data using ECDSA.
- Parameters:
data (
bytes) – Data to signsignature_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 algorithmpeer_public_key (
EllipticCurvePublicKey) – Peer’s public key
- Return type:
bytes- Returns:
Shared secret
- Raises:
HSMOperationError – If key exchange fails
- class hsmkey.keys.ec.PKCS11EllipticCurvePublicKey(curve, x, y)[source]
Bases:
EllipticCurvePublicKeyElliptic 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 sessionpkcs11_key – PKCS#11 public key object
key_id (
bytes|None) – Key IDkey_label (
str|None) – Key label
- Return type:
- Returns:
PKCS11EllipticCurvePublicKey instance
- property curve: EllipticCurve
Return the curve.
- 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)
Ed25519 Keys
- class hsmkey.keys.ed25519.PKCS11Ed25519PrivateKey(session, key_id=None, key_label=None)[source]
Bases:
PKCS11PrivateKeyMixin,Ed25519PrivateKeyEd25519 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)
- 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.keys.ed25519.PKCS11Ed25519PublicKey(public_key_bytes)[source]
Bases:
Ed25519PublicKeyEd25519 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 sessionpkcs11_key – PKCS#11 public key object
key_id (
bytes|None) – Key IDkey_label (
str|None) – Key label
- Return type:
- Returns:
PKCS11Ed25519PublicKey instance
Ed448 Keys
- class hsmkey.keys.ed448.PKCS11Ed448PrivateKey(session, key_id=None, key_label=None)[source]
Bases:
PKCS11PrivateKeyMixin,Ed448PrivateKeyEd448 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)
- 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.keys.ed448.PKCS11Ed448PublicKey(public_key_bytes)[source]
Bases:
Ed448PublicKeyEd448 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 sessionpkcs11_key – PKCS#11 public key object
key_id (
bytes|None) – Key IDkey_label (
str|None) – Key label
- Return type:
- Returns:
PKCS11Ed448PublicKey instance
Exceptions
Custom exceptions for hsmkey module.
- exception hsmkey.exceptions.HSMError[source]
Bases:
ExceptionBase exception for all HSM-related errors.
- exception hsmkey.exceptions.HSMSessionError[source]
Bases:
HSMErrorError related to HSM session management.
- exception hsmkey.exceptions.HSMKeyNotFoundError[source]
Bases:
HSMErrorRequested key was not found in the HSM.
- exception hsmkey.exceptions.HSMOperationError[source]
Bases:
HSMErrorCryptographic operation failed on 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.
- 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 sessionkey_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 sessionkey_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:
HSMPinError – If PIN authentication fails
HSMSessionError – If session cannot be opened
- 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 decryptpadding_instance (
AsymmetricPadding) – Padding scheme (PKCS1v15 or OAEP)
- Return type:
bytes- Returns:
Decrypted plaintext
- Raises:
HSMOperationError – If decryption fails
ValueError – If unsupported padding
- 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)
- sign(data, padding_instance, algorithm)[source]
Sign data using this key.
- Parameters:
data (
bytes) – Data to signpadding_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 encryptpadding_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 sessionpkcs11_key – PKCS#11 public key object
key_id (
bytes|None) – Key IDkey_label (
str|None) – Key label
- Return type:
- 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)
- recover_data_from_signature(signature, padding_instance, algorithm)[source]
Recover data from a signature (signature recovery).
- Parameters:
signature (
bytes) – The signaturepadding_instance (
AsymmetricPadding) – Padding schemealgorithm (
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 verifydata (
bytes) – Original datapadding_instance (
AsymmetricPadding) – Padding schemealgorithm (
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 algorithmpeer_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)
- sign(data, signature_algorithm)[source]
Sign data using ECDSA.
- Parameters:
data (
bytes) – Data to signsignature_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 sessionpkcs11_key – PKCS#11 public key object
key_id (
bytes|None) – Key IDkey_label (
str|None) – Key label
- Return type:
- 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)
- 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)
- 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 sessionpkcs11_key – PKCS#11 public key object
key_id (
bytes|None) – Key IDkey_label (
str|None) – Key label
- Return type:
- Returns:
PKCS11Ed25519PublicKey instance
- 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)
- 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 sessionpkcs11_key – PKCS#11 public key object
key_id (
bytes|None) – Key IDkey_label (
str|None) – Key label
- Return type:
- Returns:
PKCS11Ed448PublicKey instance
- 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 sessionkey_id (
bytes|None) – Key ID (CKA_ID)key_label (
str|None) – Key label (CKA_LABEL)kid (
str|None) – JWK Key ID to assignuse (
str|None) – Key use (‘sig’ or ‘enc’)key_ops (
list[str] |None) – Allowed key operations
- Return type:
- Returns:
HSMJWK instance backed by the HSM key
- Raises:
HSMKeyNotFoundError – If the key is not found
ValueError – If key type is not supported
- 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)
- 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 IDkey_label (
str|None) – PKCS#11 key labelkid (
str|None) – JWK Key ID to assignuse (
str|None) – Key use (‘sig’ or ‘enc’)key_ops (
list[str] |None) – Allowed key operations
- Return type:
- Returns:
The created HSMJWK
- Raises:
ValueError – If kid is not unique
- 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 sessionkey_id (
bytes|None) – Key ID (CKA_ID)key_label (
str|None) – Key label (CKA_LABEL)kid (
str|None) – JWK Key ID to assignuse (
str|None) – Key use (‘sig’ or ‘enc’)key_ops (
list[str] |None) – Allowed key operations
- Return type:
- 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 librarytoken_label (
str) – Token labelpin (
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”)