encrypt method
Encrypts payload into a nonce || ciphertext || tag wire packet.
The nonce is this session's 4-byte salt followed by the next counter.
associatedData (AAD) is bound into the authentication tag (protecting
routing headers, session IDs, sequence numbers, …) but is not encrypted
and is not included in the packet; the peer must supply the identical
AAD to decrypt.
Throws StateError if the session has been disposed, and PqForgeException after 2^32 messages.
Implementation
Future<Uint8List> encrypt(
Uint8List payload, {
Uint8List? associatedData,
}) async {
_ensureNotDisposed();
if (_counter >= 0x100000000) {
throw const PqForgeException(
'Secure-session nonce counter exhausted (2^32 messages)',
);
}
final seq = _counter++;
final nonce = Uint8List(cipherSuite.nonceLength)
..setRange(0, _nonceSalt.length, _nonceSalt)
..setRange(
_nonceSalt.length,
cipherSuite.nonceLength,
PqBytes.uint64(seq),
);
final body = await _engine.seal(
key: _secretKey,
nonce: nonce,
plaintext: payload,
aad: associatedData ?? _emptyAad,
);
return Uint8List(nonce.length + body.length)
..setRange(0, nonce.length, nonce)
..setRange(nonce.length, nonce.length + body.length, body);
}