SealedBox

object SealedBox

Encrypt bytes to a recipient's public key so that only the holder of the private key can read them, with caller-chosen associated data bound to the result.

Every seal generates a fresh P-256 key pair and a fresh 96-bit nonce from the platform CSPRNG, agrees a secret with the recipient by ECDH, stretches it with HKDF-SHA-256 into an AES-256-GCM key, and encrypts. Sealing the same plaintext twice gives two different boxes, and there is no deterministic form, for tests or otherwise: a reproducible seal lets a reader who knows all but one input confirm guesses at it.

A box proves nothing about who sealed it. Sealing needs only the public key, and anyone can hold that — an app that compiles it in hands it to every user. Opening a box shows it was sealed to this key and not altered since; it does not show by whom. Authenticate the sender separately where that matters.

The format (version 1), all lengths in bytes:

version (1) = 0x01 | ephemeral public key (65, SEC 1 uncompressed) | nonce (12) | ciphertext | tag (16)

The HKDF salt is empty (RFC 5869's all-zero default) and its info is the ASCII label kuilt-seal/v1 P-256 HKDF-SHA-256 AES-256-GCM followed by the ephemeral and then the recipient public key, so a box is bound to the key it was sealed for. The associated data is the AEAD's, as given. A box is plaintext.size + OVERHEAD bytes.

No compression, deliberately. Compressing before encrypting makes the length depend on the content. A caller that must hide the length pads the plaintext to a fixed size itself.

Both calls are suspend because WebCrypto, the wasmJs provider, has only asynchronous operations. A failure caused by the bytes passed in is a SealedBoxException; none carries plaintext. A platform provider that cannot run at all fails its one-time self-test with IllegalStateException.

Properties

Link copied to clipboard
const val OVERHEAD: Int

Bytes a box adds to its plaintext: version, ephemeral key, nonce and tag.

Functions

Link copied to clipboard
suspend fun open(recipient: SealPrivateKey, sealed: ByteArray, associatedData: ByteArray): ByteArray

Opens a box seal produced for recipient's public key under the same associatedData, and returns the plaintext. Throws SealedBoxException: SealedBoxException.Reason.NOT_AUTHENTIC for a wrong key, different associated data or altered bytes, alike.

Link copied to clipboard
suspend fun seal(recipient: SealPublicKey, plaintext: ByteArray, associatedData: ByteArray): ByteArray

Seals plaintext to recipient, binding associatedData (which is authenticated, not encrypted, and must be passed again to open). Throws IllegalStateException if the process has replaced the platform CSPRNG or the provider fails its self-test, and SealedBoxException with SealedBoxException.Reason.SEAL_FAILED if a sealing step fails.