# Official application cryptography — ABI 1.12

The `CRYPTO-OFFICIAL-02` module adds byte-oriented authenticated encryption,
signatures, derivation, recipient encryption and encrypted key custody to the
official runtime. It uses the existing OpenSSL dependency. Existing
`SECURERANDOM`, `PASSWORDHASH`, `PASSWORDVERIFY` and `SHA256` implementations,
identifiers and return formats remain unchanged.

The machine-readable interface is `contracts/crypto_v2.json`. New builtins have
IDs 138–151. They require ABI 1.12; they do not introduce a new `TLValue` kind or
change its layout. The new algorithms are runtime facilities, not a complete
Infinetus transfer, device-trust or authorization protocol.

## Byte and ownership contract

All byte inputs and outputs use an `ARRAY` whose elements are **INTEGER 0..255**.
An empty ARRAY is a valid zero-length message. Embedded zero and every byte value
are preserved. STRING, NUMBER, LOGICAL, negative integers, integers above 255
and nested arrays are rejected; nothing is silently coerced to a byte. Text
must be encoded explicitly by the application before cryptographic processing.

| Value | Limit |
| --- | --- |
| Plaintext, signing message, HKDF input material | 1,048,576 bytes |
| AEAD/HPKE ciphertext including tag | 1,048,592 bytes |
| AAD, HPKE `info`, HKDF salt and HKDF `info` | 65,536 bytes each |
| HKDF output | 0..8,160 bytes |
| Private AES key / Ed25519 seed / X25519 private input | 32 bytes |
| Ed25519/X25519 public key | 32 bytes |
| AES-GCM nonce and tag | 12 and 16 bytes |
| Ed25519 signature | 64 bytes |

Inputs are validated before provider work. The runtime creates bounded native
scratch copies and releases them after each operation. An ARRAY is the existing
general-purpose runtime representation: its memory cost is larger than its byte
count. A 1 MiB input is a maximum per call, not a recommended chunk size for every
device. Select smaller application chunks and bound the number of live arrays.

Key generation/import/load return opaque native handles (`ANY`). They belong to
their runtime and creator thread. Creation is restricted to the runtime owner
thread so that automatic finalization has deterministic affinity. Enter the
owning execution context before using or closing a handle. A handle cannot be
used by another runtime or thread; a background worker can create its own
runtime and keys. Repeated close succeeds, and closing one alias closes all
aliases. Use separate keys for encryption, signing and key agreement.

The module cleanses its owned private buffers and frees provider key objects on
close or automatic finalization. This is not a promise of universal erasure:
caller-owned STRINGs and ARRAYs, allocator remnants, operating-system snapshots,
swap and provider internals are outside that guarantee. Keep imported secret
arrays, derived shared secrets and unlock strings short-lived. No API exports
raw private material from an opaque handle.

## Key API

| Builtin | Result and meaning |
| --- | --- |
| `CRYPTOKEYGEN(algorithm)` | A freshly generated opaque private-key handle. |
| `CRYPTOKEYIMPORT(algorithm, bytes32)` | An opaque handle containing the supplied key/seed. |
| `CRYPTOPUBLICKEY(key)` | Ed25519 or X25519 public bytes; AES handles are rejected. |
| `CRYPTOKEYCLOSE(key)` | `.T.` after close, including an already-closed handle. |

`algorithm` accepts `"AES-256-GCM"`, `"ED25519"` and `"X25519"`, without regard
to ASCII letter case. Ed25519 import accepts a 32-byte seed, not a 64-byte
private/public concatenation. X25519 accepts the 32-byte scalar representation;
the provider performs the RFC 7748 scalar processing. Generation uses
`RAND_priv_bytes` and fails if secure entropy is unavailable. There is no weak
random-number fallback and no environment-controlled deterministic mode.

To distribute a per-object AES key, create 32 random bytes, import them as an AES
handle and HPKE-encrypt those same bytes for each authorized recipient. The
existing `SECURERANDOM(32)` provides 64 lowercase hexadecimal characters; an
application can decode that representation explicitly. It must not use account
passwords, bearer tokens or a server session secret as object keys. Generating an
opaque AES handle intentionally provides no subsequent raw-key export.

`tests/abi112_crypto/hex_key_example.kokum` provides a complete tested recipe:
decode `SECURERANDOM(32)`, import those 32 bytes, wrap the same bytes with HPKE
Auth, open and import at the recipient, and encrypt/decrypt an object containing
binary zeros. Its explicit decoder is ordinary representation conversion:

