Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Improve upload validation

Neeraj Gupta6bc144f53e23
diff --git a/mobile/apps/photos/lib/core/errors.dart b/mobile/apps/photos/lib/core/errors.dart
index 4bfcc20b4c..10e220043e 100644
--- a/mobile/apps/photos/lib/core/errors.dart
+++ b/mobile/apps/photos/lib/core/errors.dart
@@ -142,3 +142,11 @@ class InvalidDateTimeError implements Exception {
'(id: $assetId, title: ${assetTitle ?? "unknown"}) - $originalError';
}
}
+
+class BadMD5DigestError implements Exception {
+ final String message;
+ BadMD5DigestError(this.message);
+
+ @override
+ String toString() => message;
+}
diff --git a/mobile/apps/photos/lib/db/upload_locks_db.dart b/mobile/apps/photos/lib/db/upload_locks_db.dart
index 498eb56904..448aedca1b 100644
--- a/mobile/apps/photos/lib/db/upload_locks_db.dart
+++ b/mobile/apps/photos/lib/db/upload_locks_db.dart
@@ -1,4 +1,5 @@
import 'dart:async';
+import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart';
@@ -35,6 +36,8 @@ class UploadLocksDB {
columnPartSize: "part_size",
columnLastAttemptedAt: "last_attempted_at",
columnCreatedAt: "created_at",
+ columnFileMd5: "file_md5",
+ columnPartMd5s: "part_md5s",
);
static const _partsTable = (
@@ -67,7 +70,20 @@ class UploadLocksDB {
static final migrationScripts = [
..._createTrackUploadsTable(),
+ ..._addMD5Columns(),
];
+ static List<String> _addMD5Columns() {
+ return [
+ '''
+ ALTER TABLE ${_trackUploadTable.table}
+ ADD COLUMN ${_trackUploadTable.columnFileMd5} TEXT;
+ ''',
+ '''
+ ALTER TABLE ${_trackUploadTable.table}
+ ADD COLUMN ${_trackUploadTable.columnPartMd5s} TEXT;
+ ''',
+ ];
+ }
final dbConfig = MigrationConfig(
initializationScript: initializationScript,
@@ -121,7 +137,7 @@ class UploadLocksDB {
${_trackUploadTable.columnStatus} TEXT DEFAULT '${MultipartStatus.pending.name}' NOT NULL,
${_trackUploadTable.columnPartSize} INTEGER NOT NULL,
${_trackUploadTable.columnLastAttemptedAt} INTEGER NOT NULL,
- ${_trackUploadTable.columnCreatedAt} INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL
+ ${_trackUploadTable.columnCreatedAt} INTEGER DEFAULT CURRENT_TIMESTAMP NOT NULL,
)
''',
'''
@@ -329,6 +345,14 @@ class UploadLocksDB {
partsURLs: partsURLs,
);
+ // Retrieve MD5 data
+ final String? fileMd5 = row[_trackUploadTable.columnFileMd5] as String?;
+ List<String>? partMd5s;
+ if (row[_trackUploadTable.columnPartMd5s] != null) {
+ final partMd5sJson = row[_trackUploadTable.columnPartMd5s] as String;
+ partMd5s = List<String>.from(jsonDecode(partMd5sJson));
+ }
+
return MultipartInfo(
urls: urls,
status: MultipartStatus.values
@@ -337,6 +361,8 @@ class UploadLocksDB {
partETags: partETags,
encFileSize: encFileSize,
partSize: row[_trackUploadTable.columnPartSize] as int,
+ fileMd5: fileMd5,
+ partMd5s: partMd5s,
);
}
@@ -435,6 +461,8 @@ class UploadLocksDB {
String fileNonce,
String keyNonce, {
required int partSize,
+ String? fileMd5,
+ List<String>? partMd5s,
}) async {
final db = await database;
final objectKey = urls.objectKey;
@@ -455,6 +483,9 @@ class UploadLocksDB {
_trackUploadTable.columnPartSize: partSize,
_trackUploadTable.columnLastAttemptedAt:
DateTime.now().millisecondsSinceEpoch,
+ if (fileMd5 != null) _trackUploadTable.columnFileMd5: fileMd5,
+ if (partMd5s != null)
+ _trackUploadTable.columnPartMd5s: jsonEncode(partMd5s),
},
);
diff --git a/mobile/apps/photos/lib/module/upload/model/multipart.dart b/mobile/apps/photos/lib/module/upload/model/multipart.dart
index 94a97ebc36..ed0c39d6b2 100644
--- a/mobile/apps/photos/lib/module/upload/model/multipart.dart
+++ b/mobile/apps/photos/lib/module/upload/model/multipart.dart
@@ -36,6 +36,8 @@ class MultipartInfo {
final int encFileSize;
final MultipartUploadURLs urls;
final MultipartStatus status;
+ final String? fileMd5;
+ final List<String>? partMd5s;
MultipartInfo({
this.partUploadStatus,
@@ -44,6 +46,8 @@ class MultipartInfo {
this.status = MultipartStatus.pending,
required this.encFileSize,
required this.urls,
+ this.fileMd5,
+ this.partMd5s,
});
}
diff --git a/mobile/apps/photos/lib/module/upload/service/multipart.dart b/mobile/apps/photos/lib/module/upload/service/multipart.dart
index f97dde5043..7ca979bf0a 100644
--- a/mobile/apps/photos/lib/module/upload/service/multipart.dart
+++ b/mobile/apps/photos/lib/module/upload/service/multipart.dart
@@ -1,11 +1,15 @@
+import "dart:convert";
import "dart:io";
+import "package:convert/convert.dart";
+import "package:crypto/crypto.dart";
import "package:dio/dio.dart";
import "package:ente_crypto/ente_crypto.dart";
import "package:ente_feature_flag/ente_feature_flag.dart";
import "package:flutter/foundation.dart";
import "package:logging/logging.dart";
import "package:photos/core/constants.dart";
+import "package:photos/core/errors.dart";
import "package:photos/db/upload_locks_db.dart";
import "package:photos/module/upload/model/multipart.dart";
import "package:photos/module/upload/model/xml.dart";
@@ -26,7 +30,7 @@ class MultiPartUploader {
this._featureFlagService,
);
- Future<EncryptionResult> getEncryptionResult(
+ Future<FileEncryptResult> getEncryptionResult(
String localId,
String fileHash,
int collectionID,
@@ -45,13 +49,24 @@ class MultiPartUploader {
final encryptKeyNonce = CryptoUtil.base642bin(result.keyNonce);
- return EncryptionResult(
+ // Get the full multipart info to access MD5 data
+ final multipartInfo = await _db.getCachedLinks(
+ localId,
+ fileHash,
+ collectionID,
+ encFileName,
+ );
+
+ return FileEncryptResult(
key: CryptoUtil.decryptSync(
encryptedFileKey,
collectionKey,
encryptKeyNonce,
),
header: fileNonce,
+ fileMd5: multipartInfo.fileMd5,
+ partMd5s: multipartInfo.partMd5s,
+ partSize: multipartInfo.partSize,
);
}
@@ -91,8 +106,10 @@ class MultiPartUploader {
String encryptedFileName,
int fileSize,
Uint8List fileKey,
- Uint8List fileNonce,
- ) async {
+ Uint8List fileNonce, {
+ String? fileMd5,
+ List<String>? partMd5s,
+ }) async {
final collectionKey =
CollectionsService.instance.getCollectionKey(collectionID);
@@ -112,6 +129,8 @@ class MultiPartUploader {
CryptoUtil.bin2base64(fileNonce),
CryptoUtil.bin2base64(encryptedResult.nonce!),
partSize: multipartPartSizeForUpload,
+ fileMd5: fileMd5,
+ partMd5s: partMd5s,
);
}
@@ -184,11 +203,18 @@ class MultiPartUploader {
Future<String> putMultipartFile(
MultipartUploadURLs urls,
File encryptedFile,
- int fileSize,
- ) async {
+ int fileSize, {
+ String? fileMd5,
+ List<String>? partMd5s,
+ }) async {
// upload individual parts and get their etags
final etags = await _uploadParts(
- MultipartInfo(urls: urls, encFileSize: fileSize),
+ MultipartInfo(
+ urls: urls,
+ encFileSize: fileSize,
+ fileMd5: fileMd5,
+ partMd5s: partMd5s,
+ ),
encryptedFile,
);
@@ -206,6 +232,7 @@ class MultiPartUploader {
final partUploadStatus = partInfo.partUploadStatus;
final partsLength = partsURLs.length;
final etags = partInfo.partETags ?? <int, String>{};
+ final partMd5s = partInfo.partMd5s;
int i = 0;
final partSize = partInfo.partSize ?? multipartPartSizeForUpload;
@@ -237,30 +264,56 @@ class MultiPartUploader {
'Forced exception to test multipart upload retry mechanism.',
);
}
- final response = await _s3Dio.put(
- partURL,
- data: encryptedFile.openRead(
- i * partSize,
- isLastPart ? null : (i + 1) * partSize,
- ),
- options: Options(
- headers: {
- Headers.contentLengthHeader: fileSize,
- Headers.contentTypeHeader: "application/octet-stream",
- },
- ),
- );
- final eTag = response.headers.value("etag");
+ final headers = {
+ Headers.contentLengthHeader: fileSize,
+ Headers.contentTypeHeader: "application/octet-stream",
+ };
- if (eTag?.isEmpty ?? true) {
- throw Exception('ETAG_MISSING');
+ // Add MD5 header if available for this part
+ if (partMd5s != null && i < partMd5s.length) {
+ headers['Content-MD5'] = partMd5s[i];
+ } else if (kDebugMode) {
+ AssertionError('Part MD5s not available for part ${i + 1}');
}
- etags[i] = eTag!;
+ try {
+ final response = await _s3Dio.put(
+ partURL,
+ data: encryptedFile.openRead(
+ i * partSize,
+ isLastPart ? null : (i + 1) * partSize,
+ ),
+ options: Options(
+ headers: headers,
+ ),
+ );
- await _db.updatePartStatus(partInfo.urls.objectKey, i, eTag);
- i++;
+ final eTag = response.headers.value("etag");
+
+ if (eTag?.isEmpty ?? true) {
+ throw Exception('ETAG_MISSING');
+ }
+
+ etags[i] = eTag!;
+
+ await _db.updatePartStatus(partInfo.urls.objectKey, i, eTag);
+ i++;
+ } on DioException catch (e) {
+ if (e.response?.statusCode == 400 &&
+ e.response?.data.toString().contains('BadDigest') == true ||
+ e.response?.data.toString().contains('InvalidDigest') == true) {
+ final comput = await computePartMd5(
+ encryptedFile,
+ i * partSize,
+ isLastPart ? null : (i + 1) * partSize,
+ );
+ throw BadMD5DigestError(
+ "Failed for part ${i + 1} ${e.response?.data}, sent: ${partMd5s?[i]}, computed: $comput, \n all part MD5s: $partMd5s",
+ );
+ }
+ rethrow;
+ }
}
await _db.updateTrackUploadStatus(
@@ -271,6 +324,14 @@ class MultiPartUploader {
return etags;
}
+ Future<String> computePartMd5(File file, int start, int? end) async {
+ final output = AccumulatorSink<Digest>();
+ final input = md5.startChunkedConversion(output);
+ await file.openRead(start, end).forEach(input.add);
+ input.close();
+ return base64Encode(output.events.single.bytes);
+ }
+
Future<void> _completeMultipartUpload(
String objectKey,
Map<int, String> partEtags,
diff --git a/mobile/apps/photos/lib/utils/file_uploader.dart b/mobile/apps/photos/lib/utils/file_uploader.dart
index 7540292cf1..797089fd02 100644
--- a/mobile/apps/photos/lib/utils/file_uploader.dart
+++ b/mobile/apps/photos/lib/utils/file_uploader.dart
@@ -690,7 +690,7 @@ class FileUploader {
);
Uint8List? key;
- final EncryptionResult? multiPartFileEncResult = hasExistingMultiPart
+ final FileEncryptResult? multiPartFileEncResult = hasExistingMultiPart
? await _multiPartUploader.getEncryptionResult(
lockKey,
mediaUploadData.hashData!.fileHash!,
@@ -746,12 +746,35 @@ class FileUploader {
await _checkIfWithinStorageLimit(mediaUploadData.sourceFile!);
final encryptedFile = File(encryptedFilePath);
- final EncryptionResult fileAttributes = multiPartFileEncResult ??
- await CryptoUtil.encryptFile(
- mediaUploadData.sourceFile!.path,
- encryptedFilePath,
- key: key,
- );
+ // Calculate the number of parts to determine if we need MD5
+ // Use source length to estimate encrypted size for part count decision
+ final estimatedEncSize = CryptoUtil.estimateEncryptedSize(sourceLength);
+ final estimatedCount =
+ _multiPartUploader.calculatePartCount(estimatedEncSize);
+
+ FileEncryptResult? fileAttributes = multiPartFileEncResult;
+ String? fileMd5;
+ List<String>? partMd5s;
+
+ if (fileAttributes == null) {
+ final result = flagService.internalUser
+ ? (await CryptoUtil.encryptFileWithMD5(
+ mediaUploadData.sourceFile!.path,
+ encryptedFilePath,
+ key: key,
+ multiPartChunkSizeInBytes: (estimatedCount > 1)
+ ? _multiPartUploader.multipartPartSizeForUpload
+ : null,
+ ))
+ : (await CryptoUtil.encryptFile(
+ mediaUploadData.sourceFile!.path,
+ encryptedFilePath,
+ key: key,
+ ));
+ fileAttributes = result;
+ fileMd5 = result.fileMd5;
+ partMd5s = result.partMd5s;
+ }
late final Uint8List? thumbnailData;
if (mediaUploadData.thumbnail == null &&
@@ -771,7 +794,7 @@ class FileUploader {
final EncryptionResult encryptedThumbnailData =
await CryptoUtil.encryptChaCha(
thumbnailData!,
- fileAttributes.key!,
+ fileAttributes.key,
);
if (File(encryptedThumbnailPath).existsSync()) {
await File(encryptedThumbnailPath).delete();
@@ -807,8 +830,12 @@ class FileUploader {
_logger.internalInfo(
"[UPLOAD-DEBUG] File URL obtained, uploading actual file (size: ${formatBytes(encFileSize)})...",
);
- fileObjectKey =
- await _putFile(fileUploadURL, encryptedFile, encFileSize);
+ fileObjectKey = await _putFile(
+ fileUploadURL,
+ encryptedFile,
+ encFileSize,
+ contentMd5: fileMd5,
+ );
_logger.internalInfo(
"[UPLOAD-DEBUG] Actual file uploaded successfully!",
);
@@ -836,13 +863,17 @@ class FileUploader {
fileUploadURLs,
encFileName,
encFileSize,
- fileAttributes.key!,
- fileAttributes.header!,
+ fileAttributes.key,
+ fileAttributes.header,
+ fileMd5: fileMd5,
+ partMd5s: partMd5s,
);
fileObjectKey = await _multiPartUploader.putMultipartFile(
fileUploadURLs,
encryptedFile,
encFileSize,
+ fileMd5: fileMd5,
+ partMd5s: partMd5s,
);
}
// in case of multipart, upload the thumbnail towards the end to avoid
@@ -866,10 +897,9 @@ class FileUploader {
final encryptedMetadataResult = await CryptoUtil.encryptChaCha(
utf8.encode(jsonEncode(metadata)),
- fileAttributes.key!,
+ fileAttributes.key,
);
- final fileDecryptionHeader =
- CryptoUtil.bin2base64(fileAttributes.header!);
+ final fileDecryptionHeader = CryptoUtil.bin2base64(fileAttributes.header);
final thumbnailDecryptionHeader =
CryptoUtil.bin2base64(encryptedThumbnailData.header!);
final encryptedMetadata = CryptoUtil.bin2base64(
@@ -928,7 +958,7 @@ class FileUploader {
pubMetadataRequest = await getPubMetadataRequest(
file,
pubMetadata,
- fileAttributes.key!,
+ fileAttributes.key,
);
}
await CryptoUtil.decryptVerify(
@@ -995,6 +1025,7 @@ class FileUploader {
}
if ((isMultipartUpload || hasExistingMultiPart) &&
isPutOrMultiPartError(e)) {
+
await UploadLocksDB.instance.deleteMultipartTrack(lockKey);
}
rethrow;
@@ -1041,7 +1072,9 @@ class FileUploader {
}
bool isPutOrMultiPartError(Object e) {
- if (e is MultiPartFileMissingError || e is MultiPartError) {
+ if (e is MultiPartFileMissingError ||
+ e is MultiPartError ||
+ e is BadMD5DigestError) {
return true;
}
if (e is DioException) {
@@ -1298,7 +1331,7 @@ class FileUploader {
int collectionID,
String encryptedKey,
String keyDecryptionNonce,
- EncryptionResult fileAttributes,
+ FileEncryptResult fileAttributes,
String fileObjectKey,
String fileDecryptionHeader,
int fileSize,
@@ -1553,19 +1586,25 @@ class FileUploader {
UploadURL uploadURL,
File file,
int fileSize, {
+ String? contentMd5,
int attempt = 1,
}) async {
final startTime = DateTime.now().millisecondsSinceEpoch;
final fileName = basename(file.path);
int bytesSent = 0;
try {
+ final Map<String, dynamic> headers = {
+ Headers.contentLengthHeader: fileSize,
+ };
+ if (contentMd5 != null) {
+ headers['Content-MD5'] = contentMd5;
+ }
+
await _dio.put(
uploadURL.url,
data: file.openRead(),
options: Options(
- headers: {
- Headers.contentLengthHeader: fileSize,
- },
+ headers: headers,
),
onSendProgress: (sent, total) {
bytesSent = sent;
@@ -1588,6 +1627,7 @@ class FileUploader {
newUploadURL,
file,
fileSize,
+ contentMd5: contentMd5,
attempt: attempt + 1,
);
} else {
diff --git a/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart b/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart
index d24dfa75e4..015064c569 100644
--- a/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart
+++ b/mobile/apps/photos/plugins/ente_crypto/lib/src/crypto.dart
@@ -3,9 +3,12 @@ import "dart:io";
import 'dart:typed_data';
import "package:computer/computer.dart";
+import "package:convert/convert.dart";
+import "package:crypto/crypto.dart";
import "package:ente_crypto/src/models/derived_key_result.dart";
import "package:ente_crypto/src/models/encryption_result.dart";
import "package:ente_crypto/src/models/errors.dart";
+import "package:flutter/foundation.dart";
import "package:flutter_sodium/flutter_sodium.dart";
import "package:logging/logging.dart";
@@ -86,7 +89,7 @@ EncryptionResult chachaEncryptData(Map<String, dynamic> args) {
// 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 {
+Future<FileEncryptResult> chachaEncryptFileV2(Map<String, dynamic> args) async {
final encryptionStartTime = DateTime.now().millisecondsSinceEpoch;
final logger = Logger("chachaEncryptFileV2");
final sourceFile = File(args["sourceFilePath"]);
@@ -152,11 +155,14 @@ Future<EncryptionResult> chachaEncryptFileV2(Map<String, dynamic> args) async {
.toString(),
);
- return EncryptionResult(key: key, header: initPushResult.header);
+ return FileEncryptResult(
+ key: key,
+ header: initPushResult.header,
+ );
}
// Encrypts a given file, in chunks of encryptionChunkSize
-Future<EncryptionResult> chachaEncryptFile(Map<String, dynamic> args) async {
+Future<FileEncryptResult> chachaEncryptFile(Map<String, dynamic> args) async {
final encryptionStartTime = DateTime.now().millisecondsSinceEpoch;
final logger = Logger("ChaChaEncryptV1");
final sourceFile = File(args["sourceFilePath"]);
@@ -199,7 +205,261 @@ Future<EncryptionResult> chachaEncryptFile(Map<String, dynamic> args) async {
.toString(),
);
- return EncryptionResult(key: key, header: initPushResult.header);
+ return FileEncryptResult(
+ key: key,
+ header: initPushResult.header,
+ );
+}
+
+// Encrypts a file with MD5 calculation and real-time verification
+Future<FileEncryptResult> chachaEncryptFileWithVerification(
+ Map<String, dynamic> args,
+) async {
+ final encryptionStartTime = DateTime.now();
+ final logger = Logger("ChaChaEncryptWithMD5");
+ final sourceFile = File(args["sourceFilePath"]);
+ final destinationFile = File(args["destinationFilePath"]);
+ final int? multiPartChunkSizeInBytes = args["multiPartChunkSizeInBytes"];
+ final sourceFileLength = await sourceFile.length();
+
+ logger.info("Encrypting file of size $sourceFileLength");
+ if (multiPartChunkSizeInBytes != null) {
+ logger.info("Using multipart chunk size: $multiPartChunkSizeInBytes bytes");
+ }
+
+ // Use openSync for simpler, predictable chunk reading
+ final inputFile = sourceFile.openSync(mode: FileMode.read);
+
+ // Use streaming write
+ final outSink = destinationFile.openWrite(mode: FileMode.writeOnly);
+
+ final key = args["key"] ?? Sodium.cryptoSecretstreamXchacha20poly1305Keygen();
+ final initPushResult =
+ Sodium.cryptoSecretstreamXchacha20poly1305InitPush(key);
+
+ // Initialize verification state
+ final verifyPullState = Sodium.cryptoSecretstreamXchacha20poly1305InitPull(
+ initPushResult.header,
+ key,
+ );
+
+ // MD5 setup
+ AccumulatorSink<Digest>? fullAccumulator;
+ ChunkedConversionSink<List<int>>? fullMd5Sink;
+ AccumulatorSink<Digest>? partAccumulator;
+ ChunkedConversionSink<List<int>>? partMd5Sink;
+
+ final List<String> partMd5s = [];
+ final BytesBuilder partBuffer = BytesBuilder();
+
+ if (multiPartChunkSizeInBytes == null) {
+ fullAccumulator = AccumulatorSink<Digest>();
+ fullMd5Sink = md5.startChunkedConversion(fullAccumulator);
+ } else {
+ partAccumulator = AccumulatorSink<Digest>();
+ partMd5Sink = md5.startChunkedConversion(partAccumulator);
+ }
+
+ var bytesRead = 0;
+ var totalEncryptedBytes = 0;
+ var tag = Sodium.cryptoSecretstreamXchacha20poly1305TagMessage;
+ var chunkIndex = 0;
+
+ try {
+ while (tag != Sodium.cryptoSecretstreamXchacha20poly1305TagFinal) {
+ chunkIndex++;
+ var chunkSize = encryptionChunkSize;
+ if (bytesRead + chunkSize >= sourceFileLength) {
+ chunkSize = sourceFileLength - bytesRead;
+ tag = Sodium.cryptoSecretstreamXchacha20poly1305TagFinal;
+ }
+
+ final buffer = await inputFile.read(chunkSize);
+ if (buffer.length != chunkSize) {
+ throw Exception(
+ "$kPartialReadErrorTag to read $chunkSize bytes, but got ${buffer.length} bytes",
+ );
+ }
+
+ bytesRead += chunkSize;
+
+ // Encrypt
+ final encryptedData = Sodium.cryptoSecretstreamXchacha20poly1305Push(
+ initPushResult.state,
+ buffer,
+ null,
+ tag,
+ );
+
+ // Verify with optimized comparison
+ try {
+ final pullResult = Sodium.cryptoSecretstreamXchacha20poly1305Pull(
+ verifyPullState,
+ encryptedData,
+ null,
+ );
+
+ // Use fast comparison
+ if (!_uint8listEquals(pullResult.m, buffer)) {
+ throw Exception(
+ "$kBitFlipErrorTag Data corruption detected at chunk $chunkIndex",
+ );
+ }
+
+ if (pullResult.tag != tag) {
+ throw Exception(
+ "$kBitFlipErrorTag Tag mismatch at chunk $chunkIndex",
+ );
+ }
+ } catch (e) {
+ await inputFile.close();
+ await outSink.close();
+ await destinationFile.delete();
+ if (e.toString().startsWith(kBitFlipErrorTag)) {
+ rethrow;
+ }
+ throw Exception(
+ "$kBitFlipErrorTag Verification failed at chunk $chunkIndex: $e",
+ );
+ }
+
+ // Handle MD5 calculation and disk writes
+ totalEncryptedBytes += encryptedData.length;
+
+ if (multiPartChunkSizeInBytes == null) {
+ // Single-part: stream MD5 and write directly
+ fullMd5Sink!.add(encryptedData);
+ outSink.add(encryptedData);
+ } else {
+ // Multi-part: buffer data and flush at exact part boundaries
+ partBuffer.add(encryptedData);
+
+ final bool isLastChunk =
+ tag == Sodium.cryptoSecretstreamXchacha20poly1305TagFinal;
+
+ // Flush complete parts from buffer
+ while (partBuffer.length >= multiPartChunkSizeInBytes) {
+ final partBytes =
+ partBuffer.toBytes().sublist(0, multiPartChunkSizeInBytes);
+
+ // Calculate MD5 for this part
+ partMd5Sink!.add(partBytes);
+ partMd5Sink.close();
+ final digest = partAccumulator!.events.single;
+ partMd5s.add(base64.encode(digest.bytes));
+
+ logger.info(
+ "Part ${partMd5s.length}: $multiPartChunkSizeInBytes bytes",
+ );
+
+ // Write to disk
+ outSink.add(partBytes);
+
+ // Keep remaining bytes for next part
+ final remaining =
+ partBuffer.toBytes().sublist(multiPartChunkSizeInBytes);
+ partBuffer.clear();
+ partBuffer.add(remaining);
+
+ // Start new MD5 for next part (if not last)
+ if (!isLastChunk || partBuffer.isNotEmpty) {
+ partAccumulator = AccumulatorSink<Digest>();
+ partMd5Sink = md5.startChunkedConversion(partAccumulator);
+ }
+ }
+
+ // Handle last chunk (remaining data < partSize)
+ if (isLastChunk && partBuffer.isNotEmpty) {
+ final lastPartBytes = partBuffer.toBytes();
+
+ // Calculate MD5 for last part
+ partMd5Sink!.add(lastPartBytes);
+ partMd5Sink.close();
+ final digest = partAccumulator!.events.single;
+ partMd5s.add(base64.encode(digest.bytes));
+
+ // Write to disk
+ outSink.add(lastPartBytes);
+ partBuffer.clear();
+ }
+ }
+ }
+
+ await inputFile.close();
+
+ // Finalize MD5
+ String? finalFileMd5;
+ if (multiPartChunkSizeInBytes == null && fullMd5Sink != null) {
+ fullMd5Sink.close();
+ final digest = fullAccumulator!.events.single;
+ finalFileMd5 = base64.encode(digest.bytes);
+ logger.info("File MD5: $finalFileMd5");
+ }
+
+ // Ensure all data is written
+ await outSink.flush();
+ await outSink.close();
+
+ final encryptionTimeSeconds = (DateTime.now().millisecondsSinceEpoch -
+ encryptionStartTime.millisecondsSinceEpoch) /
+ 1000;
+ final partsInfo =
+ multiPartChunkSizeInBytes != null ? " Parts: ${partMd5s.length}" : "";
+ debugPrint(
+ "FileEncryption: Time: ${encryptionTimeSeconds}s "
+ "Total encrypted: $totalEncryptedBytes bytes$partsInfo",
+ );
+
+ return FileEncryptResult(
+ key: key,
+ header: initPushResult.header,
+ fileMd5: finalFileMd5,
+ partMd5s: multiPartChunkSizeInBytes != null && partMd5s.isNotEmpty
+ ? partMd5s
+ : null,
+ partSize: multiPartChunkSizeInBytes,
+ );
+ } catch (e) {
+ try {
+ await inputFile.close();
+ } catch (_) {}
+ try {
+ await outSink.close();
+ } catch (_) {}
+ if (await destinationFile.exists()) {
+ try {
+ await destinationFile.delete();
+ } catch (_) {}
+ }
+ rethrow;
+ }
+}
+
+// Fast equality check for Uint8List
+bool _uint8listEquals(Uint8List a, Uint8List b) {
+ if (identical(a, b)) return true;
+ if (a.length != b.length) return false;
+
+ final len = a.length;
+ int i = 0;
+
+ // Compare 8 bytes at a time for speed
+ while (i + 7 < len) {
+ final va =
+ a.buffer.asByteData().getUint64(a.offsetInBytes + i, Endian.little);
+ final vb =
+ b.buffer.asByteData().getUint64(b.offsetInBytes + i, Endian.little);
+ if (va != vb) return false;
+ i += 8;
+ }
+
+ // Remaining bytes
+ while (i < len) {
+ if (a[i] != b[i]) return false;
+ i++;
+ }
+
+ return true;
}
Future<void> chachaDecryptFile(Map<String, dynamic> args) async {
@@ -501,7 +761,7 @@ class CryptoUtil {
// 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> encryptFile(
+ static Future<FileEncryptResult> encryptFile(
String sourceFilePath,
String destinationFilePath, {
Uint8List? key,
@@ -511,7 +771,7 @@ class CryptoUtil {
args["destinationFilePath"] = destinationFilePath;
args["key"] = key;
return _computer
- .compute<Map<String, dynamic>, EncryptionResult>(
+ .compute<Map<String, dynamic>, FileEncryptResult>(
chachaEncryptFile,
param: args,
taskName: "encryptFile",
@@ -523,7 +783,7 @@ class CryptoUtil {
// 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(
+ static Future<FileEncryptResult> encryptFileV2(
String sourceFilePath,
String destinationFilePath, {
Uint8List? key,
@@ -539,6 +799,29 @@ class CryptoUtil {
);
}
+ // Encrypts the file with MD5 calculation and real-time verification
+ static Future<FileEncryptResult> encryptFileWithMD5(
+ String sourceFilePath,
+ String destinationFilePath, {
+ Uint8List? key,
+ int? multiPartChunkSizeInBytes,
+ }) {
+ final args = <String, dynamic>{};
+ args["sourceFilePath"] = sourceFilePath;
+ args["destinationFilePath"] = destinationFilePath;
+ args["key"] = key;
+ if (multiPartChunkSizeInBytes != null) {
+ args["multiPartChunkSizeInBytes"] = multiPartChunkSizeInBytes;
+ }
+ return _computer
+ .compute<Map<String, dynamic>, FileEncryptResult>(
+ chachaEncryptFileWithVerification,
+ param: args,
+ taskName: "encryptFileWithMD5",
+ )
+ .unwrapExceptionInComputer();
+ }
+
// 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(
@@ -753,6 +1036,25 @@ class CryptoUtil {
);
}
+ /// Estimates the encrypted size for a given plaintext size.
+ /// Takes into account the ChaCha20-Poly1305 overhead per chunk.
+ static int estimateEncryptedSize(int plainTextSize) {
+ if (plainTextSize <= 0) {
+ return 0;
+ }
+
+ final int chunkOverhead = Sodium.cryptoSecretstreamXchacha20poly1305Abytes;
+ final int fullChunks = plainTextSize ~/ encryptionChunkSize;
+ final int lastChunkSize = plainTextSize % encryptionChunkSize;
+
+ int estimatedSize = fullChunks * (encryptionChunkSize + chunkOverhead);
+ if (lastChunkSize > 0) {
+ estimatedSize += lastChunkSize + chunkOverhead;
+ }
+
+ return estimatedSize;
+ }
+
/// Validates that the plaintext and ciphertext sizes match for streaming encryption.
/// Returns true if the sizes are valid for chunked ChaCha20-Poly1305 encryption.
///
@@ -766,18 +1068,7 @@ class CryptoUtil {
return false;
}
- final int chunkOverhead = Sodium.cryptoSecretstreamXchacha20poly1305Abytes;
-
- // Calculate expected ciphertext size
- final int fullChunks = plainTextSize ~/ encryptionChunkSize;
- final int lastChunkSize = plainTextSize % encryptionChunkSize;
-
- int expectedCipherTextSize =
- fullChunks * (encryptionChunkSize + chunkOverhead);
- if (lastChunkSize > 0) {
- expectedCipherTextSize += lastChunkSize + chunkOverhead;
- }
-
+ final int expectedCipherTextSize = estimateEncryptedSize(plainTextSize);
return expectedCipherTextSize == cipherTextSize;
}
}
diff --git a/mobile/apps/photos/plugins/ente_crypto/lib/src/models/chacha_encryption_result.dart b/mobile/apps/photos/plugins/ente_crypto/lib/src/models/chacha_encryption_result.dart
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/mobile/apps/photos/plugins/ente_crypto/lib/src/models/encryption_result.dart b/mobile/apps/photos/plugins/ente_crypto/lib/src/models/encryption_result.dart
index 9da16c573c..8c54ed3832 100644
--- a/mobile/apps/photos/plugins/ente_crypto/lib/src/models/encryption_result.dart
+++ b/mobile/apps/photos/plugins/ente_crypto/lib/src/models/encryption_result.dart
@@ -13,3 +13,21 @@ class EncryptionResult {
this.nonce,
});
}
+
+class FileEncryptResult {
+ // Key using which the file is encrypted
+ final Uint8List key;
+ // Header used for decrypting the file. This is stored in DB. We need both key and header to decrypt the file.
+ final Uint8List header;
+ final String? fileMd5;
+ final List<String>? partMd5s;
+ final int? partSize;
+
+ FileEncryptResult({
+ required this.key,
+ required this.header,
+ this.fileMd5,
+ this.partMd5s,
+ this.partSize,
+ });
+}
diff --git a/mobile/apps/photos/plugins/ente_crypto/lib/src/models/errors.dart b/mobile/apps/photos/plugins/ente_crypto/lib/src/models/errors.dart
index 939c4bd8ee..ecb8860413 100644
--- a/mobile/apps/photos/plugins/ente_crypto/lib/src/models/errors.dart
+++ b/mobile/apps/photos/plugins/ente_crypto/lib/src/models/errors.dart
@@ -38,6 +38,7 @@ extension FutureErrorHandling<T> on Future<T> {
const kPartialReadErrorTag = 'PartialRead';
const kStreamPullError = 'crypto_secretstream_xchacha20poly1305_pull';
const kVerificationErrorTag = 'VerificationError';
+const kBitFlipErrorTag = 'BitFlipDetected';
// Exception counterpart for upstream handling via catchError chains
class PartialReadException implements Exception {
@@ -62,3 +63,11 @@ class VerificationError implements Exception {
return 'VerificationError: $message';
}
}
+
+class BitFlipError implements Exception {
+ final String message;
+ BitFlipError(this.message);
+
+ @override
+ String toString() => 'BitFlipError: $message';
+}
diff --git a/mobile/apps/photos/plugins/ente_crypto/pubspec.lock b/mobile/apps/photos/plugins/ente_crypto/pubspec.lock
index 06ccfec1eb..cad7a5c8d3 100644
--- a/mobile/apps/photos/plugins/ente_crypto/pubspec.lock
+++ b/mobile/apps/photos/plugins/ente_crypto/pubspec.lock
@@ -26,6 +26,22 @@ packages:
url: "https://github.com/ente-io/computer.git"
source: git
version: "3.2.1"
+ convert:
+ dependency: "direct main"
+ description:
+ name: convert
+ sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.1.2"
+ crypto:
+ dependency: "direct main"
+ description:
+ name: crypto
+ sha256: "1e445881f28f22d6140f181e07737b22f1e099a5e1ff94b0af2f9e4a463f4855"
+ url: "https://pub.dev"
+ source: hosted
+ version: "3.0.6"
ffi:
dependency: transitive
description:
@@ -92,6 +108,14 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
+ typed_data:
+ dependency: transitive
+ description:
+ name: typed_data
+ sha256: f9049c039ebfeb4cf7a7104a675823cd72dba8297f264b6637062516699fa006
+ url: "https://pub.dev"
+ source: hosted
+ version: "1.4.0"
vector_math:
dependency: transitive
description:
diff --git a/mobile/apps/photos/plugins/ente_crypto/pubspec.yaml b/mobile/apps/photos/plugins/ente_crypto/pubspec.yaml
index a3aea1ca8a..18b6605536 100644
--- a/mobile/apps/photos/plugins/ente_crypto/pubspec.yaml
+++ b/mobile/apps/photos/plugins/ente_crypto/pubspec.yaml
@@ -9,6 +9,8 @@ dependencies:
collection:
computer:
git: "https://github.com/ente-io/computer.git"
+ convert: ^3.1.1
+ crypto: ^3.0.3
flutter:
sdk: flutter
flutter_sodium: ^0.2.0
diff --git a/mobile/apps/photos/pubspec.lock b/mobile/apps/photos/pubspec.lock
index 43fc965232..b5e2ba014d 100644
--- a/mobile/apps/photos/pubspec.lock
+++ b/mobile/apps/photos/pubspec.lock
@@ -358,7 +358,7 @@ packages:
source: hosted
version: "2.0.1"
convert:
- dependency: transitive
+ dependency: "direct main"
description:
name: convert
sha256: b30acd5944035672bc15c6b7a8b47d773e41e2f17de064350988c5d02adb1c68
diff --git a/mobile/apps/photos/pubspec.yaml b/mobile/apps/photos/pubspec.yaml
index a7458764aa..ec4cfd7f70 100644
--- a/mobile/apps/photos/pubspec.yaml
+++ b/mobile/apps/photos/pubspec.yaml
@@ -39,6 +39,7 @@ dependencies:
computer: # logged task name in verbose in fork
git: "https://github.com/ente-io/computer.git"
connectivity_plus: ^6.0.2
+ convert: ^3.1.1
crypto: ^3.0.2
cupertino_icons: ^1.0.0
dart_ui_isolate: ^1.1.1