encrypt method

  1. @override
List<int> encrypt(
  1. List<int> nonce,
  2. List<int> plaintext, {
  3. List<int>? associatedData,
  4. List<int>? dst,
})
override

Encrypts the provided plaintext data with ChaCha20-Poly1305 encryption.

Parameters:

  • nonce: The nonce as a List<int>, with a maximum length of 16 bytes.
  • plaintext: The plaintext data to be encrypted.
  • associatedData: Optional associated data that is not encrypted but included in the tag calculation.
  • dst: An optional destination List<int> where the encrypted data and tag will be written.

Throws:

  • ArgumentException if the provided nonce length is incorrect or if the destination length is incorrect.

Implementation

@override
List<int> encrypt(
  List<int> nonce,
  List<int> plaintext, {
  List<int>? associatedData,
  List<int>? dst,
}) {
  if (nonce.length > 16) {
    throw ArgumentException.invalidOperationArguments(
      "encrypt",
      name: "nonce",
      reason: "Invalid nonce bytes length.",
    );
  }

  final counter = List<int>.filled(16, 0);

  counter.setRange(
    counter.length - nonce.length,
    counter.length,
    nonce.asBytes,
  );

  final authKey = List<int>.filled(32, 0);
  ChaCha20.stream(_key, counter, authKey, nonceInplaceCounterLength: 4);

  final resultLength = plaintext.length + tagLength;

  final List<int> result = dst ?? List<int>.filled(resultLength, 0);
  if (result.length != resultLength) {
    throw ArgumentException.invalidOperationArguments(
      "encrypt",
      name: "dst",
      reason: "Invalid destination bytes length.",
      expecteLen: resultLength,
    );
  }

  ChaCha20.streamXOR(
    _key,
    counter,
    plaintext.asBytes,
    result,
    nonceInplaceCounterLength: 4,
  );

  final calculatedTag = List<int>.filled(tagLength, 0);
  final cipherText = result.sublist(0, result.length - tagLength);
  _authenticate(calculatedTag, authKey, cipherText, associatedData);

  result.setRange(result.length - tagLength, result.length, calculatedTag);
  BinaryOps.zero(counter);
  return result;
}