Liking cljdoc? Tell your friends :D

taoensso.tempel

Data security framework for Clojure.

See the GitHub page (esp. Wiki) for info on motivation and design:
  <https://www.taoensso.com/tempel>

See `df.clj` for data formats.
All formats intended to support non-breaking future updates.

Abbreviations:
  External:
    pbkdf - Password Based Key Derivation Function
    aad   - Additional Associated Aata (see `help:aad`)
    akm   - Additional Keying Material (see `help:akm`)
    kek   - Key encryption key (key used to encrypt another key)
    cnt   - Unencrypted content
    ecnt  - Encrypted   content
    kc    - KeyChain
    ck    - ChainKey

  Internal:
      key0  - Rand/user/password key (pre AKM, etc.)
      key1  - Key with AKM, etc.
      key2  - Final key ready for encryption/decryption
      key1b - Backup    key
     ekeyX  - Encrypted key

*config*clj

Tempel's behaviour is controlled by:
  1. Call   options, as provided to API functions.
  2. Config options, as provided in this dynamic map.

Config options (2) act as the default over which call options (1) will be merged.
So these are equivalent:

  (binding [*config* (merge *config* <your-opts>)]
    (encrypt-with-password ba-content password {}))

  (encrypt-with-password ba-content password <your-opts>)

