SaltDns.Crypto (Salt v1.0.0)

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

Ported from Karta.Crypto (Karta mail platform, MIT, Shiloh B.V.), with one addition: a caller-supplied context string bound into the authentication.

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 additional authenticated data is the version byte, the key id and the context. A value therefore cannot be relabelled as another key's, nor moved to a field with a different context (for example from tsig_key.secret to smtp.password). The context is not stored; the reader must supply the same one.

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/4, looking its key up by id in keys.

Encrypts plaintext with the 32-byte key, labelling the result key_id and binding it to context.

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, context)

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

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

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

encrypt(plaintext, key_id, key, context)

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

Encrypts plaintext with the 32-byte key, labelling the result key_id and binding it to context.

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

key_id(value)

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

Returns the key id a ciphertext is labelled with.