dreamworkAPI
Ctrl K
GitHub
libraryDocs / crypto / chacha20

crypto.chacha20

librarysharedmenusource

ChaCha20 stream cipher library, the IETF variant with a 96-bit nonce and a 32-bit block counter.

Encryption and decryption are the same operation, the data is XORed with the keystream.

A key and nonce pair must never be used twice, otherwise both plaintexts can be recovered. If nonces are random, prefer crypto.xchacha20, its 192-bit nonce is safe to generate randomly.

ChaCha20 alone does not authenticate the data, use a MAC ( e.g. crypto.hmac ) over the ciphertext to detect tampering.

See RFC 8439 for the algorithm.

Fields

NameTypeDescription
key_sizeinteger = 32
nonce_sizeinteger = 12
block_sizeinteger = 64

Functions

crypto.chacha20.blockComputes a single 64-byte ChaCha20 keystream block.
crypto.chacha20.encryptEncrypts or decrypts the data with ChaCha20.

#crypto.chacha20.block

sharedmenunodiscardsource
function crypto.chacha20.block(key: string, nonce: string, counter?: integer): string

Computes a single 64-byte ChaCha20 keystream block.

Parameters
NameTypeDescription
keystringThe 32-byte key.
noncestringThe 12-byte nonce.
counteroptionalintegerThe block counter, default is 0.
Returns
TypeNameDescription
stringblockThe 64-byte keystream block.

#crypto.chacha20.encrypt

sharedmenunodiscardsource
function crypto.chacha20.encrypt(data: string, key: string, nonce: string, counter?: integer): string

Encrypts or decrypts the data with ChaCha20.

The data can be processed in parts: each part except the last must be a multiple of 64 bytes long, and counter of the next part is counter + #part / 64.

Parameters
NameTypeDescription
datastringThe plaintext to encrypt or the ciphertext to decrypt.
keystringThe 32-byte key.
noncestringThe 12-byte nonce.
counteroptionalintegerThe initial block counter, default is 0.
Returns
TypeNameDescription
stringresultThe ciphertext or plaintext, same length as data.
Generated from the dreamwork meta branch.