Config options:

   Default values (*) should be sensible for most common use cases.

  `:hash-algo` ∈ #{:md5 :sha-1 *:sha-256 :sha-512}
    Hash algorithm used for internal HMACs, key derivation, etc.
    Default: `:sha-256`, there's usually no good reason to change this.
    Signing never uses `:md5` or `:sha-1`, these are upgraded to `:sha-256`.
    Signing with ML-DSA keys always uses `:sha-512`.
    Encrypting with `:md5` or `:sha-1` needs a 128-bit `:sym-cipher-algo`.

  `:pbkdf-algo` ∈ #{*:scrypt-r8p1-v1 :pbkdf2-hmac-sha-256-v1}
    Algorithm to use for password-based key stretching.
    Default: `:scrypt-r8p1-v1` when `com.lambdaworks.crypto.SCrypt` is available,
    or `:pbkdf2-hmac-sha-256-v1` otherwise.

    Terminology note: when Tempel uses the term `pbkdf` WITHOUT a version number
    like `pbkdf2`, it's referring to the general concept of ANY "Password-Based
    Key Derivation Function", and NOT any particular implementation (like the
    common PBKDF1 or PBKDF2 functions).

  `:pbkdf-nwf`
    ∈ #{:ref-10-msecs :ref-50-msecs *:ref-100-msecs :ref-200-msecs :ref-500-msecs
        :ref-1000-msecs :ref-2000-msecs :ref-5000-msecs <unsigned-short>}

    Normalized work factor (nwf) that describes how much computational effort
    should be used for password stretching when applying configured password
    stretching algorithm (see `:pbkdf-algo`).

    More effort means more resistance to brute-force attacks, but also more time
    and resources spent during normal operation.

    The `:ref-<num>-msecs` keywords take ~the described time on a 2020 M1
    MacBook Pro on a JVM with hardware SHA-256 (Java 21+ there), and PBKDF2
    ~10x longer on JVMs without it (e.g. Java 17 on Apple Silicon). Tempel
    raises these presets over time, so new writes may cost more after an
    upgrade. Numeric values pin the cost but are algorithm-specific (PBKDF2:
    iterations = 1024 x nwf, scrypt: N = 2^(nwf+1)), so set `:pbkdf-algo`
    explicitly with them. See `pbkdf-nwf-estimate`.

    Default: `:ref-100-msecs`, reasonable for many logins (PBKDF2: 693,248
    iterations, above OWASP's minimum of 600,000; scrypt: N=2^15, r=8, p=1).

  `:pbkdf-nwf-max` (relevant only when decrypting with a password)
    ∈ #{:ref-10-msecs :ref-50-msecs :ref-100-msecs :ref-200-msecs :ref-500-msecs
        :ref-1000-msecs :ref-2000-msecs :ref-5000-msecs}

    Optional upper limit on the envelope's password-stretching work factor,
    checked before any derivation. Only the `:ref-<num>-msecs` keywords are
    accepted since the envelope chooses the PBKDF algorithm, and numeric
    work factors differ between algorithms.

    Default: nil (accept any work factor supported by the algorithm).
    Set a limit appropriate to your resource budget when accepting untrusted
    envelopes, and also limit request size and concurrency.

  `:sym-cipher-algo` ∈ #{:aes-gcm-128-v1 *:aes-gcm-256-v1 :chacha20-poly1305-v1}
    The symmetric cipher algorithm to use. A cipher that supports "AEAD"
    (Authenticated Encryption with Associated Data) must generally be provided
    in order to use `:ba-aad` options (see `help:aad`).

    Default (since v1.3): `:aes-gcm-256-v1`, a good general-purpose symmetric
    cipher with AEAD support and a large security margin. The default before
    v1.3 was `:aes-gcm-128-v1`. Encrypted data names its cipher, so remains
    readable whatever this option.

    Data encrypted for an ML-KEM receiver key (or, in signed encryption,
    sender's copy key) needs a 256-bit AEAD cipher: `:aes-gcm-256-v1` or
    `:chacha20-poly1305-v1`. Other ciphers are upgraded to `:aes-gcm-256-v1`.
    An ML-KEM `:backup-key` on other data (e.g. password or symmetric-key)
    applies this to its own key wrap only.

  `:sig-algo` (relevant only when signing)
    ∈ #{*nil :sha-256-rsa :sha-512-rsa :sha-256-rsa-pss :sha-512-rsa-pss
        :sha-256-ecdsa :sha-512-ecdsa :ed25519 :ml-dsa-65 :ml-dsa-87
        :ml-dsa-65-ed25519}

    The signature algorithm to use. Must suit the signing key's algorithm.
    Default: nil, meaning `:sha-256-rsa` for RSA keys, `:sha-256-ecdsa`
    for EC keys, `:ed25519` for Ed25519 keys, and the matching
    `:ml-dsa-<n>` (or `:ml-dsa-65-ed25519`) for ML-DSA keys.

    The `-rsa-pss` algorithms may be preferred for RSA keys when policy
    requires RSA-PSS. NB older Tempel versions cannot verify them.

  `:keypair-creator` ∈ #{<function> <delay>}
    The function to use when generating asymmetric keypairs.
    See `keypair-create`, `keypair-creator` for details.

    Default: `default-keypair-creator_`, which uses up to 10% of threads
    to buffer up to 16 keypairs per type.

    This is often something you'll want to customize.

  `:symmetric-keys`
    Symmetric keys to add to new `KeyChain`s.
    See `keychain`, `keychain-add-missing-recommended-keys` for details.

    Default: a single random symmetric key.

  `:asymmetric-keypairs`
    Asymmetric keypairs to add to new `KeyChain`s, in order (each added
    key gets top priority, so later keys are preferred for writing).
    See `keychain`, `keychain-add-missing-recommended-keys` for details.

    Default (since v1.3): `[:dh-3072 :ml-kem-768-x25519 :ml-dsa-65-ed25519]`
      - `:ml-kem-768-x25519` (hybrid post-quantum) for encryption,
        confidential while either ML-KEM-768 or X25519 holds,
      - `:ml-dsa-65-ed25519` (hybrid post-quantum) for signing,
        unforgeable while either ML-DSA-65 or Ed25519 holds,
      - `:dh-3072` for (classical) `encrypt-with-2-keypairs`.

    Together these support all Tempel functionality. The post-quantum
    keys need JVM support (OpenJDK 17.0.21+, 21.0.13+, 25.0.4+, or 27+),
    creating them throws otherwise: Tempel never silently substitutes
    classical keys. For classical-only `KeyChain`s (e.g. for older JVMs
    or Tempel readers), use `[:rsa-3072 :dh-3072]` (the default before
    v1.3).

  `:embed-key-ids?` (relevant only when encrypting)
    Should key ids be embedded in encrypted output when using `KeyChain`s?
    This will allow the automatic selection of relevant keys during decryption,
    in exchange for leaking (making public) the ids used for encryption.

    This is often convenient, and *usually* safe unless you have custom key ids
    that contain private information and/or if it's important that you not leak
    information about which public `KeyChain`s might contain the necessary keys.

    Default: true.
    You may want to disable this for maximum security, but note that doing so
    may complicate decryption. See the Tempel Wiki for details.

  `:embed-hmac?` (relevant only when encrypting)
    Should an HMAC be embedded in encrypted output? When present, embedded
    HMACs can be checked on decryption to help verify data integrity and
    decryption key.

    Default: true.
    You'll generally want to keep this enabled unless you're trying to
    minimize the size of your encrypted output. Adds ~32 bytes to output when
    using the default `:sha-256` hash algorithm.

    Encrypted keychains and legacy CBC ciphers always include an HMAC,
    regardless of this option, and require it when decrypting.

  `:ignore-hmac?` (relevant only when decrypting)
    Should embedded HMAC be ignored when decrypting?

    Default: false.
    Keep this disabled unless you're sure you understand the implications.

    For trusted offline recovery only: this also permits reading legacy
    keychains/CBC data without an HMAC. Re-encrypt recovered data promptly.
    Decryption with an ML-KEM primary or backup key always checks the HMAC.

  `:require-hmac?` (relevant only when decrypting)
    Should data without an embedded HMAC be rejected when decrypting?

    Default: false, to support data written with `:embed-hmac? false`.
    Recommended if all your data was written with `:embed-hmac? true`
    (the default). Has no effect with `:ignore-hmac? true`.

    The HMAC also authenticates what's outside the encrypted content,
    including the kind of output. Without this option an attacker could
    remove the HMAC and (for example) have an encrypted keychain decrypted
    as ordinary data by code that uses the same key for both.

  `:require-pq?`
    When true, every public-key encryption or signature involved in an
    operation must use a post-quantum key (`:ml-kem-<n>`, `:ml-kem-768-x25519`,
    `:ml-dsa-<n>`, `:ml-dsa-65-ed25519`), else throws. This covers:
      - The receiver's key, any sender's copy, and the signature
        (incl. signed encryption, in every read role).
      - Any backup copy (see `:backup-key`), when writing, and when
        reading even if the copy isn't used. Password and symmetric-key
        encryption are otherwise unaffected.
      - `keychain-encrypt` with `:key-pub` (and `keychain-decrypt`).
    `encrypt-with-2-keypairs` and `decrypt-with-2-keypairs` (classical only)
    always throw.

    Writers use the highest-priority eligible post-quantum keys.
    Nested `:backup-opts` can't disable this option. Readers check the
    copies present in the data: detecting a removed copy needs an HMAC
    (`:require-hmac? true`).

    Default: false. When set in `*config*`, use call option
    `{:require-pq? false}` e.g. to read older classical data.

  `:backup-key`
    When encrypting:
      Encrypt data so that decryption will be possible with either the primary
      key/password, *OR* with this optional secondary (backup) `KeyChain`
      (see `keychain`) or `KeyPair` (see `keypair-create`).

      NB: this backup key will be able to decrypt *without* the per-call AKM
      (see `help:akm`). A global `:ba-akm` in `*config*` still applies to
      the backup copy of the key, so recovery needs the same global AKM
      (or none).

    When decrypting (call option only, ignored in `*config*`):
      Decrypt data that was encrypted with support for a backup key, using
      this `KeyChain` (see `keychain`) or `KeyPair` (see `keypair-create`)
      INSTEAD of the primary key/password, which must be nil or omitted:

        (decrypt-with-password ba-encrypted nil {:backup-key <key>})
        (keychain-decrypt      ba-encrypted     {:backup-key <key>})

      Anyone with the backup public key can create recoverable data.
      For signed encryption, `decrypt-signed-with-2-keypairs` also verifies
      the expected sender and receiver during recovery. For other
      envelopes, authenticate the sender separately when needed. Recovery
      cannot establish who knew the original password.
      Always authenticate backup public keys.

    Key algorithm must support use as an asymmetric cipher.
    Suitable algorithms: `:rsa-<nbits>`, `:x25519`, `:ml-kem-768`, `:ml-kem-1024`,
    `:ml-kem-768-x25519`. With an ML-KEM primary key, must be ML-KEM at least
    as strong, and hybrid if the primary is:
    `:ml-kem-768`        primary needs any ML-KEM backup,
    `:ml-kem-768-x25519` primary needs `:ml-kem-768-x25519` backup,
    `:ml-kem-1024`       primary needs `:ml-kem-1024` backup.
    With `:require-pq?`, must be ML-KEM for any primary.
    A backup `KeyChain` then uses its highest-priority such key.

  `:backup-opts`
    When encrypting: encryption opts map used with `:backup-key`.
    When decrypting: decryption opts map used with `:backup-key`.
source

as-baclj

(as-ba x)
(as-ba target-len x)
Returns a byte[] from given input:
  byte[]   -> byte[]
  string[] -> corresponding UTF-8 byte[]
  char[]   -> corresponding UTF-8 byte[]
  int      -> (byte-array <int>)
  seqable  -> (byte-array <seq>)

When `target-len` is provided, trim or zero-pad the returned array as necessary.
source

ba=clj

(ba= x y)
Returns true iff given two byte[]s with the same content.
source

chainkey?clj

(chainkey? x)
source

decrypt-keychainclj

(decrypt-keychain ba-encrypted-keychain
                  &
                  [{:keys [password key-sym key-prv return ba-akm backup-key
                           backup-opts ignore-hmac? pbkdf-nwf-max require-pq?]
                    :or {return :keychain}}])
Complement of `keychain-encrypt`.

