Current section

Files

Jump to
salsa20 README.md
Raw

README.md

# Salsa20 for Elixir

A pure-Elixir implementation of the [Salsa20 stream cipher](http://cr.yp.to/snuffle/spec.pdf),
plus the [HSalsa20](http://cr.yp.to/highspeed/naclcrypto-20090310.pdf) hash function
used to derive subkeys.

No dependencies, no NIFs.

## Installation

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

## Usage

```elixir
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 2^64 — one nonce covers 2^70 bytes, and past that the
keystream would repeat.

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

```elixir
{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:

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

## Arguments

- Key: 16 or 32 bytes. Prefer 32.
- Nonce: 8 bytes for `crypt`/`crypt_bytes`, 16 for `hash`.
- Message: a binary or iodata.

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](LICENSE).