encryptMutableBytes function

Future<Uint8List> encryptMutableBytes(
  1. Uint8List data,
  2. Uint8List key, {
  3. required CryptoImplementation crypto,
})

Implementation

Future<Uint8List> encryptMutableBytes(
  Uint8List data,
  Uint8List key, {
  required CryptoImplementation crypto,
}) async {
  final lengthInBytes = encodeEndian(
    data.length,
    4,
  );

  final totalOverhead =
      encryptionOverheadLength + 4 + encryptionNonceLength + 2;

  final finalSize =
      padFileSizeDefault(data.length + totalOverhead) - totalOverhead;

  data = Uint8List.fromList(
    lengthInBytes + data + Uint8List(finalSize - data.length),
  );

  // Generate a random nonce.
  final nonce = crypto.generateRandomBytes(encryptionNonceLength);

  final header = [0x8d, 0x01] + nonce;

  // Encrypt the data.
  final encryptedBytes = await crypto.encryptXChaCha20Poly1305(
    key: key,
    plaintext: data,
    nonce: nonce,
  );

  // Prepend the header to the final data.
  return Uint8List.fromList(header + encryptedBytes);
}