Given a `ba-encrypted-keychain` byte[] as returned by `keychain-encrypt`,
and a password, symmetric key, or private key (`:key-prv`) - checks if
given password or key is correct.

If incorrect, returns nil. Throws on invalid options (e.g. `:ba-akm` type)
or data (e.g. missing HMAC, `:pbkdf-nwf-max` exceeded), or with a password:
on a missing optional dependency or JVM error.
If   correct, return value depends on `:return` option:
  `:keychain`   - Returns decrypted `KeyChain` (default)
  `:ba-content` - Returns decrypted byte[] content
  `:ba-aad`     - Returns verified unencrypted embedded ?byte[] AAD
  `:map`        - Returns {:keys [keychain ba-aad ba-content]} map

May instead be given a `:backup-key` (see `*config*`), throws if incorrect.
Throws on data that doesn't meet `:require-pq?` (see `*config*`).

See `keychain-encrypt` for details.
See Tempel Wiki for detailed usage info, common patterns, examples, etc.
source

decrypt-signed-with-2-keypairsclj

(decrypt-signed-with-2-keypairs ba-encrypted
                                {:keys [as-receiver as-sender backup-key from to
                                        sender-read-key return ba-akm
                                        backup-opts require-pq?]
                                 :or {return :ba-content}})
Complement of `encrypt-signed-with-2-keypairs`.

Decrypts the given byte[] and verifies that it was signed by the expected
sender for its intended receiver. Throws on any failure, and returns
nothing (not even AAD) unless verified.

Return value depends on `:return` option:
  `:ba-content` - Returns verified decrypted byte[] content (default)
  `:ba-aad`     - Returns verified unencrypted embedded ?byte[] AAD
  `:map`        - Returns {:keys [ba-aad ba-content]} map

Takes `KeyChain`s (see `keychain`) and/or `KeyPair`s (see `keypair-create`)
for exactly one of these roles:

  Receiver:
    (decrypt-signed-with-2-keypairs ba-enc
      {:as-receiver bob-keychain, :from alice-public-keychain})

    `:as-receiver` - Receiver's private key AND its public key (same
                     `KeyChain` entry or `KeyPair`). After rotation, keep
                     old entries (both keys) at lower priority to read
                     older data.
    `:from`        - Trusted public key/s for one expected sender.
                     A `KeyChain` accepts any of its signing keys (e.g.
                     after rotation). The result doesn't identify which
                     key signed.

  Sender (sender-readable data only):
    (decrypt-signed-with-2-keypairs ba-enc {:as-sender alice-keychain})
    (decrypt-signed-with-2-keypairs ba-enc
      {:as-sender alice-keychain, :to bob-public-keychain})
    (decrypt-signed-with-2-keypairs ba-enc
      {:as-sender alice-signing-public-key, :sender-read-key alice-encryption-keypair})

    `:as-sender`       - Sender's own public signature key/s, and (unless
                         `:sender-read-key` is given) the private AND
                         public key used for the sender's copy.
    `:sender-read-key` - Private AND public key used for the sender's copy.
    `:to`              - Optional receiver public key/s. When given, also
                         requires that the data is for one of them.

  Backup key recovery (see `:backup-key` in `*config*`):
    (decrypt-signed-with-2-keypairs ba-enc
      {:backup-key backup-keychain, :from alice-public-keychain, :to bob-public-keychain})

    Needs trusted public keys of both sender (`:from`) and receiver (`:to`).
    Doesn't need the per-call AKM (see `:backup-key` in `*config*`).

Only accepts output from `encrypt-signed-with-2-keypairs`.
Doesn't detect replays: include e.g. a unique id in content or AAD if needed.

A receiver could disclose the envelope's signature as evidence of authorship.

Options:
  Role options above are call options only (`:backup-key` in `*config*`
  is ignored when decrypting).

  `:ba-akm`      - See `help:akm`, needed by both receiver and sender
  `:backup-opts` - See `*config*`

  And see `*config*` for details: `require-pq?`.
source

decrypt-with-1-keypairclj

(decrypt-with-1-keypair ba-encrypted
                        receiver-key-prv
                        &
                        [{:keys [return ba-akm backup-key backup-opts
                                 ignore-hmac? require-hmac? require-pq?]
                          :or {return :ba-content}}])
Complement of `encrypt-with-1-keypair`.

Uses a hybrid (symmetric + asymmetric) scheme to decrypt the given byte[].
Return value depends on `:return` option:
  `:ba-content` - Returns decrypted byte[] content (default)
  `:ba-aad`     - Returns verified unencrypted embedded ?byte[] AAD
  `:map`        - Returns {:keys [ba-aad ba-content]} map

Takes a `KeyChain` (see `keychain`) or `KeyPair` (see `keypair-create`).
Key algorithm must support use as an asymmetric cipher.
Suitable algorithms: `:rsa-<nbits>`, `:x25519`, `:ml-kem-768`, `:ml-kem-1024`,
`:ml-kem-768-x25519` (hybrid, confidential while either ML-KEM or X25519 holds).

Encryption uses receiver's asymmetric public  key.
Decryption uses receiver's asymmetric private key.