```kokum
FUNCTION DecodeLowerHex(text AS STRING) AS ANY
    LOCAL digits, characters, output, index
    IF LEN(text) > 8192 OR NOT REGEXMATCH("\\A(?:[0-9a-f]{2})*\\z", text)
        RETURN NULL
    ENDIF
    digits = {"0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "a": 10, "b": 11, "c": 12, "d": 13, "e": 14, "f": 15}
    characters = REGEXFINDALL("[0-9a-f]", text)
    output = []
    FOR index = 1 TO LEN(characters) STEP 2
        AADD(output, digits[characters[index]] * 16 + digits[characters[index + 1]])
    NEXT
    RETURN output
ENDFUNC
```

It accepts empty or bounded, even-length, lowercase hexadecimal; invalid input
returns NULL, which the caller must check. Tests cover all 256 byte values,
malformed characters, odd length, whitespace and a trailing newline. The example
passes AST, IR, bytecode and the external Linux VM. The temporary decoded ARRAY
holds private content-key bytes in caller memory; importing copies them into an
opaque native resource. Reassigning that ARRAY to `[]` releases the caller's
reference but does not guarantee erasure of its previous allocation. Keep this
temporary material out of logs, database rows and GUI serialization.

## AES-256-GCM

```text
CRYPTOAEADSEAL(aesKey, nonce12, plaintext, aad) -> ciphertext ARRAY
CRYPTOAEADOPEN(aesKey, nonce12, ciphertext, aad) -> plaintext ARRAY
```

The ciphertext is exactly `encrypted_bytes || tag16`. Nonces are exactly 12
bytes and tags are always the full 16 bytes. Decrypting requires the original
key, nonce and AAD. A truncated or altered tag, changed ciphertext, different
AAD or wrong key causes a catchable error. No plaintext ARRAY is created before
successful authentication, and failed-open native scratch plaintext is cleansed.

**The application must never reuse a nonce with a key.** The generic AEAD API
does not keep a persistent nonce ledger and cannot detect a reuse after import,
vault reload, restart or a different process. A transfer profile can allocate a
fresh key per immutable object revision and encode a monotonic chunk index into
a fixed 12-byte nonce. It must specify the encoding, chunk bound and durable
allocation rules before use. A retry can retransmit identical stored ciphertext;
editing plaintext requires the profile's new-revision/key rules. Do not reset a
nonce counter while retaining the key.

AAD should be a canonical byte encoding of the version, role, author/device,
recipient or audience commitment, object/revision, chunk position/count and
lengths that the application needs to authenticate. The runtime authenticates
the supplied bytes exactly; it does not infer those fields from an arbitrary
JSON object or from a relay connection.

## Signatures and derivation

```text
CRYPTOSIGN(ed25519Key, message) -> signature64 ARRAY
CRYPTOVERIFY(public32, message, signature64) -> LOGICAL
CRYPTOX25519(x25519Key, peerPublic32) -> shared32 ARRAY
CRYPTOHKDF(inputMaterial, salt, info, outputLength) -> ARRAY
```

Signatures use pure Ed25519 from RFC 8032, with no prehash or context variant.
Verification returns `.F.` for a well-formed input carrying an invalid signature.
Malformed types or lengths raise an argument error, and provider failures raise
a provider error. All three outcomes fail authentication; applications must not
treat an exception as approval.

Raw X25519 rejects an all-zero shared secret, including the low-order public
inputs exercised by the tests. The returned shared secret is ordinary caller
memory. Derive a role-specific key rather than using it directly. HKDF performs
RFC 5869 SHA-256 Extract followed by Expand. Empty salt has the RFC-defined
meaning; empty output is allowed. Give `info` a versioned application purpose and
the relevant context to separate different uses of the input material.

## HPKE profile

```text
CRYPTOHPKESEAL(recipientPublic32, plaintext, info, aad [, senderXKey]) -> MAP
CRYPTOHPKEOPEN(recipientXKey, envelope, info, aad [, senderPublic32]) -> ARRAY
```

The fixed suite is RFC 9180 **DHKEM(X25519, HKDF-SHA256), HKDF-SHA256,
AES-256-GCM**, with identifiers `(32, 1, 2)`. Four arguments select Base mode 0.
Five arguments select Auth mode 2; the sealing side supplies a sender X25519
private handle and the opening side supplies the expected sender public bytes.
Other suites, modes and argument counts are rejected.

