std.crypto.chacha.XChaCha20
class pub XChaCha20
The XChaCha20 stream cipher.
XChaCha20 combines a regular ChaCha20 stream cipher with the HChaCha20 hasher. It uses a 192-bits nonce, which is large enough that one can generate it randomly.
For more information about XChaCha20 and the differences between it and ChaCha20, consider reading the RFC that describes XChaCha20 at https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha.
Static methods
new
Show source codeHide source code
fn pub static new(key: ref ByteArray, nonce: ref ByteArray) -> XChaCha20 {
if key.size != KEY_SIZE {
panic('XChaCha20 key sizes must be exactly ${KEY_SIZE} bytes')
}
if nonce.size != XCHACHA_NONCE_SIZE {
panic('XChaCha20 nonce sizes must be exactly ${XCHACHA_NONCE_SIZE} bytes')
}
let sub_key = hchacha20(key, nonce.slice(start: 0, size: 16))
XChaCha20(
ChaCha20(
Matrix(
[
0x61707865,
0x3320646E,
0x79622D32,
0x6B206574,
little.read_u32(from: sub_key, at: 0),
little.read_u32(from: sub_key, at: 4),
little.read_u32(from: sub_key, at: 8),
little.read_u32(from: sub_key, at: 12),
little.read_u32(from: sub_key, at: 16),
little.read_u32(from: sub_key, at: 20),
little.read_u32(from: sub_key, at: 24),
little.read_u32(from: sub_key, at: 28),
DEFAULT_COUNTER,
0,
little.read_u32(from: nonce, at: 16),
little.read_u32(from: nonce, at: 20),
],
),
),
)
}
fn pub static new(key: ref ByteArray, nonce: ref ByteArray) -> XChaCha20
Returns a new XChaCha20 cipher from the given key and nonce.
The key must be something generated randomly and securely, not something predictable.
The nonce must be unique for every message encrypted using this cipher. Using the same nonce for different messages weakens the encryption.
Compared to regular ChaCha20 it's fine for randomly generate the nonce, as it's large enough that reuse of the same nonce is unlikely to occur.
Panics
This method panics if key
isn't exactly 32 bytes, or if nonce
isn't
exactly 24 bytes.
Examples
import std.crypto.chacha (XChaCha20)
import std.rand (Random)
let rand = Random.new
let key = rand.bytes(size: 32)
let nonce = rand.bytes(size: 24)
XChaCha20.new(key, nonce)
Instance methods
counter=
Show source codeHide source code
fn pub mut counter=(value: Int) {
@chacha.counter = value
}
fn pub mut counter=(value: Int)
Sets the block counter to the given value.
Panics
This method panics if the value doesn't fit in the range valid for an unsigned 32-bits integer.
decrypt
Show source codeHide source code
fn pub mut decrypt(bytes: mut ByteArray) -> ByteArray {
@chacha.apply(bytes)
}
fn pub mut decrypt(bytes: mut ByteArray) -> ByteArray
Decrypts a ByteArray
and returns the decrypted result as a new
ByteArray
.
encrypt
Show source codeHide source code
fn pub mut encrypt(bytes: mut ByteArray) -> ByteArray {
@chacha.apply(bytes)
}
fn pub mut encrypt(bytes: mut ByteArray) -> ByteArray
Encrypts a ByteArray
and returns the encrypted result as a new
ByteArray
.
Implemented traits
Cipher
impl Cipher for XChaCha20