libsodium_crypto_stream (libsodium v3.0.1)

View Source

The default stream cipher, currently XSalsa20 (see primitive/0).

crypto_stream/3 returns raw keystream and 'xor'/3 encrypts or decrypts by combining a message with it. The noncebytes/0 byte nonce is long enough to be chosen at random for every message.

This is not authenticated encryption: ciphertexts can be modified without detection, so pair it with a MAC or use libsodium_crypto_secretbox instead. A nonce must never be reused with the same key.

K = libsodium_crypto_stream:keygen(),
N = libsodium_randombytes:buf(libsodium_crypto_stream:noncebytes()),
C = libsodium_crypto_stream:'xor'(<<"message">>, N, K),
<<"message">> = libsodium_crypto_stream:'xor'(C, N, K).

Summary

Types

k()

A crypto_stream_KEYBYTES (32-byte) binary.

n()

A crypto_stream_NONCEBYTES (24-byte) binary.

Functions

Return CLen bytes of keystream for the noncebytes/0 byte nonce N and the keybytes/0 byte key K.

Return crypto_stream_keybytes(), in bytes.

Generate a random keybytes/0 byte key.

Return crypto_stream_messagebytes_max(), in bytes.

Return crypto_stream_noncebytes(), in bytes.

Return crypto_stream_primitive() as an atom.

Encrypt or decrypt M by combining it with the keystream for the nonce N and key K.

Types

k()

-type k() :: <<_:256>>.

A crypto_stream_KEYBYTES (32-byte) binary.

n()

-type n() :: <<_:192>>.

A crypto_stream_NONCEBYTES (24-byte) binary.

Functions

crypto_stream(CLen, N, K)

-spec crypto_stream(CLen, N, K) -> Result
                       when CLen :: non_neg_integer(), N :: n(), K :: k(), Result :: binary().

Return CLen bytes of keystream for the noncebytes/0 byte nonce N and the keybytes/0 byte key K.

keybytes()

-spec keybytes() -> Result when Result :: 32.

Return crypto_stream_keybytes(), in bytes.

keygen()

-spec keygen() -> Result when Result :: k().

Generate a random keybytes/0 byte key.

messagebytes_max()

-spec messagebytes_max() -> Result when Result :: non_neg_integer().

Return crypto_stream_messagebytes_max(), in bytes.

noncebytes()

-spec noncebytes() -> Result when Result :: 24.

Return crypto_stream_noncebytes(), in bytes.

primitive()

-spec primitive() -> Result when Result :: xsalsa20.

Return crypto_stream_primitive() as an atom.

'xor'(M, N, K)

-spec 'xor'(M, N, K) -> Result when M :: binary(), N :: n(), K :: k(), Result :: binary().

Encrypt or decrypt M by combining it with the keystream for the nonce N and key K.