Each seal generates a fresh ephemeral private key and uses sequence number zero.
The API has no reusable HPKE context, sequence counter, exporter, PSK or AuthPSK
mode. A new invocation is a new encapsulation. This automatically allocates the
one-shot HPKE nonce under its fresh derived key; it does not change the manual
nonce contract of `CRYPTOAEADSEAL`.

The returned MAP has exactly these six lowercase fields:

| Field | Type and value |
| --- | --- |
| `kem_id` | INTEGER 32 |
| `kdf_id` | INTEGER 1 |
| `aead_id` | INTEGER 2 |
| `mode` | INTEGER 0 or 2 |
| `enc` | ARRAY of 32 ephemeral public bytes |
| `ciphertext` | ARRAY containing ciphertext and full tag |

Open rejects missing/extra fields, wrong types, unsupported identifiers and a
mode inconsistent with the supplied argument count. Its `info` and AAD must
match the sender's values. X25519 public serialization follows RFC 9180's
identity encoding; DH outputs are checked for all-zero failure. All secret
agreement and schedule intermediates stay inside the native layer.

Base mode encrypts for the recipient but provides no sender authentication.
Auth mode binds possession of the caller-selected sender X25519 key. It does
not establish that a first-seen directory key belongs to a particular person.
Pin/verify identity keys through the application trust workflow, stop pending
delivery when a trusted key changes, and bind both parties and protocol context
into the application profile. HPKE Auth is not a publicly verifiable Ed25519
signature; use separate signing keys for signed post/manifests where required.

Opening the same valid envelope again succeeds. Replay/duplicate detection,
revocation, authorization, expiry and receipt persistence belong to the
application. Static recipient HPKE does not by itself provide forward secrecy
or post-compromise recovery. Removing a post cannot erase plaintext that a
recipient already obtained.

### Minimal byte round trip

```kokum
FUNCTION Main AS INTEGER
    LOCAL recipient, sender, packet, recovered
    recipient = CRYPTOKEYGEN("X25519")
    sender = CRYPTOKEYGEN("X25519")
    packet = CRYPTOHPKESEAL(CRYPTOPUBLICKEY(recipient), [0, 255, 0], [1], [2], sender)
    recovered = CRYPTOHPKEOPEN(recipient, packet, [1], [2], CRYPTOPUBLICKEY(sender))
    ? LEN(recovered)
    CRYPTOKEYCLOSE(sender)
    CRYPTOKEYCLOSE(recipient)
    RETURN 0
ENDFUNC
```

This demonstrates the API and binary zeros; `[1]` and `[2]` are demonstration
context bytes. An application profile must replace them with its defined
identity, version and object context. Tests use published vectors and a separate
implementation in addition to such round trips.

## Persistent private-key vault

```text
CRYPTOKEYSAVE(key, absolutePath, independentPassphrase) -> bytesWritten INTEGER
CRYPTOKEYLOAD(absolutePath, independentPassphrase) -> opaque key handle
```

This release uses a portable **encrypted local vault**, with the existing
`PRIVATEWRITE`/`PRIVATEREAD` storage protection. It does not claim native Keychain,
Credential Manager, TPM or Secret Service integration. Choose a file inside the
private directory returned by `APPDATADIR`. On POSIX, the existing facility
checks ownership, private directory/file permissions, regular-file/link
properties and unsafe path traversal; writes use an exclusive private temporary
file and atomic replacement. On Windows it uses the existing owner-private DACL
implementation. A storage policy failure is an error; there is no plaintext or
world-readable fallback.

The unlock secret is a **separate vault passphrase**, 12..1024 counted bytes.
The minimum length is an input policy, not a strength guarantee. NUL bytes are
significant to the KDF. A text UI should collect a strong independent passphrase
using a secret-input control, confirm it on initial creation, and never log it.
Do not save the passphrase beside the encrypted file or derive it from an
Infinetus password/token. The function cannot recognize whether a caller has
reused an account password; the application must enforce that separation in its
workflow.

The exact format is `kokum-key-v1:` followed by 180 lowercase hex characters,
193 file bytes total. Decoding yields a 90-byte record:

