// Encryption for dash-sync (PROTOCOL.md "Keys" + "A batch"), byte for byte what the dashboard's // sync.py does with PyNaCl: a batch = "DS1\0" + 24-byte nonce + XChaCha20-Poly1305-IETF(data key, // nonce, zlib(JSON), ad = "dash-sync/1/"); the data key sits on the server wrapped with // Argon2id(passphrase). Argon2id with 64 MB takes a second or two, so it runs in its own isolate. import 'dart:convert'; import 'dart:io'; import 'dart:isolate'; import 'dart:typed_data'; import 'package:sodium/sodium_sumo.dart'; const _magic = [0x44, 0x53, 0x31, 0x00]; // "DS1\0" const _keyAd = 'dash-sync/key/1'; class SyncCrypto { SyncCrypto._(this._sodium); static Future create() async => SyncCrypto._(await SodiumSumoInit.init()); final SodiumSumo _sodium; Aead get _aead => _sodium.crypto.aeadXChaCha20Poly1305IETF; Uint8List _ad(String account) => utf8.encode('dash-sync/1/$account'); /// JSON → zlib → sealed batch, ready to POST. Uint8List sealBatch(Uint8List key, Map batch, String account) { final plain = Uint8List.fromList(ZLibCodec(level: 6).encode(utf8.encode(jsonEncode(batch)))); final nonce = _sodium.randombytes.buf(24); final k = SecureKey.fromList(_sodium, key); try { final box = _aead.encrypt(message: plain, nonce: nonce, key: k, additionalData: _ad(account)); return Uint8List.fromList([..._magic, ...nonce, ...box]); } finally { k.dispose(); } } /// A sealed batch → its JSON. Throws on a wrong key / account or a damaged batch. Map openBatch(Uint8List key, Uint8List blob, String account) { if (blob.length < 28 + 16 || !_listEq(blob.sublist(0, 4), _magic)) { throw const FormatException('not a sync batch'); } final k = SecureKey.fromList(_sodium, key); try { final plain = _aead.decrypt( cipherText: blob.sublist(28), nonce: blob.sublist(4, 28), key: k, additionalData: _ad(account)); return jsonDecode(utf8.decode(ZLibCodec().decode(plain))) as Map; } finally { k.dispose(); } } /// The data key from the server's wrapped key + the passphrase (in a background isolate). /// Throws [WrongPassphrase]. static Future unwrap(Map w, String passphrase) => Isolate.run(() async => _unwrap(await SodiumSumoInit.init(), w, passphrase)); static Uint8List _unwrap(SodiumSumo s, Map w, String passphrase) { if (w['kdf'] != 'argon2id13') throw FormatException('unknown kdf ${w['kdf']}'); final kek = s.crypto.pwhash( outLen: 32, password: Int8List.fromList(utf8.encode(passphrase)), salt: base64Decode(w['salt'] as String), opsLimit: w['ops'] as int, memLimit: w['mem'] as int, alg: CryptoPwhashAlgorithm.argon2id13, ); try { // a copy: what libsodium returns is a view on native memory that's freed with the isolate return Uint8List.fromList(s.crypto.aeadXChaCha20Poly1305IETF.decrypt( cipherText: base64Decode(w['box'] as String), nonce: base64Decode(w['nonce'] as String), key: kek, additionalData: utf8.encode(_keyAd), )); } on SodiumException { throw const WrongPassphrase(); } finally { kek.dispose(); } } /// The recovery key ("ABCD-EFGH-…", base32 of the data key) → the data key. static Uint8List fromRecovery(String code) { const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; final s = code.replaceAll(RegExp(r'[\s-]'), '').toUpperCase(); final out = []; var buf = 0, bits = 0; for (final ch in s.split('')) { final v = alphabet.indexOf(ch); if (v < 0) throw const FormatException("that's not a recovery key"); buf = (buf << 5) | v; bits += 5; if (bits >= 8) { bits -= 8; out.add((buf >> bits) & 0xff); } } if (out.length != 32) throw const FormatException("that's not a recovery key"); return Uint8List.fromList(out); } static bool _listEq(List a, List b) { if (a.length != b.length) return false; for (var i = 0; i < a.length; i++) { if (a[i] != b[i]) return false; } return true; } } class WrongPassphrase implements Exception { const WrongPassphrase(); @override String toString() => 'Wrong passphrase'; }