ML-KEM data always needs a valid embedded HMAC (`:ignore-hmac?`
doesn't apply). Throws on data that doesn't meet `:require-pq?`
(see `*config*`), incl. when decrypting with `:backup-key`.

Will throw on decryption failure (bad key, etc.).
source

decrypt-with-2-keypairsclj

(decrypt-with-2-keypairs ba-encrypted
                         receiver-key-prv
                         sender-key-pub
                         &
                         [{:keys [return ba-akm backup-key backup-opts
                                  ignore-hmac? require-hmac?]
                           :or {return :ba-content}}])
Complement of `encrypt-with-2-keypairs`.

Uses a hybrid (symmetric + asymmetric) scheme to decrypt the given byte[].
Return value depends on `:return` option:
  `:ba-content` - Returns decrypted byte[] content (default)
  `:ba-aad`     - Returns verified unencrypted embedded ?byte[] AAD
  `:map`        - Returns {:keys [ba-aad ba-content]} map

Takes `KeyChain`s (see `keychain`) and/or `KeyPair`s (see `keypair-create`).
Key algorithm must support key agreement.
Suitable algorithms: `:dh-<nbits>`, `:ec-<curve>`, `:x25519`.

Encryption uses:
  - Receiver's asymmetric public  key
  - Sender's   asymmetric private key

Decryption uses:
  - Receiver's asymmetric private key
  - Sender's   asymmetric public  key

The sender can also decrypt, by instead giving their own private key and
the receiver's public key.

Throws with `:require-pq?` (classical only, see `*config*`).

Will throw on decryption failure (bad key, etc.).
source

decrypt-with-passwordclj

(decrypt-with-password ba-encrypted
                       password
                       &
                       [{:keys [return ba-akm backup-key backup-opts
                                ignore-hmac? require-hmac? require-pq?
                                pbkdf-nwf-max]
                         :or {return :ba-content}}])
Complement of `encrypt-with-password`.

Uses a symmetric cipher to decrypt the given byte[].
Return value depends on `:return` option:
  `:ba-content` - Returns decrypted byte[] content (default)
  `:ba-aad`     - Returns verified unencrypted embedded ?byte[] AAD
  `:map`        - Returns {:keys [ba-aad ba-content]} map

Takes a password (string, char[], or UTF-8 byte[]). Password will be "stretched"
using an appropriate "Password-Based Key Derivation Function" (PBKDF).

Will throw on decryption failure (bad password, etc.).
source

decrypt-with-symmetric-keyclj

(decrypt-with-symmetric-key ba-encrypted
                            key-sym
                            &
                            [{:keys [return ba-akm backup-key backup-opts
                                     ignore-hmac? require-hmac? require-pq?]
                              :or {return :ba-content}}])
Complement of `encrypt-with-symmetric-key`.

Uses a symmetric cipher to decrypt the given byte[].
Return value depends on `:return` option:
  `:ba-content` - Returns decrypted byte[] content (default)
  `:ba-aad`     - Returns verified unencrypted embedded ?byte[] AAD
  `:map`        - Returns {:keys [ba-aad ba-content]} map

Takes a `KeyChain` (see `keychain`) or byte[] key.
Will throw on decryption failure (bad key, etc.).
source

default-configclj

Default initial value for `*config*`.
source

default-keypair-creator_clj

Default stateful `KeyPair` generator with options:
{:buffer-len 16, :n-threads [:perc 10]}
source

encrypt-keychainclj

(encrypt-keychain keychain
                  &
                  [{:keys [password key-sym key-pub ba-content ba-aad ba-akm
                           hash-algo sym-cipher-algo pbkdf-algo pbkdf-nwf
                           embed-key-ids? embed-hmac? backup-key backup-opts
                           require-pq?]}])
Given a `KeyChain` and password, symmetric key, or public key, returns
a byte[] that includes:

  - Encrypted:
    - The entire keychain
    - Optional other content (see `ba-content` option below)

  - Unencrypted:
    - Any public keys in keychain (retrieve with `public-data`)
    - Optional AAD (see `help:aad`)
    - Envelope data necessary for decryption (specifies algorithms, etc.)

Output can be safely stored (e.g. in a database).
Decrypt output with: `keychain-decrypt`.

See Tempel Wiki for detailed usage info, common patterns, examples, etc.

Options:
  `:password`   - String, char[], or UTF-8 byte[]       as with `encrypt-with-password`
  `:key-sym`    - `KeyChain` (see `keychain`) or byte[] as with `encrypt-with-symmetric-key`
  `:key-pub`    - `KeyChain` or `KeyPair`               as with `encrypt-with-1-keypair`
                  (decrypt with `:key-prv`). With an ML-KEM key the outer
                  envelope also uses its profile (see `encrypt-with-1-keypair`).

  `:ba-aad`     - See `help:aad`
  `:ba-akm`     - See `help:akm`
  `:ba-content` - Optional additional byte[] content that should be encrypted
                  and included in output for retrieval with `keychain-decrypt`.

  And see `*config*` for details:
    `hash-algo`, `sym-cipher-algo`, `pbkdf-algo`, `pbkdf-nwf`,
    `embed-key-ids?`, `embed-hmac?`, `backup-key`, `backup-opts`,
    `require-pq?`.
source

encrypt-signed-with-2-keypairsclj

(encrypt-signed-with-2-keypairs ba-content
                                {:keys [from to sender-readable? sender-read-key
                                        ba-aad ba-akm hash-algo sym-cipher-algo
                                        sig-algo embed-key-ids? backup-key
                                        backup-opts require-pq?]})
Signs the given content byte[] for an intended receiver, then encrypts it
so that only that receiver, the sender (by default), and any configured
`:backup-key` can decrypt it. Returns a byte[] that includes:
  - The encrypted content and sender's signature
  - Optional unencrypted AAD (see `help:aad`)
  - Envelope data necessary for decryption (specifies algorithms, etc.)

Naming note: always involves 2 parties (sender, receiver), but uses a 3rd
keypair (the sender's encryption key) when `:sender-readable?` is true
(the default). Callers typically just provide 2 `KeyChain`s, and the
relevant keys get used.

Takes `KeyChain`s (see `keychain`) and/or `KeyPair`s (see `keypair-create`):
  `:from` - Sender's private key AND its public key (same `KeyChain` entry
            or `KeyPair`), with signature support:
            `:rsa-<nbits>`, `:ec-<curve>`, `:ed25519`, `:ml-dsa-65`, `:ml-dsa-87`,
            `:ml-dsa-65-ed25519`.
  `:to`   - Receiver's public key, with asymmetric cipher support:
            `:rsa-<nbits>`, `:x25519`, `:ml-kem-768`, `:ml-kem-1024`, `:ml-kem-768-x25519`.

Uses the highest-priority suitable keys, so algorithms may mix (e.g. an
`:ml-kem-768` receiver with an `:rsa-<nbits>` sender). Throws if the
sender's highest-priority signing key lacks its public key. See
`:require-pq?` in `*config*`.

Sender's copy (`:sender-readable?`, default true):
  The sender can also decrypt the same output, via the highest-priority
  public encryption key (asymmetric cipher support) in `:sender-read-key`
  when given, else in `:from`. Keep only the sender's own keys in
  `:from`. The private key for reading may be kept elsewhere.
  With an ML-KEM receiver, this key follows the `:backup-key` rule (see `*config*`).
  Throws if there's no suitable key, rather than omit the copy. ML-DSA keys
  can't encrypt, so post-quantum senders need a separate ML-KEM key.

The signature covers the content, AAD, AKM (without revealing it),
algorithms, key wraps, and the identities of the sender's, receiver's,
and sender copy's public keys. So, for example, the receiver can't
readdress it to someone else.

Decrypt and verify output with `decrypt-signed-with-2-keypairs`:

  ;; Alice signs and encrypts for Bob, keeping her own copy
  (encrypt-signed-with-2-keypairs ba-content
    {:from alice-keychain, :to bob-public-keychain})

  ;; Without a copy for Alice, saving its cost: one extra key wrap
  ;; (~1.2KB with the default hybrid `:ml-kem-768-x25519` key)
  (encrypt-signed-with-2-keypairs ba-content
    {:from alice-keychain, :to bob-public-keychain, :sender-readable? false})

  ;; Direct keys
  (encrypt-signed-with-2-keypairs ba-content
    {:from alice-ml-dsa-keypair, :to bob-ml-kem-public-key,
     :sender-read-key alice-ml-kem-public-key})

Compare:
  `encrypt-with-1-keypair`  - Only receiver can decrypt, sender unauthenticated.
  `encrypt-with-2-keypairs` - Either party can create and decrypt (classical only).
  `sign`                    - Authenticity without encryption.

Options:
  `:from`             - See above, required
  `:to`               - See above, required
  `:sender-readable?` - See above, default true
  `:sender-read-key`  - See above

  `:ba-aad` - See `help:aad`, also signed
  `:ba-akm` - See `help:akm`, bound by the signature but not revealed

  Options above are call options only, except `:ba-aad` and `:ba-akm`.
  And see `*config*` for details:
    `hash-algo`, `sym-cipher-algo`, `sig-algo`,
    `embed-key-ids?`, `backup-key`, `backup-opts`, `require-pq?`.

  `:embed-key-ids?` embeds the receiver's key id. Sender key ids are
  never public. An HMAC is always embedded. ML-KEM keys use the ML-KEM
  profile (see `encrypt-with-1-keypair`). The receiver's key is the
  primary for `:backup-key`.
source

encrypt-with-1-keypairclj

(encrypt-with-1-keypair ba-content
                        receiver-key-pub
                        &
                        [{:keys [ba-aad ba-akm hash-algo sym-cipher-algo
                                 embed-key-ids? embed-hmac? backup-key
                                 backup-opts require-pq?]}])
Uses a symmetric or hybrid (symmetric + asymmetric) scheme to encrypt the
given content byte[] and return a byte[] that includes:
  - The encrypted content
  - Optional unencrypted AAD (see `help:aad`)
  - Envelope data necessary for decryption (specifies algorithms, etc.)

Takes a `KeyChain` (see `keychain`) or `KeyPair` (see `keypair-create`).
Key algorithm must support use as an asymmetric cipher.
Suitable algorithms: `:rsa-<nbits>`, `:x25519`, `:ml-kem-768`, `:ml-kem-1024`,
`:ml-kem-768-x25519` (hybrid, confidential while either ML-KEM or X25519 holds).

ML-KEM keys (`:ml-kem-<n>`, `:ml-kem-768-x25519`; need JVM support, see
`keychain`) always use a 256-bit AEAD cipher (`:aes-gcm-256-v1` or
`:chacha20-poly1305-v1`, other ciphers are upgraded to
`:aes-gcm-256-v1`), `:sha-256` (or `:sha-512` when configured), and an
embedded HMAC. Any `:backup-key` must then be ML-KEM (see `*config*`).

Encryption uses receiver's asymmetric public  key.
Decryption uses receiver's asymmetric private key.

Decrypt output byte[] with: `decrypt-with-1-keypair`.
To let the receiver verify who sent the message, use `encrypt-signed-with-2-keypairs`.

Options:
  `:ba-aad` - See `help:aad`
  `:ba-akm` - See `help:akm`

  And see `*config*` for details:
    `hash-algo`, `sym-cipher-algo`,
    `embed-key-ids`, `backup-key`, `backup-opts`, `require-pq?`.
source

encrypt-with-2-keypairsclj

(encrypt-with-2-keypairs ba-content
                         receiver-key-pub
                         sender-key-prv
                         &
                         [{:keys [ba-aad ba-akm hash-algo ka-algo
                                  sym-cipher-algo embed-key-ids? embed-hmac?
                                  backup-key backup-opts]}])
Uses a hybrid (symmetric + asymmetric) scheme to encrypt the given content
byte[] and return a byte[] that includes:
  - The encrypted content
  - Optional unencrypted AAD (see `help:aad`)
  - Envelope data necessary for decryption (specifies algorithms, etc.)

Takes `KeyChain`s (see `keychain`) and/or `KeyPair`s (see `keypair-create`).
Key algorithm must support key agreement.
Suitable algorithms: `:dh-<nbits>`, `:ec-<curve>`, `:x25519`.

Encryption uses:
  - Receiver's asymmetric public  key
  - Sender's   asymmetric private key

Decryption uses:
  - Receiver's asymmetric private key
  - Sender's   asymmetric public  key

Decrypt output byte[] with: `decrypt-with-2-keypairs`.
This is static key agreement: either participant can create messages, and
compromise of either private key exposes past messages (no forward secrecy).
Authenticate peer public keys and bind sender/receiver roles in AAD when needed.
For a message the receiver can verify was signed by its sender (including
with post-quantum keys), see `encrypt-signed-with-2-keypairs`.

Options:
  `:ba-aad` - See `help:aad`
  `:ba-akm` - See `help:akm`

  And see `*config*` for details:
    `hash-algo`, `ka-algo`, `sym-cipher-algo`,
    `embed-key-ids?`, `backup-key`, `backup-opts`.
    Throws with `:require-pq?` (classical only).
source

encrypt-with-passwordclj

(encrypt-with-password ba-content
                       password
                       &
                       [{:keys [ba-aad ba-akm hash-algo sym-cipher-algo
                                pbkdf-algo pbkdf-nwf embed-key-ids? embed-hmac?
                                backup-key backup-opts]}])
Uses a symmetric cipher to encrypt the given byte[] content and return
a byte[] that includes:
  - The encrypted content
  - Optional unencrypted AAD (see `help:aad`)
  - Envelope data necessary for decryption (specifies algorithms, etc.)

Takes a password (string, char[], or UTF-8 byte[]).
Password will be "stretched" using an appropriate "Password-Based Key
Derivation Function" (PBKDF).

Decrypt output with: `decrypt-with-password`.

Options:
  `:ba-aad` - See `help:aad`
  `:ba-akm` - See `help:akm`

  And see `*config*` for details:
    `hash-algo`, `sym-cipher-algo`, `pbkdf-algo`, `pbkdf-nwf`,
    `embed-key-ids?`, `embed-hmac?`, `backup-key`, `backup-opts`,
    `require-pq?`.
source

encrypt-with-symmetric-keyclj

(encrypt-with-symmetric-key ba-content
                            key-sym
                            &
                            [{:keys [ba-aad ba-akm hash-algo sym-cipher-algo
                                     embed-key-ids? embed-hmac? backup-key
                                     backup-opts]}])
Uses a symmetric cipher to encrypt the given byte[] content and return
a byte[] that includes:
  - The encrypted content
  - Optional unencrypted AAD (see `help:aad`)
  - Envelope data necessary for decryption (specifies algorithms, etc.)

Takes a `KeyChain` (see `keychain`) or byte[] key.
Decrypt output with: `decrypt-with-symmetric-key`.

Options:
  `:ba-aad` - See `help:aad`
  `:ba-akm` - See `help:akm`

  And see `*config*` for details:
    `hash-algo`, `sym-cipher-algo`, `embed-key-ids?`,
    `backup-key`, `backup-opts`, `require-pq?`.
source

help:aadclj

"Additional Authenticated Data" (AAD) is optional arbitrary byte[] data that
may be provided to many of Tempel's API functions (e.g. `encrypt-with-X` when
using an AEAD cipher).

