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.

This method takes a nonce, plaintext data, and optional associated data and performs ChaCha20-Poly1305 encryption. It generates an authentication tag, and the encrypted data is returned in the List<int> dst. If dst is not provided, a new List<int> is created to hold the result.

Parameters:

  • nonce: The nonce as a List
  • 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.

Returns:

  • The List<int> containing the encrypted data and authentication tag.

Note: This method uses ChaCha20-Poly1305 encryption, including nonce handling, authentication tag calculation, and associated data processing.

Implementation

@override
List<int> encrypt(List<int> nonce, List<int> plaintext,
    {List<int>? associatedData, List<int>? dst}) {
  if (nonce.length > 16) {
    throw const ArgumentException("ChaCha20Poly1305: incorrect nonce length");
  }

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

  counter.setRange(counter.length - nonce.length, counter.length,
      BytesUtils.toBytes(nonce));

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

  final resultLength = plaintext.length + tagLength;

  List<int> result = dst ?? List<int>.filled(resultLength, 0);
  if (result.length != resultLength) {
    throw const ArgumentException(
        "ChaCha20Poly1305: incorrect destination length");
  }

  ChaCha20.streamXOR(_key, counter, BytesUtils.toBytes(plaintext), 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);
  zero(counter);
  return result;
}