π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[mob] Simplified v2 version
Neeraj Gupta3ebf3e3cda61
diff --git a/mobile/apps/photos/lib/models/file/file.dart b/mobile/apps/photos/lib/models/file/file.dartindex 8f55363277..971bafdf64 100644--- a/mobile/apps/photos/lib/models/file/file.dart+++ b/mobile/apps/photos/lib/models/file/file.dart@@ -63,6 +63,7 @@ class EnteFile {// in Version 1, live photo hash is stored as zip's hash.// in V2: LivePhoto hash is stored as imgHash:vidHashstatic const kCurrentMetadataVersion = 2;+ static const kMetadataSimplifiedEncVersion = 3;static final _logger = Logger('File');diff --git a/mobile/apps/photos/lib/utils/file_uploader.dart b/mobile/apps/photos/lib/utils/file_uploader.dartindex e8bc6de704..a3966466ca 100644--- a/mobile/apps/photos/lib/utils/file_uploader.dart+++ b/mobile/apps/photos/lib/utils/file_uploader.dart@@ -625,17 +625,24 @@ class FileUploader {}} else if (encryptedFileExists) {// otherwise just delete the file for singlepart upload+ _logger.severe('File exists without multipart entry, deleting file');await File(encryptedFilePath).delete();}await _checkIfWithinStorageLimit(mediaUploadData.sourceFile!);final encryptedFile = File(encryptedFilePath);final EncryptionResult fileAttributes = multiPartFileEncResult ??- await CryptoUtil.encryptFile(- mediaUploadData.sourceFile!.path,- encryptedFilePath,- key: key,- );+ (flagService.internalUser+ ? await CryptoUtil.encryptFileV2(+ mediaUploadData.sourceFile!.path,+ encryptedFilePath,+ key: key,+ )+ : await CryptoUtil.encryptFile(+ mediaUploadData.sourceFile!.path,+ encryptedFilePath,+ key: key,+ ));late final Uint8List? thumbnailData;if (mediaUploadData.thumbnail == null &&@@ -722,6 +729,9 @@ class FileUploader {null,mediaUploadData.exifData,);+ file.metadataVersion = flagService.internalUser+ ? EnteFile.kMetadataSimplifiedEncVersion+ : EnteFile.kCurrentMetadataVersion;final metadata =await file.getMetadataForUpload(mediaUploadData, exifTime);diff --git a/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart b/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dartindex 52202c5ac9..d1b62acc6a 100644--- a/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart+++ b/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart@@ -10,6 +10,7 @@ import "package:flutter_sodium/flutter_sodium.dart";import "package:logging/logging.dart";const int encryptionChunkSize = 4 * 1024 * 1024;+// 17 bytes of overhead per chunkfinal int decryptionChunkSize =encryptionChunkSize + Sodium.cryptoSecretstreamXchacha20poly1305Abytes;const int hashChunkSize = 4 * 1024 * 1024;@@ -81,10 +82,83 @@ EncryptionResult chachaEncryptData(Map<String, dynamic> args) {);}+// chachaEncryptFileV2 does chucked encryption similar to chachaEncryptFile.+// This implementation is refactored to simplify the logic to make it easier to+// maintain and reason about.+// Rolling out this version 2 in phases to ensure stability+Future<EncryptionResult> chachaEncryptFileV2(Map<String, dynamic> args) async {+ final encryptionStartTime = DateTime.now().millisecondsSinceEpoch;+ final logger = Logger("chachaEncryptFileV2");+ final sourceFile = File(args["sourceFilePath"]);+ final destinationFile = File(args["destinationFilePath"]);+ if (destinationFile.existsSync() && (destinationFile.lengthSync() > 0)) {+ logger.warning("Destination file already exists and is not empty");+ throw Exception("Destination file already exists and is not empty");+ }+ final sourceFileLength = await sourceFile.length();+ logger.info("Encrypting file of size " + sourceFileLength.toString());++ final inputFile = sourceFile.openSync(mode: FileMode.read);+ final key = args["key"] ?? Sodium.cryptoSecretstreamXchacha20poly1305Keygen();+ final initPushResult =+ Sodium.cryptoSecretstreamXchacha20poly1305InitPush(key);+ var bytesRead = 0;+ var tag = Sodium.cryptoSecretstreamXchacha20poly1305TagMessage;+ while (tag != Sodium.cryptoSecretstreamXchacha20poly1305TagFinal) {+ final bool isLastChunk =+ bytesRead + encryptionChunkSize >= sourceFileLength;+ final int chunkSize =+ isLastChunk ? (sourceFileLength - bytesRead) : encryptionChunkSize;++ // Read until we have the full chunk size (or reach EOF)+ final buffer = BytesBuilder();+ while (buffer.length < chunkSize) {+ final remainingBytes = chunkSize - buffer.length;+ final readBytes = await inputFile.read(remainingBytes);+ if (readBytes.isEmpty) break; // EOF reached unexpectedly+ buffer.add(readBytes);+ }++ final bufferBytes = buffer.toBytes();+ bytesRead += bufferBytes.length;+ if (bufferBytes.length != chunkSize) {+ throw Exception(+ "Expected to read $chunkSize bytes, but got ${bufferBytes.length} bytes",+ );+ }+ // Set final tag only after confirming we've read all expected data+ if (isLastChunk) {+ if (bytesRead == sourceFileLength) {+ tag = Sodium.cryptoSecretstreamXchacha20poly1305TagFinal;+ } else {+ throw Exception(+ "Expected $sourceFileLength bytes, but read $bytesRead bytes",+ );+ }+ }+ final encryptedData = Sodium.cryptoSecretstreamXchacha20poly1305Push(+ initPushResult.state,+ bufferBytes,+ null,+ tag,+ );+ await destinationFile.writeAsBytes(encryptedData, mode: FileMode.append);+ }+ await inputFile.close();++ logger.info(+ "Encryption time: " ++ (DateTime.now().millisecondsSinceEpoch - encryptionStartTime)+ .toString(),+ );++ return EncryptionResult(key: key, header: initPushResult.header);+}+// Encrypts a given file, in chunks of encryptionChunkSizeFuture<EncryptionResult> chachaEncryptFile(Map<String, dynamic> args) async {final encryptionStartTime = DateTime.now().millisecondsSinceEpoch;- final logger = Logger("ChaChaEncrypt");+ final logger = Logger("ChaChaEncryptV1");final sourceFile = File(args["sourceFilePath"]);final destinationFile = File(args["destinationFilePath"]);final sourceFileLength = await sourceFile.length();@@ -320,6 +394,26 @@ class CryptoUtil {);}+ // Encrypts the file at sourceFilePath, with the key (if provided) and a+ // randomly generated nonce using XChaCha20 (w Poly1305 MAC), and writes it+ // to the destinationFilePath.+ // If a key is not provided, one is generated and returned.+ static Future<EncryptionResult> encryptFileV2(+ String sourceFilePath,+ String destinationFilePath, {+ Uint8List? key,+ }) {+ final args = <String, dynamic>{};+ args["sourceFilePath"] = sourceFilePath;+ args["destinationFilePath"] = destinationFilePath;+ args["key"] = key;+ return _computer.compute(+ chachaEncryptFileV2,+ param: args,+ taskName: "encryptFileV2",+ );+ }+// Decrypts the file at sourceFilePath, with the given key and header using// XChaCha20 (w Poly1305 MAC), and writes it to the destinationFilePath.static Future<void> decryptFile(