When provided, AAD will be embedded *UNENCRYPTED* with the API function's
output byte[].

It may then later be retrieved:
  - Without verification: using `public-data` (see its docstring for details).
  - With    verification: using the appropriate complementary API function
                          (e.g. `decrypt-with-X`).

Verification in this context means confirmation of:
  1. Data integrity (the data is intact, and unmodified)
  2. Authenticity (the data was indeed created/signed/etc. by the expected key).

Examples of common AAD content:
  - Metadata like the sender, receiver, timestamp, etc.
  - Routing information
  - A description of the encrypted content
  - File or data integrity checks (hashes, etc.)
  - Cryptographic signatures
  - Arbitrary Clojure data via Nippy, Ref. <https://www.taoensso.com/nippy>
source

help:akmclj

"Additional Keying Material" (AKM) is optional arbitrary byte[] data that
may be provided to many of Tempel's API functions (e.g. `encrypt-with-X`).

When provided, AKM will act as additional secret material to supplement any
main cryptographic keys, and so enhance security through increased resistance
to certain types of attacks, etc.

When an AKM is provided to an API function (e.g. `encrypt-with-X`), the same
AKM *must* be provided to the function's complement (e.g. `decrypt-with-X`).

In some contexts, an AKM may also be known as "Shared Keying Material" (SKM).

