Mastercard pkcs11-tools

repository·master·Indexed 42 days ago

https://github.com/mastercard/pkcs11-tools

A collection of CLI utilities for managing cryptographic keys and certificates on PKCS#11 compliant tokens, including HSMs and software implementations like SoftHSM. Supports key generation, import/export, and wrapping/unwrapping. Version 3.0.0 introduces support for NIST/PKCS#11 v3.2 Post-Quantum Cryptography (PQC) algorithms including ML-KEM, ML-DSA, and SLH-DSA.

Tokens
43.1K
Snippets
103
Records
182
Agent score
48%

What's inside pkcs11-tools

  1. Overview of pkcs11-tools

    master

    pkcs11-tools is a toolkit of small utilities designed for key management tasks on cryptographic tokens that implement a PKCS#11 interface. It provides a CLI experience similar to Unix utilities (like ls, mv, rm) but specialized for cryptographic operations.

    Key capabilities include:

    • Key Generation & Management: Generate keys (including Post-Quantum Cryptography), CSRs (PKCS#10), and self-signed certificates.
    • Import/Export: Import certificates, public keys, and data files.
    • Wrapping/Unwrapping: Support for symmetric and asymmetric key wrapping/unwrapping, including session key generation and direct wrapping.
    • Advanced Operations: Key rewrapping (unwrap as session key then rewrap), token initialization, and reset.
    • Compatibility: Works with software tokens like SoftHSM, NSS, and Kryoptic, as well as hardware tokens like YubiHSM and AWS CloudHSM.
    • Algorithm Support: DES, 3DES, AES, HMAC, RSA, DSA, DH, NIST curves, Edwards curves, and Post-Quantum Cryptography (ML-KEM, ML-DSA, SLH-DSA).
  2. Overview of pkcs11-tools commands

    master

    The pkcs11-tools toolkit is a collection of command-line utilities for managing cryptographic objects on PKCS#11 tokens (HSMs, smart cards, or software keystores like SoftHSM2 or NSS).

    Key commands include:

    • p11ls: List token contents by object class.
    • p11keygen: Generate keys or key pairs (with optional wrapping).
    • p11importcert: Import PEM/DER certificates and bind them to private keys via CKA_ID.
    • p11importpubk: Import public keys (adjusts CKA_ID per IBM JCA rules).
    • p11importdata: Import arbitrary files as data objects.
    • p11wrap / p11unwrap: Export/Import keys using the pkcs11-wrap(5) format.
    • p11rm: Delete objects or classes of objects.
    • p11setattr: Change object attributes.
    • p11cat: Print certificates or public keys in PEM format.
    • p11more: Display decoded, human-readable certificate/key content.
    • p11od: Object dumper (prints all attributes in hex).
    • p11req: Generate PKCS#10 CSRs.
    • p11kcv: Compute Key Check Values (KCV) for symmetric keys.
    • p11init: Initialize or reset a token/PIN.
    • p11slotinfo: Print slot/token info and supported mechanisms.
    • p11mv: Rename token objects.
    • p11mkcert: Generate self-signed certificates for Java JCA.
    • masqreq: Adjust subject DN/extensions of an existing CSR.
  3. Use vendor-specific wrapper scripts for pkcs11-tools

    master

    The with_xxx scripts are POSIX shell wrappers that simplify running pkcs11-tools commands against specific PKCS#11 vendor libraries. Instead of manually locating library paths and setting environment variables, you can use the appropriate wrapper for your hardware or software token.

    Each wrapper automatically:

    1. Locates the vendor PKCS#11 library via auto-detection.
    2. Sources configuration from .pkcs11rc or .pkcs11rc.<vendor>.
    3. Sets necessary environment variables like PKCS11LIB.
    4. Executes the requested pkcs11-tools command.

    Available Wrappers:

    • with_aws: AWS CloudHSM
    • with_beid: Belgian national eID
    • with_kryoptic: Kryoptic software token
    • with_luna: Thales/Gemalto SafeNet Luna HSM
    • with_nfast: Entrust (nCipher) nShield HSM
    • with_nss: Mozilla NSS soft token (defaults to Slot 1)
    • with_softhsm: OpenDNSSEC SoftHSM v2
    • with_utimaco: Utimaco SecurityServer HSM
    • with_yubico: Yubico YubiHSM 2
    with_softhsm p11ls
    with_luna p11keygen -k rsa -b 2048 -i my-rsa-key sign verify
  4. Understand variable precedence in pkcs11-tools

    master

    When configuring pkcs11-tools, multiple sources can define variables. The precedence order (from lowest to highest) is:

    1. Wrapper defaults: Hard-coded values in with_xxx scripts.
    2. .pkcs11rc files: Variables sourced from .pkcs11rc or .pkcs11rc.<vendor>.
    3. Environment variables: Variables exported by the caller before invoking the wrapper.
    4. Command-line options: Direct flags passed to the pkcs11-tools command (e.g., -l, -s, -t, -p, -m).

    Note: If you export a variable in your shell before calling the wrapper, the .pkcs11rc file will not overwrite it, because a POSIX shell assignment to an already-exported variable has no effect on the exported value from the parent.

  5. How library auto-detection works

    master

    The wrappers attempt to find the vendor library automatically by searching specific directories.

    Search Order:

    1. Vendor-specific directories defined within the wrapper.
    2. /usr/lib and /usr/lib/pkcs11.
    3. /usr/lib64 and /usr/lib64/pkcs11 (Linux only).
    4. /usr/lib/<arch>-linux-gnu and its pkcs11 subdirectory (Linux only).
    5. /usr/local/lib and /usr/local/lib/pkcs11.
    6. $HOME/.local/lib.
    7. $HOMEBREW_PREFIX/lib and $HOMEBREW_PREFIX/lib/pkcs11 (if HOMEBREW_PREFIX is set).

    Notes:

    • On macOS, wrappers search for .dylib files first (except SoftHSM2, which uses .so).
    • For with_utimaco, libcs_pkcs11_R3.so is preferred over libcs_pkcs11_R2.so.
    • You can bypass auto-detection entirely by setting the PKCS11LIB environment variable to an explicit path.
  6. Understand the pkcs11-wrap file format

    master

    The pkcs11-wrap file format is a text-based, self-describing container for a PKCS#11-wrapped key. It is used to transport keys between different PKCS#11 tokens.

    Key Characteristics

    • Producers: Created by p11wrap and p11keygen (using the -W parameter).
    • Consumers: Consumed by p11unwrap and p11rewrap.
    • Format: A POSIX text file where lines are terminated by newlines, blank lines are ignored, and lines starting with # are comments. The lexer is case-insensitive for header keywords and algorithm names.
    • Structure: A file typically consists of:
      1. Header lines: Describe file type, grammar version, wrapping key, algorithm, and PKCS#11 attributes.
      2. PEM-style base64 blocks: Carry the encrypted key material.
      3. Optional Public Key: An embedded PEM block used in envelope wrapping.

    Alternative Format: JWK

    When p11wrap or p11keygen is invoked with the -J flag, the output is in JWK (JSON Web Key, RFC 7517) format. Note that the JWK format does not support envelope wrapping.

  7. Post-Quantum Cryptography (PQC) support

    master

    Starting with version 3.0.0, pkcs11-tools supports NIST/PKCS#11 v3.2 Post-Quantum Cryptography algorithms.

    Supported Algorithms:

    • mlkem (ML-KEM, FIPS 203)
    • mldsa (ML-DSA, FIPS 204)
    • slhdsa (SLH-DSA, FIPS 205)

    Usage Notes:

    • Generation: Use p11keygen to generate PQC key pairs.
    • Certificates/CSRs: Use p11req and p11mkcert to produce CSRs and self-signed certificates for mldsa and slhdsa keys.
    • Requirements: Public key export, CSR, and certificate creation require libcrypto >= 3.5.0.
    • Configuration: PQC support is enabled by default. To disable it, use the --disable-pqc flag.
  8. How envelope wrapping works

    master

    Envelope wrapping allows you to wrap any key material (including symmetric keys) using a single private (RSA) key by combining asymmetric and symmetric wrapping.

    Mechanism: It uses an "inner" algorithm to wrap the target key and an "outer" algorithm to wrap the resulting inner key.

    Configuration via -a envelope(args...):

    • inner=<algorithm>: Specifies the algorithm for the target key. Must be one of cbcpad, rfc3394, or rfc5649. (Default: cbcpad).
    • outer=<algorithm>: Specifies the algorithm for the outer layer using the wrapping key. Must be one of pkcs1 or oaep. (Default: oaep).
    # Wrap a key using OAEP outer layer and RFC5649 inner layer
    p11wrap -w "rsa-key" -i "target-key" -a "envelope(inner=rfc5649,outer=oaep)"
  9. Configure key attributes via positional arguments

    master

    Beyond standard command-line options, p11keygen allows you to set specific PKCS#11 attributes (prefixed with CKA_ or bare) using positional ATTRIBUTE=VALUE arguments. This is useful for fine-grained control over key usage (e.g., signing, encryption, or sensitivity).

    Supported Value Syntax:

    • Boolean: true, false, yes, no, on, off, or bare name (for true), or prefix with ! or no (for false).
    • String: Double-quoted ASCII, e.g., "mykey".
    • Hex: Even-digit hex prefixed with 0x, e.g., 0xdeadbeef.
    • Date: YYYYMMDD format.
    • Mechanism: PKCS#11 mechanism names starting with CKM_.
    • Templates: Attribute arrays in { }, e.g., { encrypt decrypt sensitive !extractable }.
    # Example: Generate an AES key that is specifically marked as non-extractable and can be used for encryption/decryption
    p11keygen -i "my-aes-key" -k aes CKA_EXTRACTABLE=false CKA_ENCRYPT=true CKA_DECRYPT=true
  10. Use p11init operations: -I, -U, and -R

    master

    p11init performs three primary operations:

    1. Token Initialization (-I): Calls C_InitToken. The slot must be uninitialized unless -R is used. Requires a token label (-T) and the SO PIN (-O). Note: You must use a slot index (-s) for this operation; -t (token label) is not supported with -I.
    2. User PIN Initialization/Change (-U): Calls C_InitPIN. It uses the SO PIN (-O) to authenticate and sets the user PIN to the value provided via -P. This can be addressed by token label (-t) if the token is already initialized.
    3. Combined Initialization (-I -U): Performs both operations in sequence: initializes the token first, then sets the user PIN.
    4. Reset/Reinitialize (-I -R): Calls C_InitToken on an already initialized token, erasing all existing content. The provided SO PIN (-O) must match the current SO PIN.
  11. Address PKCS#11 objects by label or ID

    master

    When specifying objects in commands, use the following syntax:

    By Label

    If an object has a CKA_LABEL, use [object_class]/[label]:

    • pubk/my-public-key-label (Public Key)
    • prvk/my-private-key-label (Private Key)
    • seck/my-secret-key-label (Secret Key)
    • cert/my-certificate-label (Certificate)
    • data/my-data-label (Data)

    By ID

    If an object lacks a label, use its CKA_ID in the format [object_class]/id/{[hex-string]}:

    • prvk/id/{39363231313338383739}

    Extended Filters

    Append +attribute=value pairs to the selector:

    • cert/sn/12335344+CKA_ENCRYPT/{01}
  12. How to address token objects

    master

    Objects on a token are addressed using the format class/label.

    Supported Classes:

    • pubk: Public key (CKO_PUBLIC_KEY)
    • prvk: Private key (CKO_PRIVATE_KEY)
    • seck: Secret key (CKO_SECRET_KEY)
    • cert: Certificate (CKO_CERTIFICATE)
    • data: Data object (CKO_DATA)

    Examples:

    • By label: pubk/my-rsa-key or seck/aes-wrapping-key.
    • By ID (if no label exists): class/id/{hexstring}. Example: prvk/id/{39363231313338383739}.

    Attribute Filtering: You can append an attribute filter using +. Example: p11ls cert/sn/12335344+CKA_ENCRYPT={01}