Salsa20 for Elixir

A pure-Elixir implementation of the Salsa20 stream cipher, plus the HSalsa20 hash function used to derive subkeys.

No dependencies, no NIFs.

Installation

def deps do
  [{:salsa20, "~> 1.0"}]
end

Usage

k = :crypto.strong_rand_bytes(32)
v = :crypto.strong_rand_bytes(8)

c = Salsa20.crypt("attack at dawn", k, v)
Salsa20.crypt(c, k, v)   # => "attack at dawn"

crypt is symmetric: running it over the ciphertext returns the plaintext. The optional fourth argument is the block number to start from, which is how you seek within a stream; it defaults to 0. It must be a non-negative integer below 264 — one nonce covers 270 bytes, and past that the keystream would repeat.

For data arriving in pieces, carry the session state between calls:

{c1, p} = Salsa20.crypt_bytes("attack ", {k, v, 0, ""}, [])
{c2, p} = Salsa20.crypt_bytes("at ", p, [])
{c3, _} = Salsa20.crypt_bytes("dawn", p, [])

c1 <> c2 <> c3   # same bytes as Salsa20.crypt("attack at dawn", k, v)

Salsa20.hash/2 is HSalsa20 over a 16-byte input, producing a 32-byte subkey:

subkey = Salsa20.hash(k, :crypto.strong_rand_bytes(16))

Arguments

Anything else raises FunctionClauseError. Malformed iodata — a list containing something that isn't a byte or binary — raises ArgumentError.

What this is not

Salsa20 only encrypts; it does not detect tampering. If an attacker can modify ciphertext, use an authenticated construction instead — NaCl's secretbox (XSalsa20-Poly1305) or similar. Also, Salsa20 is not an AEAD and the nonce must never be reused with the same key.

License

MIT. See LICENSE.