Examples of common AKM content:
  - Metadata like the sender and receiver of an encrypted message
  - Random numbers or Nonces stored or transmitted separately
  - Key derivation parameters
  - Protocol-specific values
  - Security credentials or certificates
  - Arbitrary Clojure data via Nippy, Ref. <https://www.taoensso.com/nippy>
source

keychainclj

(keychain &
          [{:keys [empty? only? symmetric-keys asymmetric-keypairs
                   keypair-creator]}])
Returns a new `KeyChain` with key/pairs as specified by options:
  `:symmetric-keys`      - Seq of keys     given to `keychain-add-symmetric-key`
  `:asymmetric-keypairs` - Seq of keypairs given to `keychain-add-asymmetric-keypair`

Supplied options override the corresponding `*config*` values.
Keys are added in order, each with top priority, so later keys are
preferred for writing (encryption, signing).

Common recipes:

  ;; Default (since v1.3): symmetric key, DH, and hybrid post-quantum
  ;; ML-KEM-768 + X25519 (for encryption), ML-DSA-65 + Ed25519 (for signing).
  ;; Needs JVM support for post-quantum keys (OpenJDK 17.0.21+, 21.0.13+,
  ;; 25.0.4+, or 27+), else throws.
  (keychain)

  ;; Classical-only (the default before v1.3), e.g. for older JVMs,
  ;; or when older Tempel versions need to read the `KeyChain`:
  (keychain {:asymmetric-keypairs [:rsa-3072 :dh-3072]})

  ;; Without classical `encrypt-with-2-keypairs` support:
  (keychain {:asymmetric-keypairs [:ml-kem-768-x25519 :ml-dsa-65-ed25519]})

Pure `:ml-kem-<n>` and `:ml-dsa-<n>` (no X25519 or Ed25519) are also
available, e.g. `:ml-kem-1024` with `:ml-dsa-87` for a larger post-quantum
margin.
To upgrade an existing `KeyChain`, see `keychain-add-missing-recommended-keys`.

Options:
  `:empty?` - When truthy, returns a `KeyChain` without any keys
  `:only?`  - When truthy, returns a `KeyChain` with keys ONLY as
              specified in call options (ignores any keys specified in `*config*`)

  And see `*config*` for details:
    `symmetric-keys`, `asymmetric-keypairs`, `keypair-creator`.
source

keychain-add-asymmetric-keypairclj

(keychain-add-asymmetric-keypair keychain
                                 x-keypair
                                 &
                                 [{:keys [key-id priority return]
                                   :or {return :keychain}}])
Produces a ?new `KeyChain` that contains the given asymmetric keypair.

`x-keypair` may be an algorithm keyword (see `keypair-create`),
a `java.security.KeyPair`, or a map with {:keys [key-prv key-pub]}.

New keys will by default get top priority, override with `:priority` option.

Return value depends on `:return` option:
  `:keychain` - Returns (possibly new) `KeyChain` (default)
  `:map`      - Returns {:keys [keychain changed? key-id]}

  And see `*config*` for details:
    `keypair-creator`.
source

(keychain-add-missing-recommended-keys
  keychain
  &
  [{:keys [symmetric-keys asymmetric-keypairs keypair-creator return]}])
Returns a ?new `KeyChain` with any missing recommended key types added
(e.g. to upgrade an owner `KeyChain` created by an older Tempel version),
or the given `KeyChain` when nothing's missing.

Recommended types are what `keychain` would create from `:symmetric-keys`
and `:asymmetric-keypairs` (call options over `*config*`), which must be
generation templates (e.g. `:random`, `:ml-kem-768`).

A type is present when the `KeyChain` has:
  - Symmetric: a key at least as long as the longest template.
  - Asymmetric: a complete (private AND public) keypair of the same algo,
    or of an at least as strong post-quantum algo of the same family
    (e.g. `:ml-kem-1024` or `:ml-kem-768-x25519` for `:ml-kem-768`).
    So a pure ML-KEM or ML-DSA keypair at least as strong counts as present
    for `:ml-kem-768-x25519` or `:ml-dsa-65-ed25519`: to move to the hybrid,
    add it with `keychain-add-asymmetric-keypair`.

New post-quantum and symmetric keys get priority above all existing keys,
new classical keys below them, each in configured order (later = preferred).
Existing keys keep their ids and relative priorities.

Throws for a `KeyChain` without secret keys (e.g. a public one), or when
any key can't be created (e.g. post-quantum keys without JVM support),
never adding only some.

With `{:return :map}`, returns {:keys [keychain changed? key-ids]}, with
new key ids in template order.

Persist the new private `KeyChain` before publishing its new public keys.

And see `*config*` for details:
  `symmetric-keys`, `asymmetric-keypairs`, `keypair-creator`.
source

keychain-add-symmetric-keyclj

(keychain-add-symmetric-key keychain
                            x-key
                            &
                            [{:keys [key-id priority return]
                              :or {return :keychain}}])
Produces a ?new `KeyChain` that contains the given symmetric key.

`x-key` may be: `:random`, byte[] of length >= 32, or {:keys [key-sym]} map.
New keys will by default get top priority, override with `:priority` option.

Return value depends on `:return` option:
  `:keychain` - Returns (possibly new) `KeyChain` (default)
  `:map`      - Returns {:keys [keychain changed? key-id]}
source

keychain-decryptclj

(keychain-decrypt ba-encrypted-keychain
                  &
                  [{:keys [password key-sym key-prv return ba-akm backup-key
                           backup-opts ignore-hmac? pbkdf-nwf-max require-pq?]
                    :or {return :keychain}}])
Complement of `keychain-encrypt`.

Given a `ba-encrypted-keychain` byte[] as returned by `keychain-encrypt`,
and a password, symmetric key, or private key (`:key-prv`) - checks if
given password or key is correct.