| Offset | Length | Meaning |
| --- | --- | --- |
| 0 | 8 | ASCII `KOKKEY1!` |
| 8 | 1 | Algorithm: AES=1, Ed25519=2, X25519=3 |
| 9 | 1 | KDF id 1: PBKDF2-HMAC-SHA256 |
| 10 | 4 | Big-endian iteration count, exactly 600,000 |
| 14 | 16 | Fresh random salt |
| 30 | 12 | Fresh random nonce |
| 42 | 32 | AES-256-GCM encrypted private key/seed |
| 74 | 16 | Full authentication tag |

PBKDF2 derives a 32-byte wrapping key from the independent passphrase. The full
42-byte header is authenticated as AAD. Every save obtains a fresh salt and
nonce, including a save of the same key with the same passphrase. Unknown format,
KDF, work factor, algorithm, noncanonical hex or incorrect size is rejected
before expensive derivation. The reader's protected-file bound is 4096 bytes;
the path bound is 4096 bytes. A missing file, wrong passphrase or corrupt envelope
produces an authentication failure with no key handle. Unsafe storage produces
the separate storage error.

**Unlock:** load only after the user supplies the independent passphrase. Keep
the resulting handle for the intended session and close it on lock/account
switch. An unattended application must supply its own explicitly designed
protected-secret mechanism; this module does not manufacture a zero-interaction
unlock secret.

**Backup/recovery:** a backup of the encrypted vault plus the separately retained
passphrase can restore the key. Restore it into an owner-private path before
loading. There is no server recovery copy, account-password reset hook, key
escrow or hidden unlock path. Losing both the handle and the ability to unlock
the vault loses the private key; replacing it requires a new identity/trust
decision. Changing an account password does not change a vault passphrase.

**Rotation:** create a new role-specific key and save it in a different vault;
verify the new public identity before replacing trust records and cancel or
re-authorize pending transfers. Retain any old vault only for the explicit
local history/recovery policy. The runtime does not revoke a distributed public
key or delete already-held plaintext.

## Failures and diagnostics

| Code | Meaning |
| --- | --- |
| `KCRYPTO2201` | Invalid types, lengths, limits, algorithm or envelope fields |
| `KCRYPTO2202` | Cryptographic provider failed |
| `KCRYPTO2203` | Closed key, wrong key role, runtime or thread |
| `KCRYPTO2204` | Authentication failed, including encrypted vault unlock |
| `KCRYPTO2205` | Key agreement failed or rejected a low-order public key |
| `KCRYPTO2208` | Missing/wrong execution context or key-close affinity |
| `KCRYPTO2210` | Protected encrypted storage unavailable or unsafe |
| `KCRYPTO2290` | Bounded native allocation failed |

The C dispatch interface resets its output to NULL on every failure. Error
strings are static and omit paths, passphrases, plaintext, private material and
raw provider errors. Language adapters convert them to catchable runtime errors.
Errors do not certify that the entire operation is constant-time. Existing
runtime collection allocation behaviour also remains unchanged; this module
does not promise universal out-of-memory recovery.

## Validation and references

`tests/abi112_crypto` contains standalone published-vector tests, public API
tests and independent Python/PyCA interoperability tests. They cover RFC 5869
HKDF, RFC 8032 Ed25519, RFC 7748 X25519, published AES-GCM vectors and pinned
CFRG RFC 9180 Base/Auth vectors with exact keys, nonces and ciphertext. Negative
tests exercise corruption, wrong AAD/context/sender, low-order input, malformed
types/limits/envelopes, failed-open NULL output, private storage, encrypted vault
unlock and native-handle ownership/finalization. See its README for exact commands
and platform evidence requirements.

Primary specifications and fixtures:

- RFC 9180: <https://www.rfc-editor.org/rfc/rfc9180.html>
- RFC 8032: <https://www.rfc-editor.org/rfc/rfc8032.html>
- RFC 7748: <https://www.rfc-editor.org/rfc/rfc7748.html>
- RFC 5869: <https://www.rfc-editor.org/rfc/rfc5869.html>
- Pinned HPKE vectors: <https://github.com/cfrg/draft-irtf-cfrg-hpke/blob/5f503c564da00b0687b3de75f1dfbdfc4079ad31/test-vectors.json>
- AES-GCM fixtures: <https://github.com/openssl/openssl/blob/openssl-3.5.7/test/recipes/30-test_evp_data/evpciph_aes_common.txt>

Passing these tests is implementation evidence. It is not an independent
security audit, FIPS/CAVP validation, a native-platform execution claim for a
platform not actually run, or production acceptance of Infinetus encrypted
delivery.
