encryptFile method

Uint8List encryptFile(
  1. Uint8List clearFile,
  2. String filename
)

Encrypt a clear-text file into an encrypted file, for the recipients of this session.

clearFile - A Uint8List of the clear-text content of the file to encrypt. filename - The name of the file to encrypt. Returns the encrypted file as a Uint8List.

Implementation

Uint8List encryptFile(Uint8List clearFile, String filename) {
  // Dart FFI forces us to copy the data from Uint8List to a newly allocated Pointer<Uint8>
  final Pointer<Uint8> nativeClearFile = calloc<Uint8>(clearFile.length);
  final pointerList = nativeClearFile.asTypedList(clearFile.length);
  pointerList.setAll(0, clearFile);
  final Pointer<Utf8> nativeFilename = filename.toNativeUtf8();
  final Pointer<Pointer<Uint8>> result = calloc<Pointer<Uint8>>();
  final Pointer<Int> resultLen = calloc<Int>();
  final Pointer<Pointer<NativeSealdError>> err =
      calloc<Pointer<NativeSealdError>>();

  final int resultCode = _bindings.SealdEncryptionSession_EncryptFile(
      _ptr.pointer(),
      nativeClearFile,
      clearFile.length,
      nativeFilename,
      result,
      resultLen,
      err);

  calloc.free(nativeClearFile);
  calloc.free(nativeFilename);

  if (resultCode != 0) {
    calloc.free(result);
    calloc.free(resultLen);
    throw SealdException._fromCPtr(err);
  } else {
    // Copying the data in a Dart-created Uint8List, to avoid having to free memory later
    // Cannot use the `finalizer` argument of `asTypedList` because of https://github.com/dart-lang/sdk/issues/55800
    final Uint8List encryptedFile =
        Uint8List.fromList(result.value.asTypedList(resultLen.value));
    calloc.free(result.value);
    calloc.free(result);
    calloc.free(resultLen);
    calloc.free(err);
    return encryptedFile;
  }
}