KeyCard.py documentation¶
Add your content using reStructuredText
syntax. See the
reStructuredText
documentation for details.
Contents:
- class keycard.keycard.KeyCard(transport=None)¶
High-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).
- 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
- factory_reset()¶
Sends the FACTORY_RESET command to the card.
- 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_data(slot=StorageSlot.PUBLIC)¶
Gets the data on the card previously stored with the store data command in the specified slot.
- Return type:
bytes
- Parameters:
slot (StorageSlot) – Where to retrieve the data (PUBLIC, NDEF, CASH)
- Raises:
ValueError – If slot is invalid or data is too long.
- 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
- init(pin, puk, pairing_secret)¶
Initializes the card with security credentials.
- Return type:
None
- Parameters:
pin (bytes) – The PIN code in bytes.
puk (bytes) – The PUK code in bytes.
pairing_secret (bytes) – The shared secret for pairing.
- 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 a card is selected and has a public key.
- 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 – 64-byte BIP39 seed (only for key_type=BIP39_SEED).
- 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.
- open_secure_channel(pairing_index, pairing_key, mutually_authenticate=True)¶
Opens a secure session with the card.
- Return type:
None
- Parameters:
pairing_index (int) – Index of the pairing slot to use.
pairing_key (bytes) – The shared pairing key (32 bytes).
mutually_authenticate (bool) – Execute mutually authenticate when a secure channel has been opened
- pair(shared_secret)¶
Pairs with the card using an ECDH-derived shared secret.
- Return type:
tuple
[int
,bytes
]- Parameters:
shared_secret (bytes) – 32-byte ECDH shared secret.
- Returns:
The pairing index and client cryptogram.
- Return type:
tuple[int, bytes]
- remove_key()¶
Removes the current key from the card.
- Return type:
None
- Raises:
APDUError – If the response status word is not 0x9000.
- select()¶
Selects the Keycard applet and retrieves application metadata.
- Return type:
- Returns:
Object containing ECC public key and card info.
- Return type:
- 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)¶
Sign using the currently loaded keypair. Requires PIN verification and secure channel.
- 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:
- 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)¶
Sign using a derived keypath. Optionally updates the current path.
- Return type:
- Parameters:
digest (bytes) – 32-byte hash to sign
path (list[int]) – list of 32-bit integers
make_current (bool) – whether to update current path on card
- 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.
- Return type:
None
- Parameters:
data (bytes) – The data to store (max 127 bytes).
slot (StorageSlot) – Where to store the data (PUBLIC, NDEF, CASH)
- Raises:
ValueError – If slot is invalid or 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.
- verify_pin(pin)¶
Verifies the user PIN with the card.
- Return type:
bool
- Parameters:
pin (str) – The user-entered PIN.
- Returns:
True if PIN is valid, otherwise False.
- Return type:
bool