# Cryptography in Kokum applications

Kokum source revision CRYPTO-OFFICIAL-01 adds four general builtins to the
standard compiler and VM. A program using them requires **TVM ABI 1.10**.
The product version remains 1.1.0; a product banner alone does not identify
crypto support. GUI ABI 1.10 is a separate version.

Applications continue to compile into one portable `.kapp`. Use the matching
standard Kokum compiler and the officially distributed VM for each target
platform. Native target acceptance must accompany a platform release.

## API reference

| Operation | Arguments | Result |
| --- | --- | --- |
| `SECURERANDOM(byte_count)` | INTEGER, 1–4096 bytes | STRING containing exactly twice that many lowercase hexadecimal characters |
| `PASSWORDHASH(password [, options])` | STRING, 0–1024 bytes; optional MAP | Self-describing password record |
| `PASSWORDVERIFY(password, encoded_record)` | Password STRING, 0–1024 bytes; record STRING | LOGICAL |
| `SHA256(text)` | STRING, 0–16,777,216 bytes | 64 lowercase hexadecimal characters |

Builtin names are case-insensitive. Numeric strings, REAL/DECIMAL values,
LOGICAL values, arrays and NULL are not implicitly coerced to the argument
types above.

Text uses its existing UTF-8 representation. These operations process exact
counted STRING bytes, including an embedded NUL. They do not normalize
Unicode, trim whitespace or silently shorten a password. The byte limit can
therefore be reached with fewer than 1024 Unicode characters.

The existing source and bytecode string-literal rules have not changed.
A runtime string containing NUL can, for example, come from `JSONDECODE`;
this does not add NUL support to other text I/O operations.

## Secure random values

~~~kokum
token = SECURERANDOM(32)
~~~

This produces 32 random bytes encoded as a 64-character string. The runtime
uses the existing OpenSSL cryptographic random provider, normally seeded by
the operating system. Entropy or provider failure raises a catchable error;
there is no clock/process-ID fallback and no partial successful result.

Choose a byte count appropriate to the application's token design. The API's
minimum of one byte is a type/range contract, not a recommendation for
authentication tokens. Store and transmit credentials according to the
application's session and transport design.

## Password hashing and verification

~~~kokum
storedRecord = PASSWORDHASH(password)
accepted = PASSWORDVERIFY(candidatePassword, storedRecord)
~~~

PASSWORDHASH uses PBKDF2-HMAC-SHA256 with a newly generated 16-byte salt and a
32-byte derived value. Its default is 600,000 iterations. The only option is
`Iterations`, which accepts an INTEGER from 600,000 through 2,000,000:

~~~kokum
storedRecord = PASSWORDHASH(password, {"Iterations": 1000000})
~~~

Option names are ASCII case-insensitive. Unknown options and duplicate names
that differ only in case are rejected. Empty `{}` selects the default.
Applications cannot supply a salt, select an algorithm or change output length.

The version-1 record has this exact structure:

~~~text
$kokum$1$pbkdf2-sha256$600000$<32 lowercase salt hex>$<64 lowercase derived hex>
~~~

The decimal iteration count is canonical, without signs or leading zeroes.
Records occupy 127 bytes with a six-digit cost or 128 with a seven-digit cost.
Store the complete record. Its salt and cost are part of the record and must
not be discarded or reconstructed from other data.

PASSWORDVERIFY returns false for a wrong password, malformed record,
unsupported algorithm/version, or an out-of-range recorded cost. It validates
the record before doing the expensive derivation. Genuine cryptographic
provider failures raise an error and never authenticate the caller. Type and
password-length errors also raise an error.

The derived-value comparison uses a fixed 32-byte constant-time primitive.
The complete verification operation has no constant-time guarantee:
malformed records return early and accepted records can specify different
iteration counts.

Empty passwords are accepted by the primitive. Password strength, required
length, rate limits, authentication responses, account lockout, rehash policy
and session handling belong to the application. Password hashing is
synchronous and occupies the calling service worker; size worker pools and
rate limits using measurements on the actual deployment host.

Other password formats are not automatically compatible. Check the real
source/schema of any system being migrated and define a verified conversion,
rehash-on-success or password-reset process. Do not relabel an existing hash
as a Kokum record.

## General SHA-256

~~~kokum
digest = SHA256("abc")
~~~

The result is:

~~~text
ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad
~~~

SHA256 is a general digest. Use PASSWORDHASH for password storage. A digest
does not supply message authentication, encryption or an application's full
session protocol.

## Errors

| Code | Meaning |
| --- | --- |
| KCRYPTO1000 | Invalid arity/internal invocation or supplied execution context |
| KCRYPTO1001 | Wrong argument type |
| KCRYPTO1002 | Byte count, input length or iteration bound exceeded |
| KCRYPTO1003 | Invalid password option map, key or value type |
| KCRYPTO1900 | Recoverable module allocation/context-allocation failure |
| KCRYPTO2001 | Secure entropy unavailable |
| KCRYPTO2002 | Digest/KDF/provider or record-encoding failure |

Compile-time arity checking may reject an invalid call before a runtime
KCRYPTO error is possible. Crypto diagnostics contain static text rather than
the input password, salt, record or digest. The module cleanses its temporary
native buffers; application-owned STRING values and general runtime memory
management retain their existing behavior. Recovery from module allocations
does not imply recovery from every possible process-wide out-of-memory event.

A service should catch operational errors and return an appropriate failure.
It must not convert an exception into successful authentication or return
passwords/records in an error response.

## Compile and run with distributed tools

With the standard tools available on PATH:

~~~sh
kokumc compile crypto_demo.kokum -o crypto_demo.kbc
kokumvm crypto_demo.kbc
kokumc bundle /absolute/path/to/application/kokum.toml
kokumvm /absolute/path/to/application/dist/application.kapp
~~~

For a portable project, retain `target_os="portable"` and
`target_arch="any"` in the existing bundle settings. The compiler infers the
minimum TVM ABI from resolved operations and imports. Old-feature programs
retain their older minimum requirements; ordinary user-defined routines
with these names retain normal language shadowing.

An ABI 1.9 VM correctly rejects an ABI 1.10 crypto package. Deploy the accepted
standard VM release and select that executable in PATH and the IDE. Editing
a bytecode header cannot add a missing operation.

For a distributed Linux runtime directory, keep it intact and use its
`bin/kokumc`, `bin/kokumvm` and `start_ide.sh` launchers. The launchers
select the supplied libraries. Windows uses the distributed `kokumvm.exe`;
macOS uses the corresponding standard VM executable. Preserve the license
and third-party notices supplied with each platform runtime.

## Design references

The implementation reuses the established OpenSSL dependency. PBKDF2 was
selected to fit that dependency; no FIPS certification is claimed. OWASP
generally prefers Argon2id for new password systems and lists 600,000
iterations for PBKDF2-HMAC-SHA256.

- OpenSSL random-provider contract:
  https://docs.openssl.org/3.0/man3/RAND_bytes/
- OpenSSL PBKDF2 byte-length and failure contract:
  https://docs.openssl.org/3.0/man3/PKCS5_PBKDF2_HMAC/
- Fixed-length comparison:
  https://docs.openssl.org/3.0/man3/CRYPTO_memcmp/
- Password work-factor guidance:
  https://cheatsheetseries.owasp.org/cheatsheets/Password_Storage_Cheat_Sheet.html

These references inform the primitive choices. Application authentication and
deployment requirements still need application-specific design and testing.
