keycard package¶
Subpackages¶
- keycard.commands package
- Submodules
- keycard.commands.change_secret module
- keycard.commands.derive_key module
- keycard.commands.ecdh module
- keycard.commands.export_bip85 module
- keycard.commands.export_key module
- keycard.commands.export_lee module
- keycard.commands.factory_reset module
- keycard.commands.generate_key module
- keycard.commands.generate_mnemonic module
- keycard.commands.get_challenge module
- keycard.commands.get_data module
- keycard.commands.get_status module
- keycard.commands.ident module
- keycard.commands.init module
- keycard.commands.load_key module
- keycard.commands.mutually_authenticate module
- keycard.commands.open_secure_channel module
- keycard.commands.pair module
- keycard.commands.remove_key module
- keycard.commands.select module
- keycard.commands.set_pinless_path module
- keycard.commands.sign module
- keycard.commands.store_data module
- keycard.commands.unblock_pin module
- keycard.commands.unpair module
- keycard.commands.verify_pin module
- Module contents
change_secret()derive_key()ecdh()export_bip85()export_key()export_lee()factory_reset()generate_key()generate_mnemonic()get_challenge()get_data()get_status()ident()init()load_key()mutually_authenticate()open_secure_channel()pair()remove_key()select()set_pinless_path()sign()store_data()unblock_pin()unpair()verify_pin()
- keycard.crypto package
- keycard.parsing package
- Submodules
- keycard.parsing.application_info module
ApplicationInfoApplicationInfo.capabilitiesApplicationInfo.ecc_public_keyApplicationInfo.instance_uidApplicationInfo.key_uidApplicationInfo.version_majorApplicationInfo.version_minorApplicationInfo.free_pairing_slotsApplicationInfo.statusApplicationInfo.identity_certificateApplicationInfo.capabilitiesApplicationInfo.ecc_public_keyApplicationInfo.free_pairing_slotsApplicationInfo.identity_certificateApplicationInfo.instance_uidApplicationInfo.is_initializedApplicationInfo.is_lee_modeApplicationInfo.key_uidApplicationInfo.parse()ApplicationInfo.pin_retriesApplicationInfo.statusApplicationInfo.version_majorApplicationInfo.version_minor
- keycard.parsing.capabilities module
- keycard.parsing.certificate module
IdentityCertificateIdentityCertificate.identity_public_keyIdentityCertificate.signatureIdentityCertificate.recovery_idIdentityCertificate.ca_public_keyIdentityCertificate.check_trust()IdentityCertificate.identity_public_keyIdentityCertificate.parse()IdentityCertificate.recovery_idIdentityCertificate.signatureIdentityCertificate.verify()
compress_public_key()
- keycard.parsing.exported_key module
- keycard.parsing.identity module
- keycard.parsing.keypath module
- keycard.parsing.lee_keys module
- keycard.parsing.signature_result module
- keycard.parsing.tlv module
- Module contents
- keycard.secure_channel package
- Submodules
- keycard.secure_channel.base module
- keycard.secure_channel.v1 module
SecureChannelV1SecureChannelV1.enc_keySecureChannelV1.mac_keySecureChannelV1.ivSecureChannelV1.authenticatedSecureChannelV1.previous_ivSecureChannelV1.authenticatedSecureChannelV1.enc_keySecureChannelV1.from_handshake()SecureChannelV1.is_openSecureChannelV1.ivSecureChannelV1.mac_keySecureChannelV1.previous_ivSecureChannelV1.unwrap()SecureChannelV1.unwrap_response()SecureChannelV1.versionSecureChannelV1.wrap()SecureChannelV1.wrap_apdu()
cbc_decrypt()cbc_encrypt()cbc_mac()one_shot_encrypt()
- keycard.secure_channel.v2 module
- Module contents
SecureChannelSecureChannelV1SecureChannelV1.enc_keySecureChannelV1.mac_keySecureChannelV1.ivSecureChannelV1.authenticatedSecureChannelV1.previous_ivSecureChannelV1.authenticatedSecureChannelV1.enc_keySecureChannelV1.from_handshake()SecureChannelV1.is_openSecureChannelV1.ivSecureChannelV1.mac_keySecureChannelV1.previous_ivSecureChannelV1.unwrap()SecureChannelV1.unwrap_response()SecureChannelV1.versionSecureChannelV1.wrap()SecureChannelV1.wrap_apdu()
SecureChannelV2SecureChannelVersionchannel_version()
Submodules¶
keycard.apdu module¶
This module provides classes and functions for handling APDU (Application Protocol Data Unit) responses and encoding data in LV (Length-Value) format.
- class keycard.apdu.APDUResponse(data, status_word)¶
Bases:
objectRepresents a response to an APDU (Application Protocol Data Unit) command.
- data¶
The response data returned from the APDU command.
- Type:
bytes
- status_word¶
The status word indicating the result of the APDU command.
- Type:
int
- data: bytes¶
- status_word: int¶
- keycard.apdu.encode_lv(value)¶
Encodes the given bytes using LV (Length-Value) encoding.
The function prepends the length of the input bytes as a single byte, followed by the value itself. The maximum supported length is 255 bytes.
- Return type:
bytes- Parameters:
value (bytes) – The data to encode.
- Returns:
The LV-encoded bytes.
- Return type:
bytes
- Raises:
ValueError – If the input exceeds 255 bytes in length.
keycard.card_interface module¶
- class keycard.card_interface.CardInterface(*args, **kwargs)¶
Bases:
ProtocolAbstract base class representing a Keycard interface for command functions.
- ca_public_keys: list[bytes]¶
- card_public_key: bytes | None¶
- property identity_certificate: bytes | None¶
- property is_initialized: bool¶
- property is_pin_verified: bool¶
- property is_secure_channel_open: bool¶
- property is_selected: bool¶
- open_secure_channel()¶
- Return type:
None
- send_apdu(ins, p1=0, p2=0, data=b'', cla=None)¶
- Return type:
bytes
- send_raw_apdu(apdu)¶
- Return type:
- send_secure_apdu(ins, p1=0, p2=0, data=b'')¶
- Return type:
bytes
- trusted_identity_keys: list[bytes]¶
- property version: tuple[int, int]¶
keycard.constants module¶
This module defines constants used for communication with the Keycard applet via APDU commands.
- class keycard.constants.DerivationOption(*values)¶
Bases:
IntEnum- CURRENT = 0¶
- DERIVE = 1¶
- DERIVE_AND_MAKE_CURRENT = 2¶
- PINLESS = 3¶
- class keycard.constants.DerivationSource(*values)¶
Bases:
IntEnum- CURRENT = 128¶
- MASTER = 0¶
- PARENT = 64¶
- class keycard.constants.KeyExportOption(*values)¶
Bases:
IntEnum- EXTENDED_PUBLIC = 2¶
- PRIVATE_AND_PUBLIC = 0¶
- PUBLIC_ONLY = 1¶
- class keycard.constants.LoadKeyType(*values)¶
Bases:
IntEnum- BIP39_SEED = 3¶
- ECC = 1¶
- EXTENDED_ECC = 2¶
- LEE_SEED = 4¶
- class keycard.constants.PairingMode(*values)¶
Bases:
IntEnum- ANY = 0¶
- EPHEMERAL = 1¶
- PERSISTENT = 2¶
keycard.exceptions module¶
- exception keycard.exceptions.APDUError(sw)¶
Bases:
KeyCardErrorRaised when APDU returns non-success status word.
- exception keycard.exceptions.InvalidResponseError¶
Bases:
KeyCardErrorRaised when response parsing fails.
- exception keycard.exceptions.InvalidStateError(message)¶
Bases:
KeyCardErrorRaised when a precondition is not met.
- exception keycard.exceptions.KeyCardError¶
Bases:
ExceptionBase exception for Keycard SDK
- exception keycard.exceptions.NotInitializedError¶
Bases:
KeyCardErrorRaised when trying to use card public key before select().
- exception keycard.exceptions.NotSelectedError¶
Bases:
KeyCardErrorRaised when trying to use card before select().
- exception keycard.exceptions.TransportError¶
Bases:
KeyCardErrorRaised there are no readers
- exception keycard.exceptions.UntrustedCardError¶
Bases:
KeyCardErrorRaised when a card’s identity cannot be verified as trusted.
keycard.keycard module¶
- class keycard.keycard.KeyCard(transport=None, ca_public_keys=None, trusted_identity_keys=None)¶
Bases:
CardInterfaceHigh-level interface for interacting with a Keycard device.
This class provides convenient methods to manage pairing, secure channels, and card operations.
- change_pairing_secret(new_value)¶
Changes the pairing secret on the card.
- Return type:
None- Parameters:
new_value (str) – The new pairing secret value to set.
- Raises:
ValueError – If input format is invalid.
APDUError – If the response status word is not 0x9000.
- change_pin(new_value)¶
Changes the user PIN on the card.
- Return type:
None- Parameters:
new_value (str) – The new PIN value to set.
- Raises:
ValueError – If input format is invalid.
APDUError – If the response status word is not 0x9000.
- change_puk(new_value)¶
Changes the PUK on the card.
- Return type:
None- Parameters:
new_value (str) – The new PUK value to set.
- Raises:
ValueError – If input format is invalid.
APDUError – If the response status word is not 0x9000.
- derive_key(path='')¶
Set the derivation path for subsequent SIGN and EXPORT KEY commands.
- Return type:
None- Parameters:
path (str) – BIP-32-style path (e.g., “m/44’/60’/0’/0/0”) or “../0/1” (parent) or “./0” (current).
- ecdh(public_key, path)¶
Compute an ECDH shared secret with the key at a path. Needs applet 4.0. The result is a raw secret; apply the protocol’s KDF to it.
- Return type:
bytes- Parameters:
public_key (bytes) – The peer’s uncompressed public key, 65 bytes.
path (str) – Path under “m/44’/1237’” (NIP-44) or “m/43’/60’/1581’” (EIP-1581), at least 5 levels deep.
- Returns:
The 32-byte X coordinate of the shared point.
- Return type:
bytes
- export_bip85(path, length)¶
Export BIP-85 entropy derived from the loaded key. Needs applet 4.0.
- Return type:
bytes- Parameters:
path (str) – Path starting with “m/83696968’”, every component hardened, e.g. “m/83696968’/0’/0’”.
length (int) – Number of entropy bytes, 1 to 64.
- Returns:
The entropy.
- Return type:
bytes
- export_current_key(public_only=False)¶
Exports the current key from the card.
This is a convenience method that uses the CURRENT derivation option and does not require a keypath.
- Return type:
- Parameters:
public_only (bool) – If True, only the public key will be returned.
- Returns:
- An object containing the public key, and optionally
the private key and chain code.
- Return type:
- export_key(derivation_option, public_only, keypath=None, make_current=False, source=DerivationSource.MASTER)¶
Export a key from the card.
This is a proxy for
keycard.commands.export_key(), provided here for convenience.- Return type:
- Parameters:
derivation_option – One of the derivation options (CURRENT, DERIVE, DERIVE_AND_MAKE_CURRENT).
public_only – If True, only the public key will be returned.
keypath – BIP32-style string (e.g. “m/44’/60’/0’/0/0”) or packed bytes. If derivation_option is CURRENT, this can be omitted.
make_current – If True, updates the card’s current derivation path.
source – Which node to derive from: MASTER, PARENT, or CURRENT.
- Returns:
- An object containing the public key, and optionally
the private key and chain code.
- Return type:
See also
keycard.commands.export_key()- for the lower-levelimplementation
keycard.types.ExportedKey- return valuestructure
- export_lee(path='m')¶
Export the LEE keys at a path. Needs applet 4.0 in LEE mode.
- factory_reset()¶
Sends the FACTORY_RESET command to the card.
The card closes any secure channel and forgets its credentials, so the session, PIN and initialization state are reset.
- Return type:
None- Raises:
APDUError – If the card returns a failure status word.
- generate_key()¶
Generates a new key on the card and returns the key UID.
- Return type:
bytes- Returns:
Key UID (SHA-256 of the public key)
- Return type:
bytes
- Raises:
APDUError – If the response status word is not 0x9000
- generate_mnemonic(checksum_size=6)¶
Generate a BIP39 mnemonic using the card’s RNG.
- Return type:
list[int]- Parameters:
checksum_size (int) – Number of checksum bits (between 4 and 8 inclusive).
- Returns:
- List of integers (0-2047) corresponding to wordlist
indexes.
- Return type:
List[int]
- get_challenge(length)¶
Gets random bytes generated by the card.
Applet 4.0 needs an open secure channel, but not an initialized card. Earlier applets that support the command also answer without a channel.
- Return type:
bytes- Parameters:
length (int) – Number of bytes, 1 to 255; the card limits it to 245 over Secure Channel V2 and 221 over V1.
- Returns:
The random bytes.
- Return type:
bytes
- Raises:
ValueError – If the length does not fit in P1.
InvalidStateError – If a 4.x card has no open secure channel.
- get_data(slot=StorageSlot.PUBLIC)¶
Gets the data on the card previously stored with the store data command in the specified slot.
NDEF data is the complete NDEF file, starting with its 2-byte length. Applets before 4.0 return at most the first 223 bytes.
- Return type:
bytes- Parameters:
slot (StorageSlot) – Where to retrieve the data (PUBLIC, NDEF, CASH)
- Raises:
InvalidResponseError – If segmented NDEF data is malformed.
- property get_key_path: dict[str, int | bool] | list[int]¶
Returns the current key derivation path from the card.
- Returns:
List of 32-bit integers representing the key path.
- Return type:
list of int
- Raises:
RuntimeError – If the secure session is not open.
- ident(challenge=None)¶
Sends an identity challenge to the card.
- Return type:
bytes- Parameters:
challenge (bytes) – A challenge (nonce or data) to send to the card. If None, a random 32-byte challenge is generated.
- Returns:
The public key extracted from the card’s identity response.
- Return type:
bytes
- property identity_certificate: bytes | None¶
The card’s Identity Certificate from SELECT (4.x only).
- Returns:
The 98-byte certificate, or None.
- Return type:
bytes
- init(pin, puk, pairing_secret=None, pin_retries=None, puk_retries=None, alt_pin=None)¶
Initializes the card with its credentials.
Secure Channel V1 cards need the pairing secret. Secure Channel V2 cards take none; the channel is opened if needed and stays open.
- Return type:
None- Parameters:
pin (str) – The 6-digit PIN.
puk (str) – The 12-digit PUK.
pairing_secret – The pairing secret (Secure Channel V1 only).
pin_retries (int) – PIN attempts, 2 to 10 (default 3).
puk_retries (int) – PUK attempts, 3 to 12 (default 5).
alt_pin (str) – Optional 6-digit Alternate PIN.
- Raises:
ValueError – If the pairing secret is missing on V1, given on V2, or a parameter is out of range.
- property is_initialized: bool¶
Checks if the Keycard is initialized.
- Returns:
True if the Keycard is initialized, False otherwise.
- Return type:
bool
- property is_pin_verified: bool¶
Checks if the user PIN has been verified.
- Returns:
True if the PIN is verified, False otherwise.
- Return type:
bool
- property is_secure_channel_open: bool¶
Checks if a secure channel is currently open.
- Returns:
True if a secure channel is established, False otherwise.
- Return type:
bool
- property is_selected: bool¶
Checks if the Keycard applet has been selected.
- Returns:
True if a card is selected, False otherwise.
- Return type:
bool
- property is_session_open: bool¶
Checks if a secure session is currently open.
- Returns:
True if a secure session is established, False otherwise.
- Return type:
bool
- load_key(key_type, public_key=None, private_key=None, chain_code=None, bip39_seed=None)¶
Load a key into the card for signing purposes.
- Return type:
bytes- Parameters:
key_type – Key type
public_key – Optional ECC public key (tag 0x80).
private_key – ECC private key (tag 0x81).
chain_code – Optional chain code (tag 0x82, only for extended key).
bip39_seed – 16 to 64-byte binary seed (only for key_type BIP39_SEED, or LEE_SEED to also derive the LEE keys on applet 4.0).
- Returns:
UID of the loaded key (SHA-256 of public key).
- mutually_authenticate()¶
Performs mutual authentication between host and card.
- Return type:
None- Raises:
APDUError – If the authentication fails.
InvalidStateError – If the card does not use Secure Channel V1.
- open_secure_channel()¶
Opens a secure session with the card.
Secure Channel V1 cards use
pairing(set bypair()or assigned) and run MUTUALLY AUTHENTICATE. Secure Channel V2 cards need an Identity Certificate signed by one ofca_public_keys, or an Identity Key intrusted_identity_keys.- Return type:
None- Raises:
InvalidStateError – If a V1 card has no pairing.
UntrustedCardError – If a V2 card is not trusted.
InvalidResponseError – If the handshake does not verify.
- pair(shared_secret, pairing_mode=PairingMode.ANY)¶
Pairs with the card using an ECDH-derived shared secret.
- Return type:
- Parameters:
shared_secret (bytes) – 32-byte ECDH shared secret.
The pairing is stored in
pairingforopen_secure_channel.- Returns:
The pairing slot and key.
- Return type:
- Raises:
InvalidStateError – If the card does not use Secure Channel V1.
- remove_key()¶
Removes the current key from the card.
- Return type:
None- Raises:
APDUError – If the response status word is not 0x9000.
- property secure_channel_version: SecureChannelVersion | None¶
The secure channel version the selected card uses.
- Returns:
- V2 from applet 4.0, V1 before, or None
before select().
- Return type:
- select()¶
Selects the Keycard applet and retrieves application metadata.
Selecting the applet closes any secure channel on the card, so the session and PIN state are reset.
- Return type:
- Returns:
The card’s application information.
- Return type:
- send_apdu(ins, p1=0, p2=0, data=b'', cla=None)¶
- Return type:
bytes
- send_raw_apdu(apdu)¶
Sends a complete APDU and returns the raw response.
- Return type:
- Returns:
The response data and status word.
- Return type:
- send_secure_apdu(ins, p1=0, p2=0, data=b'')¶
- Return type:
bytes
- set_pinless_path(path)¶
Set a PIN-less path on the card. Allows signing without PIN/auth if the current derived key matches this path.
- Return type:
None- Parameters:
path (str) – BIP-32-style path (e.g., “m/44’/60’/0’/0/0”). An empty string disables the pinless path.
- sign(digest, algorithm=SigningAlgorithm.ECDSA_SECP256K1, tweak=None)¶
Sign using the currently loaded keypair; on applet 4.0, which has no current key, the master key. Requires PIN verification and secure channel.
- Return type:
- Parameters:
digest (bytes) – 32-byte hash to sign
algorithm (SigningAlgorithm) – ECDSA_SECP256K1 (default) or, on applet 4.0, SCHNORR_BIP340.
tweak (Optional[bytes]) – 32-byte Schnorr tweak; zeros if omitted.
- Returns:
- Parsed signature result, including the signature
(DER or raw), algorithm, and optional recovery ID or public key.
- Return type:
- sign_pinless(digest)¶
Sign using the predefined PIN-less path. Does not require secure channel or PIN.
- Return type:
- Parameters:
digest (bytes) – 32-byte hash to sign
- Returns:
- Parsed signature result, including the signature
(DER or raw), algorithm, and optional recovery ID or public key.
- Return type:
- Raises:
APDUError – if no PIN-less path is set
- sign_with_path(digest, path, make_current=False, algorithm=SigningAlgorithm.ECDSA_SECP256K1, tweak=None)¶
Sign using a derived keypath. Optionally updates the current path.
- Return type:
- Parameters:
digest (bytes) – 32-byte hash to sign
path (str) – BIP-32-style path (e.g. “m/44’/60’/0’/0/0”); “m” is the master key
make_current (bool) – whether to update current path on card (not supported by applet 4.0)
algorithm (SigningAlgorithm) – ECDSA_SECP256K1 (default) or, on applet 4.0, SCHNORR_BIP340.
tweak (Optional[bytes]) – 32-byte Schnorr tweak; zeros if omitted.
- Returns:
- Parsed signature result, including the signature
(DER or raw), algorithm, and optional recovery ID or public key.
- Return type:
- property status: dict[str, int | bool] | list[int]¶
Retrieves the application status using the secure session.
- Returns:
- A dictionary with:
pin_retry_count (int)
puk_retry_count (int)
initialized (bool)
- Return type:
dict
- Raises:
RuntimeError – If the secure session is not open.
- store_data(data, slot=StorageSlot.PUBLIC)¶
Stores data on the card in the specified slot.
NDEF data is the complete NDEF file, starting with its 2-byte length.
- Return type:
None- Parameters:
data (bytes) – The data to store (max 127 bytes, or 512 bytes for NDEF from applet 3.2).
slot (StorageSlot) – Where to store the data (PUBLIC, NDEF, CASH)
- Raises:
ValueError – If the data is too long.
- unblock_pin(puk, new_pin)¶
Unblocks the user PIN using the provided PUK and sets a new PIN.
- Return type:
None- Parameters:
puk_and_pin (str | bytes) – Concatenation of PUK (12 digits) + new PIN (6 digits)
- Raises:
ValueError – If the format is invalid.
APDUError – If the card returns an error.
- unpair(index)¶
Removes a pairing slot from the card.
- Return type:
None- Parameters:
index (int) – Index of the pairing slot to remove.
- Raises:
InvalidStateError – If the card does not use Secure Channel V1.
- verify_pin(pin)¶
Verifies the user PIN with the card.
- Return type:
bool- Parameters:
pin (str) – The user-entered PIN.
A failed attempt also clears a previous verification, as it does on the card.
- Returns:
True if PIN is valid, otherwise False.
- Return type:
bool
- property version: tuple[int, int]¶
Retuns tuple with major and minor version number
- Returns:
[major_version, minor_version]
- Return type:
[int, int]
keycard.pairing module¶
keycard.preconditions module¶
- keycard.preconditions.make_precondition(attribute_name, display_name=None)¶
- Return type:
Callable[[Callable[[ParamSpec(P)],TypeVar(R)]],Callable[[ParamSpec(P)],TypeVar(R)]]
- keycard.preconditions.require_initialized(func)¶
- Return type:
Callable[[ParamSpec(P)],TypeVar(R)]
- keycard.preconditions.require_pin_verified(func)¶
- Return type:
Callable[[ParamSpec(P)],TypeVar(R)]
- keycard.preconditions.require_secure_channel(func)¶
- Return type:
Callable[[ParamSpec(P)],TypeVar(R)]
- keycard.preconditions.require_selected(func)¶
- Return type:
Callable[[ParamSpec(P)],TypeVar(R)]
keycard.transport module¶
Module contents¶
Python SDK for interacting with Status Keycard.
- class keycard.CardInterface(*args, **kwargs)¶
Bases:
ProtocolAbstract base class representing a Keycard interface for command functions.
- ca_public_keys: list[bytes]¶
- card_public_key: bytes | None¶
- property identity_certificate: bytes | None¶
- property is_initialized: bool¶
- property is_pin_verified: bool¶
- property is_secure_channel_open: bool¶
- property is_selected: bool¶
- open_secure_channel()¶
- Return type:
None
- send_apdu(ins, p1=0, p2=0, data=b'', cla=None)¶
- Return type:
bytes
- send_raw_apdu(apdu)¶
- Return type:
- send_secure_apdu(ins, p1=0, p2=0, data=b'')¶
- Return type:
bytes
- trusted_identity_keys: list[bytes]¶
- property version: tuple[int, int]¶
- class keycard.KeyCard(transport=None, ca_public_keys=None, trusted_identity_keys=None)¶
Bases:
CardInterfaceHigh-level interface for interacting with a Keycard device.
This class provides convenient methods to manage pairing, secure channels, and card operations.
- change_pairing_secret(new_value)¶
Changes the pairing secret on the card.
- Return type:
None- Parameters:
new_value (str) – The new pairing secret value to set.
- Raises:
ValueError – If input format is invalid.
APDUError – If the response status word is not 0x9000.
- change_pin(new_value)¶
Changes the user PIN on the card.
- Return type:
None- Parameters:
new_value (str) – The new PIN value to set.
- Raises:
ValueError – If input format is invalid.
APDUError – If the response status word is not 0x9000.
- change_puk(new_value)¶
Changes the PUK on the card.
- Return type:
None- Parameters:
new_value (str) – The new PUK value to set.
- Raises:
ValueError – If input format is invalid.
APDUError – If the response status word is not 0x9000.
- derive_key(path='')¶
Set the derivation path for subsequent SIGN and EXPORT KEY commands.
- Return type:
None- Parameters:
path (str) – BIP-32-style path (e.g., “m/44’/60’/0’/0/0”) or “../0/1” (parent) or “./0” (current).
- ecdh(public_key, path)¶
Compute an ECDH shared secret with the key at a path. Needs applet 4.0. The result is a raw secret; apply the protocol’s KDF to it.
- Return type:
bytes- Parameters:
public_key (bytes) – The peer’s uncompressed public key, 65 bytes.
path (str) – Path under “m/44’/1237’” (NIP-44) or “m/43’/60’/1581’” (EIP-1581), at least 5 levels deep.
- Returns:
The 32-byte X coordinate of the shared point.
- Return type:
bytes
- export_bip85(path, length)¶
Export BIP-85 entropy derived from the loaded key. Needs applet 4.0.
- Return type:
bytes- Parameters:
path (str) – Path starting with “m/83696968’”, every component hardened, e.g. “m/83696968’/0’/0’”.
length (int) – Number of entropy bytes, 1 to 64.
- Returns:
The entropy.
- Return type:
bytes
- export_current_key(public_only=False)¶
Exports the current key from the card.
This is a convenience method that uses the CURRENT derivation option and does not require a keypath.
- Return type:
- Parameters:
public_only (bool) – If True, only the public key will be returned.
- Returns:
- An object containing the public key, and optionally
the private key and chain code.
- Return type:
- export_key(derivation_option, public_only, keypath=None, make_current=False, source=DerivationSource.MASTER)¶
Export a key from the card.
This is a proxy for
keycard.commands.export_key(), provided here for convenience.- Return type:
- Parameters:
derivation_option – One of the derivation options (CURRENT, DERIVE, DERIVE_AND_MAKE_CURRENT).
public_only – If True, only the public key will be returned.
keypath – BIP32-style string (e.g. “m/44’/60’/0’/0/0”) or packed bytes. If derivation_option is CURRENT, this can be omitted.
make_current – If True, updates the card’s current derivation path.
source – Which node to derive from: MASTER, PARENT, or CURRENT.
- Returns:
- An object containing the public key, and optionally
the private key and chain code.
- Return type:
See also
keycard.commands.export_key()- for the lower-levelimplementation
keycard.types.ExportedKey- return valuestructure
- export_lee(path='m')¶
Export the LEE keys at a path. Needs applet 4.0 in LEE mode.
- factory_reset()¶
Sends the FACTORY_RESET command to the card.
The card closes any secure channel and forgets its credentials, so the session, PIN and initialization state are reset.
- Return type:
None- Raises:
APDUError – If the card returns a failure status word.
- generate_key()¶
Generates a new key on the card and returns the key UID.
- Return type:
bytes- Returns:
Key UID (SHA-256 of the public key)
- Return type:
bytes
- Raises:
APDUError – If the response status word is not 0x9000
- generate_mnemonic(checksum_size=6)¶
Generate a BIP39 mnemonic using the card’s RNG.
- Return type:
list[int]- Parameters:
checksum_size (int) – Number of checksum bits (between 4 and 8 inclusive).
- Returns:
- List of integers (0-2047) corresponding to wordlist
indexes.
- Return type:
List[int]
- get_challenge(length)¶
Gets random bytes generated by the card.
Applet 4.0 needs an open secure channel, but not an initialized card. Earlier applets that support the command also answer without a channel.
- Return type:
bytes- Parameters:
length (int) – Number of bytes, 1 to 255; the card limits it to 245 over Secure Channel V2 and 221 over V1.
- Returns:
The random bytes.
- Return type:
bytes
- Raises:
ValueError – If the length does not fit in P1.
InvalidStateError – If a 4.x card has no open secure channel.
- get_data(slot=StorageSlot.PUBLIC)¶
Gets the data on the card previously stored with the store data command in the specified slot.
NDEF data is the complete NDEF file, starting with its 2-byte length. Applets before 4.0 return at most the first 223 bytes.
- Return type:
bytes- Parameters:
slot (StorageSlot) – Where to retrieve the data (PUBLIC, NDEF, CASH)
- Raises:
InvalidResponseError – If segmented NDEF data is malformed.
- property get_key_path: dict[str, int | bool] | list[int]¶
Returns the current key derivation path from the card.
- Returns:
List of 32-bit integers representing the key path.
- Return type:
list of int
- Raises:
RuntimeError – If the secure session is not open.
- ident(challenge=None)¶
Sends an identity challenge to the card.
- Return type:
bytes- Parameters:
challenge (bytes) – A challenge (nonce or data) to send to the card. If None, a random 32-byte challenge is generated.
- Returns:
The public key extracted from the card’s identity response.
- Return type:
bytes
- property identity_certificate: bytes | None¶
The card’s Identity Certificate from SELECT (4.x only).
- Returns:
The 98-byte certificate, or None.
- Return type:
bytes
- init(pin, puk, pairing_secret=None, pin_retries=None, puk_retries=None, alt_pin=None)¶
Initializes the card with its credentials.
Secure Channel V1 cards need the pairing secret. Secure Channel V2 cards take none; the channel is opened if needed and stays open.
- Return type:
None- Parameters:
pin (str) – The 6-digit PIN.
puk (str) – The 12-digit PUK.
pairing_secret – The pairing secret (Secure Channel V1 only).
pin_retries (int) – PIN attempts, 2 to 10 (default 3).
puk_retries (int) – PUK attempts, 3 to 12 (default 5).
alt_pin (str) – Optional 6-digit Alternate PIN.
- Raises:
ValueError – If the pairing secret is missing on V1, given on V2, or a parameter is out of range.
- property is_initialized: bool¶
Checks if the Keycard is initialized.
- Returns:
True if the Keycard is initialized, False otherwise.
- Return type:
bool
- property is_pin_verified: bool¶
Checks if the user PIN has been verified.
- Returns:
True if the PIN is verified, False otherwise.
- Return type:
bool
- property is_secure_channel_open: bool¶
Checks if a secure channel is currently open.
- Returns:
True if a secure channel is established, False otherwise.
- Return type:
bool
- property is_selected: bool¶
Checks if the Keycard applet has been selected.
- Returns:
True if a card is selected, False otherwise.
- Return type:
bool
- property is_session_open: bool¶
Checks if a secure session is currently open.
- Returns:
True if a secure session is established, False otherwise.
- Return type:
bool
- load_key(key_type, public_key=None, private_key=None, chain_code=None, bip39_seed=None)¶
Load a key into the card for signing purposes.
- Return type:
bytes- Parameters:
key_type – Key type
public_key – Optional ECC public key (tag 0x80).
private_key – ECC private key (tag 0x81).
chain_code – Optional chain code (tag 0x82, only for extended key).
bip39_seed – 16 to 64-byte binary seed (only for key_type BIP39_SEED, or LEE_SEED to also derive the LEE keys on applet 4.0).
- Returns:
UID of the loaded key (SHA-256 of public key).
- mutually_authenticate()¶
Performs mutual authentication between host and card.
- Return type:
None- Raises:
APDUError – If the authentication fails.
InvalidStateError – If the card does not use Secure Channel V1.
- open_secure_channel()¶
Opens a secure session with the card.
Secure Channel V1 cards use
pairing(set bypair()or assigned) and run MUTUALLY AUTHENTICATE. Secure Channel V2 cards need an Identity Certificate signed by one ofca_public_keys, or an Identity Key intrusted_identity_keys.- Return type:
None- Raises:
InvalidStateError – If a V1 card has no pairing.
UntrustedCardError – If a V2 card is not trusted.
InvalidResponseError – If the handshake does not verify.
- pair(shared_secret, pairing_mode=PairingMode.ANY)¶
Pairs with the card using an ECDH-derived shared secret.
- Return type:
- Parameters:
shared_secret (bytes) – 32-byte ECDH shared secret.
The pairing is stored in
pairingforopen_secure_channel.- Returns:
The pairing slot and key.
- Return type:
- Raises:
InvalidStateError – If the card does not use Secure Channel V1.
- remove_key()¶
Removes the current key from the card.
- Return type:
None- Raises:
APDUError – If the response status word is not 0x9000.
- property secure_channel_version: SecureChannelVersion | None¶
The secure channel version the selected card uses.
- Returns:
- V2 from applet 4.0, V1 before, or None
before select().
- Return type:
- select()¶
Selects the Keycard applet and retrieves application metadata.
Selecting the applet closes any secure channel on the card, so the session and PIN state are reset.
- Return type:
- Returns:
The card’s application information.
- Return type:
- send_apdu(ins, p1=0, p2=0, data=b'', cla=None)¶
- Return type:
bytes
- send_raw_apdu(apdu)¶
Sends a complete APDU and returns the raw response.
- Return type:
- Returns:
The response data and status word.
- Return type:
- send_secure_apdu(ins, p1=0, p2=0, data=b'')¶
- Return type:
bytes
- set_pinless_path(path)¶
Set a PIN-less path on the card. Allows signing without PIN/auth if the current derived key matches this path.
- Return type:
None- Parameters:
path (str) – BIP-32-style path (e.g., “m/44’/60’/0’/0/0”). An empty string disables the pinless path.
- sign(digest, algorithm=SigningAlgorithm.ECDSA_SECP256K1, tweak=None)¶
Sign using the currently loaded keypair; on applet 4.0, which has no current key, the master key. Requires PIN verification and secure channel.
- Return type:
- Parameters:
digest (bytes) – 32-byte hash to sign
algorithm (SigningAlgorithm) – ECDSA_SECP256K1 (default) or, on applet 4.0, SCHNORR_BIP340.
tweak (Optional[bytes]) – 32-byte Schnorr tweak; zeros if omitted.
- Returns:
- Parsed signature result, including the signature
(DER or raw), algorithm, and optional recovery ID or public key.
- Return type:
- sign_pinless(digest)¶
Sign using the predefined PIN-less path. Does not require secure channel or PIN.
- Return type:
- Parameters:
digest (bytes) – 32-byte hash to sign
- Returns:
- Parsed signature result, including the signature
(DER or raw), algorithm, and optional recovery ID or public key.
- Return type:
- Raises:
APDUError – if no PIN-less path is set
- sign_with_path(digest, path, make_current=False, algorithm=SigningAlgorithm.ECDSA_SECP256K1, tweak=None)¶
Sign using a derived keypath. Optionally updates the current path.
- Return type:
- Parameters:
digest (bytes) – 32-byte hash to sign
path (str) – BIP-32-style path (e.g. “m/44’/60’/0’/0/0”); “m” is the master key
make_current (bool) – whether to update current path on card (not supported by applet 4.0)
algorithm (SigningAlgorithm) – ECDSA_SECP256K1 (default) or, on applet 4.0, SCHNORR_BIP340.
tweak (Optional[bytes]) – 32-byte Schnorr tweak; zeros if omitted.
- Returns:
- Parsed signature result, including the signature
(DER or raw), algorithm, and optional recovery ID or public key.
- Return type:
- property status: dict[str, int | bool] | list[int]¶
Retrieves the application status using the secure session.
- Returns:
- A dictionary with:
pin_retry_count (int)
puk_retry_count (int)
initialized (bool)
- Return type:
dict
- Raises:
RuntimeError – If the secure session is not open.
- store_data(data, slot=StorageSlot.PUBLIC)¶
Stores data on the card in the specified slot.
NDEF data is the complete NDEF file, starting with its 2-byte length.
- Return type:
None- Parameters:
data (bytes) – The data to store (max 127 bytes, or 512 bytes for NDEF from applet 3.2).
slot (StorageSlot) – Where to store the data (PUBLIC, NDEF, CASH)
- Raises:
ValueError – If the data is too long.
- unblock_pin(puk, new_pin)¶
Unblocks the user PIN using the provided PUK and sets a new PIN.
- Return type:
None- Parameters:
puk_and_pin (str | bytes) – Concatenation of PUK (12 digits) + new PIN (6 digits)
- Raises:
ValueError – If the format is invalid.
APDUError – If the card returns an error.
- unpair(index)¶
Removes a pairing slot from the card.
- Return type:
None- Parameters:
index (int) – Index of the pairing slot to remove.
- Raises:
InvalidStateError – If the card does not use Secure Channel V1.
- verify_pin(pin)¶
Verifies the user PIN with the card.
- Return type:
bool- Parameters:
pin (str) – The user-entered PIN.
A failed attempt also clears a previous verification, as it does on the card.
- Returns:
True if PIN is valid, otherwise False.
- Return type:
bool
- property version: tuple[int, int]¶
Retuns tuple with major and minor version number
- Returns:
[major_version, minor_version]
- Return type:
[int, int]