If incorrect, returns nil. Throws on invalid options (e.g. `:ba-akm` type)
or data (e.g. missing HMAC, `:pbkdf-nwf-max` exceeded), or with a password:
on a missing optional dependency or JVM error.
If   correct, return value depends on `:return` option:
  `:keychain`   - Returns decrypted `KeyChain` (default)
  `:ba-content` - Returns decrypted byte[] content
  `:ba-aad`     - Returns verified unencrypted embedded ?byte[] AAD
  `:map`        - Returns {:keys [keychain ba-aad ba-content]} map

May instead be given a `:backup-key` (see `*config*`), throws if incorrect.
Throws on data that doesn't meet `:require-pq?` (see `*config*`).

See `keychain-encrypt` for details.
See Tempel Wiki for detailed usage info, common patterns, examples, etc.
source

keychain-encryptclj

(keychain-encrypt keychain
                  &
                  [{:keys [password key-sym key-pub ba-content ba-aad ba-akm
                           hash-algo sym-cipher-algo pbkdf-algo pbkdf-nwf
                           embed-key-ids? embed-hmac? backup-key backup-opts
                           require-pq?]}])
Given a `KeyChain` and password, symmetric key, or public key, returns
a byte[] that includes:

  - Encrypted:
    - The entire keychain
    - Optional other content (see `ba-content` option below)

  - Unencrypted:
    - Any public keys in keychain (retrieve with `public-data`)
    - Optional AAD (see `help:aad`)
    - Envelope data necessary for decryption (specifies algorithms, etc.)

Output can be safely stored (e.g. in a database).
Decrypt output with: `keychain-decrypt`.

See Tempel Wiki for detailed usage info, common patterns, examples, etc.

Options:
  `:password`   - String, char[], or UTF-8 byte[]       as with `encrypt-with-password`
  `:key-sym`    - `KeyChain` (see `keychain`) or byte[] as with `encrypt-with-symmetric-key`
  `:key-pub`    - `KeyChain` or `KeyPair`               as with `encrypt-with-1-keypair`
                  (decrypt with `:key-prv`). With an ML-KEM key the outer
                  envelope also uses its profile (see `encrypt-with-1-keypair`).

  `:ba-aad`     - See `help:aad`
  `:ba-akm`     - See `help:akm`
  `:ba-content` - Optional additional byte[] content that should be encrypted
                  and included in output for retrieval with `keychain-decrypt`.

  And see `*config*` for details:
    `hash-algo`, `sym-cipher-algo`, `pbkdf-algo`, `pbkdf-nwf`,
    `embed-key-ids?`, `embed-hmac?`, `backup-key`, `backup-opts`,
    `require-pq?`.
source

keychain-freeze-publicclj

(keychain-freeze-public keychain)
Takes a `KeyChain` and serializes any public keys it contains
to a storable byte[]. Returns the byte[].

Thaw (deserialize) output with: `keychain-thaw-public`.
source

keychain-normalize-prioritiesclj

(keychain-normalize-priorities keychain)
Returns a ?new `KeyChain` with key priorities normalized
to their relative rank order:
  {"a" {:priority -3}, "b" {:priority 8}} =>
  {"a" {:priority  0}, "b" {:priority 1}}
source

keychain-removeclj

(keychain-remove keychain
                 key-id
                 &
                 [{:keys [keep-private?] :or {keep-private? true}}])
Returns a ?new `KeyChain` with the identified key removed.
Options:
  `:keep-private?` - Should only the public component of keypairs
                     be removed? (Default true)
source

keychain-thaw-publicclj

(keychain-thaw-public ba-kc-pub)
Complement of `keychain-freeze-public`.
Takes a serialized byte[] of public keys and returns
a `KeyChain` that contains those public keys.
source

keychain-update-priorityclj

(keychain-update-priority keychain key-id update-fn)
Returns a ?new `KeyChain` with the identified key's
`:priority` updated to be (update-fn <old-priority>).

Priority values can be any integer, positive or negative. But to
encrypt or freeze a `KeyChain` they must be ∈ℕ[0, 65535], see
`keychain-normalize-priorities`. Default priority is zero.

When multiple keys in a `KeyChain` are appropriate for a
task, the key with highest priority (biggest int) will be
selected.
source

keychain?clj

(keychain? x)
source

keypair-createclj

(keypair-create key-algo)
(keypair-create key-algo needs)
Generates and returns a new `java.security.KeyPair` for given
`key-algo` ∈ #{:rsa :rsa-<nbits> :dh :dh-<nbits> :ec-<curve> :x25519 :ed25519
               :ml-kem-768 :ml-kem-1024 :ml-kem-768-x25519
               :ml-dsa-65 :ml-dsa-87 :ml-dsa-65-ed25519}.

`:ml-kem-768-x25519` is a hybrid of ML-KEM-768 and X25519 (both freshly
generated), confidential while either holds. `:ml-dsa-65-ed25519` is a
hybrid of ML-DSA-65 and Ed25519 (likewise), unforgeable while either holds.
ML-KEM and ML-DSA keys need JVM support, see `keychain`.

Slow! Consider instead using `keypair-creator`.
source

keypair-creatorclj

(keypair-creator &
                 [{:keys [buffer-len n-threads]
                   :or {buffer-len 16 n-threads [:perc 10]}}])
Returns a stateful (fn keypair-get [key-algo]) like `keypair-create` that
eagerly pre-computes keypairs of all previously-requested algos.

Compare:
  (keypair-create :rsa-2048) ; Slow, keypair generated on demand
  ;; vs
  (defonce kpc (keypair-creator {:buffer-len 128, :n-threads [:perc 10]}))
  (kpc :rsa-2048) ; Slow first call, keypair generated on demand
  (kpc :rsa-2048) ; Fast subsequent calls, will use cache of up to
                  ; 128 pre-generated keypairs

Cache isn't used within `with-srng`, etc.
source

pbkdf-nwf-estimateclj

(pbkdf-nwf-estimate pbkdf-algo bench-spec msecs-target-or-targets)
(pbkdf-nwf-estimate bench-spec kfn sfn nwf-to-probe msecs-target-or-targets)
Returns normalized work factor (nwf) estimate/s for which pbkdf runtime best
matches given msecs target/s on the current system:

  (pbkdf-nwf-estimate :pbkdf2-hmac-sha-256-v1 [2 3] 200) =>
    Runs pbkdf2 a total of 2x3=6 times to estimate the normalized
    work factor that yields a ~200 msec runtime on the current system.

Expensive!! Don't use in production.
Used internally to help generate reference `nwf` consts:
  `:ref-10-msecs`, `:ref-100-msecs`, etc.
source

public-dataclj

(public-data ba-tempel-output)
Given an encrypted Tempel byte[], returns a map of *UNVERIFIED* public
(unencrypted) data embedded in the byte[].

