Karta.Crypto (Karta v1.0.0)

Authenticated encryption for secrets at rest: AES-256-GCM through :crypto, with no third-party dependency.

Wire format of a ciphertext:

<<@version, byte_size(key_id), key_id::binary, iv::binary-12,
  tag::binary-16, ciphertext::binary>>

The key id names the key a value was encrypted with, so keys can be rotated: new values use the new key while old values stay readable until they are re-encrypted. The version byte and the key id are authenticated as additional data, so a value cannot be relabelled as another key's.

A fresh random 96-bit IV is drawn for every value, as NIST SP 800-38D requires for GCM.

Summary

Functions

Decrypts a value produced by encrypt/3, looking its key up by id in keys.

Encrypts plaintext with the 32-byte key, labelling the result key_id.

HKDF with HMAC-SHA256 (RFC 5869): derives length bytes (at most 8160) from input key material, a salt and context information.

Returns the key id a ciphertext is labelled with.

Types

key()

@type key() :: <<_::256>>

key_id()

@type key_id() :: binary()

keys()

@type keys() :: %{required(key_id()) => key()}

Functions

decrypt(value, keys)

@spec decrypt(binary(), keys()) :: {:ok, binary()} | :error

Decrypts a value produced by encrypt/3, looking its key up by id in keys.

Returns :error for an unknown version or key id, a wrong key, and any tampered byte, without saying which.

encrypt(plaintext, key_id, key)

@spec encrypt(binary(), key_id(), key()) :: binary()

Encrypts plaintext with the 32-byte key, labelling the result key_id.

Raises ArgumentError when the key is not 32 bytes or the key id is empty or longer than 255 bytes.

hkdf_sha256(ikm, salt, info, length)

@spec hkdf_sha256(binary(), binary(), binary(), pos_integer()) :: binary()

HKDF with HMAC-SHA256 (RFC 5869): derives length bytes (at most 8160) from input key material, a salt and context information.

key_id(value)

@spec key_id(binary()) :: {:ok, key_id()} | :error

Returns the key id a ciphertext is labelled with.