| 1 | import 'dart:io'; |
| 2 | import 'dart:typed_data'; |
| 3 | import 'package:cw_core/utils/file.dart' as file; |
| 4 | import 'package:cake_backup/backup.dart' as cwb; |
| 5 | |
| 6 | EncryptionFileUtils encryptionFileUtilsFor(bool direct) => |
| 7 | direct ? XChaCha20EncryptionFileUtils() : Salsa20EncryhptionFileUtils(); |
| 8 | |
| 9 | abstract class EncryptionFileUtils { |
| 10 | Future<void> write({required String path, required String password, required String data}); |
| 11 | Future<String> read({required String path, required String password}); |
| 12 | } |
| 13 | |
| 14 | class Salsa20EncryhptionFileUtils extends EncryptionFileUtils { |
| 15 | // Requires legacy complex key + iv as password |
| 16 | @override |
| 17 | Future<void> write( |
| 18 | {required String path, required String password, required String data}) async => |
| 19 | await file.write(path: path, password: password, data: data); |
| 20 | |
| 21 | // Requires legacy complex key + iv as password |
| 22 | @override |
| 23 | Future<String> read({required String path, required String password}) async => |
| 24 | await file.read(path: path, password: password); |
| 25 | } |
| 26 | |
| 27 | class XChaCha20EncryptionFileUtils extends EncryptionFileUtils { |
| 28 | @override |
| 29 | Future<void> write({required String path, required String password, required String data}) async { |
| 30 | final encrypted = await cwb.encrypt(password, Uint8List.fromList(data.codeUnits)); |
| 31 | await File(path).writeAsBytes(encrypted); |
| 32 | } |
| 33 | |
| 34 | @override |
| 35 | Future<String> read({required String path, required String password}) async { |
| 36 | final file = File(path); |
| 37 | final encrypted = await file.readAsBytes(); |
| 38 | final bytes = await cwb.decrypt(password, encrypted); |
| 39 | return String.fromCharCodes(bytes); |
| 40 | } |
| 41 | } |