Possible keys:
  `:ba-aad`          - See `help:aad`
  `:keychain`        - Public-key part of encrypted `KeyChain`
  `:key-id`          - See `:embed-key-ids?` option of `encrypt-X` API
  `:receiver-key-id` - ''
  `:sender-key-id`   - ''
  `:has-hmac?`       - Does data have embedded HMAC?
  `:has-backup-key?` - Can data be decrypted with a secondary (backup) key?
  `:sender-readable?` - Can data be decrypted by its sender? (signed encryption)
  `:key-algo`        - ∈ #{:rsa-<nbits> :dh-<nbits> :ec-<curve> :x25519 :ed25519 :ml-kem-<n> :ml-kem-768-x25519 :ml-dsa-<n> :ml-dsa-65-ed25519}
  `:version`         - Integer version of data format (1, 2, etc.).
  `:kind`            - ∈ #{:encrypted-with-symmetric-key
                           :encrypted-with-password
                           :encrypted-with-1-keypair
                           :encrypted-with-2-keypairs
                           :encrypted-signed-with-2-keypairs
                           :encrypted-keychain
                           :signed}

NB: provides *UNVERIFIED* data that could be corrupted or forged!
For cryptographically verified data, use the appropriate API function
(e.g. `decrypt-X`) instead.
source

rand-baclj

(rand-ba len)
Returns secure random byte[] of given length:
(rand-ba 32) => random 32 byte (256 bit) byte[].
source

rate-limiterclj

(rate-limiter spec)
(rate-limiter opts spec)
Takes limit spec and returns stateful (fn a-rate-limiter [] [req-id] [command req-id]).
Spec forms:
  * Vec: [   [n msecs-window] ...] ; e.g.           [[2 (enc/msecs :hours 1)] ...]
  * Map: {id [n msecs-window] ...} ; e.g.  {"2/1h" [2 (enc/msecs :hours 1)] ...}
  * Set: #{"<n>/<n><s|m|h|d|w>"} ; e.g. #{"2/1h" ...}

Call the returned limiter fn with a request id (any Clojure value!) to
enforce limits independently for each id.

For example, (limiter-fn <ip-address-string>) will return:
  - Falsey when    allowed (all limits pass for given IP), or
  - Truthy when disallowed (any limits fail for given IP):
    [<worst-limit-id> <worst-backoff-msecs> {<limit-id> <backoff-msecs>}]

Or call the returned limiter fn with an extra command argument:
  (limiter-fn :rl/peek  <req-id>) - Check limits WITHOUT incrementing count
  (limiter-fn :rl/reset <req-id>) - Reset all limits for given req-id
source

signclj

(sign ba-content
      signer-key-prv
      &
      [{:keys [ba-aad ba-akm embed-content? hash-algo sig-algo embed-key-ids?
               require-pq?]
        :or {embed-content? true}}])
Cryptographically signs the given content byte[] and returns a byte[]
that includes:
  - Optional unencrypted content (see `embed-content?` option below)
  - Optional unencrypted AAD     (see `help:aad`)
  - Envelope data necessary for verification (specifies algorithms, etc.)

Produces:
  - Signed content when `embed-content?` is true (default)
  - A signature    when `embed-content?` is false

Takes a `KeyChain` (see `keychain`) or `KeyPair` (see `keypair-create`).
Key algorithm must support signatures.
Suitable algorithms: `:rsa-<nbits>`, `:ec-<curve>`, `:ed25519`, `:ml-dsa-65`, `:ml-dsa-87`,
`:ml-dsa-65-ed25519` (hybrid, unforgeable while either ML-DSA-65 or Ed25519 holds).

`:ml-dsa-<n>` and `:ml-dsa-65-ed25519` (post-quantum) need JVM support, see
`keychain`. NB older Tempel versions cannot verify them.

Signing      uses signer's asymmetric private key.
Verification uses signer's asymmetric public  key.

Verify with: `signed`.

Options:
  `:ba-aad`         - See `help:aad`
  `:ba-akm`         - See `help:akm`
  `:embed-content?` - See usage info above

  And see `*config*` for details:
    `hash-algo`, `sig-algo`, `embed-key-ids?`, `require-pq?`.
    Signing never uses `:md5` or `:sha-1`, these are upgraded to `:sha-256`.
    ML-DSA keys (incl. hybrid) always use `:sha-512`.
source

signedclj

(signed ba-signed
        signer-key-pub
        &
        [{:keys [ba-content return ba-akm require-pq?] :or {return :map}}])
Complement of `sign`.

Cryptographically verifies if the given signed byte[] was signed by the
private key corresponding to the given public key.

Return value depends on `:return` option:
  `:ba-content` - Returns verified ?byte[] content (see below)
  `:ba-aad`     - Returns verified ?byte[] AAD     (when embedded)
  `:map`        - Returns {:keys [ba-aad ba-content]} map (default)

Returns nil when verification fails. Unsupported envelope algorithms,
including MD5/SHA-1 prehashes, throw.

The content verified and returned is the `:ba-content` option when given
(needed when signed with `:embed-content? false`), otherwise the embedded
content. Any embedded content is ignored when `:ba-content` is given.

Takes a `KeyChain` (see `keychain`) or `KeyPair` (see `keypair-create`).
Key algorithm must support signatures.
Suitable algorithms: `:rsa-<nbits>`, `:ec-<curve>`, `:ed25519`, `:ml-dsa-65`, `:ml-dsa-87`,
`:ml-dsa-65-ed25519`.

Signed data specifies its own algorithms. Throws on data that doesn't
meet `:require-pq?` (see `*config*`).

Signing      uses signer's asymmetric private key.
Verification uses signer's asymmetric public  key.
source

str->utf8-baclj

(str->utf8-ba s)
Returns UTF-8 encoded byte[] for given String.
source

utf8-ba->strclj

(utf8-ba->str ba)
Returns String for given UTF-8 encoded byte[].
source

with-min-runtimecljmacro

(with-min-runtime msecs form)
Executes form and ensures that at least the given number of milliseconds
have elapsed before returning result. Can be useful for protection against
timing attacks, etc:
  (with-min-runtime 2000 <variable-time-form>)
source

with-min-runtime*clj

(with-min-runtime* msecs f)
Executes (f) and ensures that at least the given number of milliseconds
have elapsed before returning result. Can be useful for protection against
timing attacks, etc.:
  (with-min-runtime* 2000 (fn variable-time-fn [] <...>))
source

with-srngcljmacro

(with-srng instance-fn & body)
Evaluates body with given (instance-fn) used as sole source of
randomness in Tempel.

(instance-fn) should return a `java.security.SecureRandom` instance.
source

with-srng-insecure-deterministic!!!cljmacro

(with-srng-insecure-deterministic!!! long-seed & body)
Evaluates body with *INSECURE* deterministic `java.util.Random` used
as sole source of randomness in Tempel.

Never use when encrypting real data, etc. Provided only for testing.
source

cljdoc builds & hosts documentation for Clojure/Script libraries

Keyboard shortcuts
Ctrl+kJump to recent docs
←Move to previous article
→Move to next article
Ctrl+/Jump to the search field
× close