Skip to content

armgit / ente

Public Imported from GitHub
0

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

Add proton authenticator import with

Prateek Sunalbce3e21a706f
diff --git a/mobile/apps/auth/lib/l10n/arb/app_en.arb b/mobile/apps/auth/lib/l10n/arb/app_en.arb
index 89b1635ddd..2873deeacb 100644
--- a/mobile/apps/auth/lib/l10n/arb/app_en.arb
+++ b/mobile/apps/auth/lib/l10n/arb/app_en.arb
@@ -121,7 +121,7 @@
"importAegisGuide": "Use the \"Export the vault\" option in Aegis's Settings.\n\nIf your vault is encrypted, you will need to enter vault password to decrypt the vault.",
"import2FasGuide": "Use the \"Settings->Backup -Export\" option in 2FAS.\n\nIf your backup is encrypted, you will need to enter the password to decrypt the backup",
"importLastpassGuide": "Use the \"Transfer accounts\" option within Lastpass Authenticator Settings and press \"Export accounts to file\". Import the JSON downloaded.",
- "importProtonAuthGuide": "Use the \"Export\" option in Proton Authenticator Settings to export your codes.",
+ "importProtonAuthGuide": "Use the \"Export\" option in Proton Authenticator Settings to export your codes.\n\nIf your export is password protected, you will need to enter the password to decrypt it.",
"exportCodes": "Export codes",
"importLabel": "Import",
"importInstruction": "Please select a file that contains a list of your codes in the following format",
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/proton_import.dart b/mobile/apps/auth/lib/ui/settings/data/import/proton_import.dart
index 8b5e126f92..b48119fec5 100644
--- a/mobile/apps/auth/lib/ui/settings/data/import/proton_import.dart
+++ b/mobile/apps/auth/lib/ui/settings/data/import/proton_import.dart
@@ -1,19 +1,19 @@
import 'dart:async';
-import 'dart:convert';
import 'dart:io';
import 'package:ente_auth/l10n/l10n.dart';
-import 'package:ente_auth/models/code.dart';
import 'package:ente_auth/services/authenticator_service.dart';
import 'package:ente_auth/store/code_store.dart';
import 'package:ente_auth/ui/components/buttons/button_widget.dart';
import 'package:ente_auth/ui/components/dialog_widget.dart';
import 'package:ente_auth/ui/components/models/button_type.dart';
import 'package:ente_auth/ui/settings/data/import/import_success.dart';
+import 'package:ente_auth/ui/settings/data/import/proton_import_parser.dart';
import 'package:ente_auth/utils/dialog_util.dart';
import 'package:ente_ui/components/progress_dialog.dart';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
+import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:logging/logging.dart';
@@ -49,24 +49,26 @@ Future<void> showProtonImportInstruction(BuildContext context) async {
Future<void> _pickProtonJsonFile(BuildContext context) async {
final l10n = context.l10n;
- FilePickerResult? result = await FilePicker.platform
- .pickFiles(dialogTitle: l10n.importSelectJsonFile);
+ final result = await FilePicker.platform.pickFiles(
+ dialogTitle: l10n.importSelectJsonFile,
+ );
if (result == null) {
return;
}
- final ProgressDialog progressDialog =
- createProgressDialog(context, l10n.pleaseWait);
+
+ final progressDialog = createProgressDialog(context, l10n.pleaseWait);
await progressDialog.show();
+
try {
- String path = result.files.single.path!;
- int? count = await _processProtonExportFile(context, path, progressDialog);
+ final path = result.files.single.path!;
+ final count = await _processProtonExportFile(context, path, progressDialog);
await progressDialog.hide();
if (count != null) {
await importSuccessDialog(context, count);
}
} catch (e, s) {
Logger('ProtonImport')
- .severe('exception while processing proton import', e, s);
+ .severe('Exception while processing Proton import', e, s);
await progressDialog.hide();
await showErrorDialog(
context,
@@ -79,15 +81,14 @@ Future<void> _pickProtonJsonFile(BuildContext context) async {
Future<int?> _processProtonExportFile(
BuildContext context,
String path,
- final ProgressDialog dialog,
+ ProgressDialog dialog,
) async {
- File file = File(path);
+ final jsonString = await File(path).readAsString();
- final jsonString = await file.readAsString();
- final decodedJson = jsonDecode(jsonString);
-
- // Validate that this is a Proton export
- if (decodedJson['version'] == null || decodedJson['entries'] == null) {
+ Map<String, dynamic> decodedJson;
+ try {
+ decodedJson = decodeProtonExportJson(jsonString);
+ } on FormatException {
await dialog.hide();
await showErrorDialog(
context,
@@ -97,75 +98,56 @@ Future<int?> _processProtonExportFile(
return null;
}
- final parsedCodes = <Code>[];
- final entries = decodedJson['entries'] as List;
-
- for (var entry in entries) {
+ if (isEncryptedProtonExport(decodedJson)) {
+ await dialog.hide();
+ String? password;
try {
- final content = entry['content'];
- if (content == null) {
- continue; // Skip entries without content
- }
-
- final entryType = content['entry_type'] as String?;
- if (entryType != 'Totp' && entryType != 'Steam') {
- // log warning
- Logger('ProtonImport').warning('Unsupported entry type: $entryType');
- continue; // Skip non-TOTP and non-Steam entries
+ await showTextInputDialog(
+ context,
+ title: context.l10n.passwordForDecryptingExport,
+ submitButtonLabel: context.l10n.submit,
+ isPasswordInput: true,
+ onSubmit: (value) async {
+ password = value;
+ },
+ );
+ if (password == null) {
+ return null;
}
- Code code;
-
- if (entryType == 'Steam') {
- // Handle Steam entries with steam:// format
- final steamUri = content['uri'] as String?;
- if (steamUri == null || !steamUri.startsWith('steam://')) {
- continue; // Skip invalid Steam URIs
- }
-
- final secret = steamUri.split('steam://')[1];
- final name = content['name'] as String? ?? '';
-
- code = Code.fromAccountAndSecret(
- Type.steam,
- '', // Steam doesn't typically have separate account
- name, // Use name as issuer
- secret,
- null,
- Code.steamDigits,
- );
- } else {
- // Handle TOTP entries with otpauth:// format
- final otpUri = content['uri'] as String?;
- if (otpUri == null || !otpUri.startsWith('otpauth://')) {
- continue; // Skip invalid OTP URIs
- }
- // Create code from OTP auth URL
- code = Code.fromOTPAuthUrl(otpUri);
- }
-
- // Add note if present
- final note = entry['note'] as String?;
- if (note != null && note.isNotEmpty) {
- code = code.copyWith(
- display: code.display.copyWith(note: note),
+ await dialog.show();
+ final decryptedJsonString = await compute(
+ _decryptProtonExportInBackground,
+ {
+ 'jsonString': jsonString,
+ 'password': password!,
+ },
+ );
+ decodedJson = decodeProtonExportJson(decryptedJsonString);
+ } catch (e, s) {
+ Logger('ProtonImport').warning('Failed to decrypt Proton export', e, s);
+ await dialog.hide();
+ if (password != null) {
+ await showErrorDialog(
+ context,
+ context.l10n.incorrectPasswordTitle,
+ context.l10n.pleaseCheckPasswordAndTryAgain,
);
}
-
- parsedCodes.add(code);
- } catch (e, s) {
- Logger('ProtonImport').warning('Failed to parse entry', e, s);
- // Continue processing other entries
+ return null;
}
}
- // Add all parsed codes to the store
+ final parsedCodes = parseProtonExport(decodedJson);
for (final code in parsedCodes) {
await CodeStore.instance.addCode(code, shouldSync: false);
}
- // Trigger sync
unawaited(AuthenticatorService.instance.onlineSync());
-
return parsedCodes.length;
}
+
+String _decryptProtonExportInBackground(Map<String, String> params) {
+ final decodedJson = decodeProtonExportJson(params['jsonString']!);
+ return decryptProtonExport(decodedJson, password: params['password']!);
+}
diff --git a/mobile/apps/auth/lib/ui/settings/data/import/proton_import_parser.dart b/mobile/apps/auth/lib/ui/settings/data/import/proton_import_parser.dart
new file mode 100644
index 0000000000..9a6f454a60
--- /dev/null
+++ b/mobile/apps/auth/lib/ui/settings/data/import/proton_import_parser.dart
@@ -0,0 +1,162 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:ente_auth/models/code.dart';
+import 'package:logging/logging.dart';
+import 'package:pointycastle/export.dart';
+
+const _protonExportVersion = 1;
+const _protonExportNonceLength = 12;
+const _protonExportMacSizeBits = 128;
+const _protonExportSaltLength = 16;
+const _protonExportPasswordKeyLength = 32;
+const _protonExportAad = 'proton.authenticator.export.v1';
+
+final _logger = Logger('ProtonImportParser');
+
+Map<String, dynamic> decodeProtonExportJson(String jsonString) {
+ final decodedJson = jsonDecode(jsonString);
+ if (decodedJson is! Map) {
+ throw const FormatException('Invalid Proton export');
+ }
+ return Map<String, dynamic>.from(decodedJson);
+}
+
+bool isEncryptedProtonExport(Map<String, dynamic> decodedJson) {
+ return decodedJson['salt'] != null &&
+ decodedJson['content'] != null &&
+ decodedJson['entries'] == null;
+}
+
+List<Code> parseProtonExport(Map<String, dynamic> decodedJson) {
+ if (isEncryptedProtonExport(decodedJson)) {
+ throw const FormatException('Password protected Proton export');
+ }
+
+ final version = decodedJson['version'];
+ final entries = decodedJson['entries'];
+ if (version != _protonExportVersion || entries is! List) {
+ throw const FormatException('Invalid Proton export');
+ }
+
+ final parsedCodes = <Code>[];
+ for (final entry in entries) {
+ if (entry is! Map) {
+ continue;
+ }
+
+ try {
+ final entryMap = Map<String, dynamic>.from(entry);
+ final content = entryMap['content'];
+ if (content is! Map) {
+ continue;
+ }
+
+ final contentMap = Map<String, dynamic>.from(content);
+ final entryType = contentMap['entry_type'] as String?;
+
+ Code code;
+ switch (entryType) {
+ case 'Steam':
+ final steamUri = contentMap['uri'] as String?;
+ if (steamUri == null || !steamUri.startsWith('steam://')) {
+ continue;
+ }
+
+ final name = (contentMap['name'] as String?)?.trim();
+ code = Code.fromAccountAndSecret(
+ Type.steam,
+ '',
+ name == null || name.isEmpty ? 'Steam' : name,
+ steamUri.substring('steam://'.length),
+ null,
+ Code.steamDigits,
+ );
+ break;
+ case 'Totp':
+ final otpUri = contentMap['uri'] as String?;
+ if (otpUri == null || !otpUri.startsWith('otpauth://')) {
+ continue;
+ }
+ code = Code.fromOTPAuthUrl(otpUri);
+ break;
+ default:
+ _logger.warning('Unsupported Proton entry type: $entryType');
+ continue;
+ }
+
+ final note = entryMap['note'] as String?;
+ if (note != null && note.isNotEmpty) {
+ code = code.copyWith(
+ display: code.display.copyWith(note: note),
+ );
+ }
+
+ parsedCodes.add(code);
+ } catch (e, s) {
+ _logger.warning('Failed to parse Proton export entry', e, s);
+ }
+ }
+
+ return parsedCodes;
+}
+
+String decryptProtonExport(
+ Map<String, dynamic> decodedJson, {
+ required String password,
+}) {
+ if (!isEncryptedProtonExport(decodedJson)) {
+ throw const FormatException('Invalid Proton export');
+ }
+
+ final saltBase64 = decodedJson['salt'];
+ final contentBase64 = decodedJson['content'];
+ if (saltBase64 is! String || contentBase64 is! String) {
+ throw const FormatException('Invalid Proton export');
+ }
+
+ final salt = base64Decode(saltBase64);
+ if (salt.length != _protonExportSaltLength) {
+ throw const FormatException('Invalid Proton export salt');
+ }
+
+ final encryptedBytes = base64Decode(contentBase64);
+ if (encryptedBytes.length <= _protonExportNonceLength) {
+ throw const FormatException('Invalid Proton export content');
+ }
+
+ final key = _deriveProtonPasswordKey(password, Uint8List.fromList(salt));
+ final nonce = encryptedBytes.sublist(0, _protonExportNonceLength);
+ final cipherText = encryptedBytes.sublist(_protonExportNonceLength);
+
+ final cipher = GCMBlockCipher(AESEngine())
+ ..init(
+ false,
+ AEADParameters(
+ KeyParameter(key),
+ _protonExportMacSizeBits,
+ nonce,
+ Uint8List.fromList(utf8.encode(_protonExportAad)),
+ ),
+ );
+
+ final decryptedBytes = cipher.process(cipherText);
+ return utf8.decode(decryptedBytes);
+}
+
+Uint8List _deriveProtonPasswordKey(String password, Uint8List salt) {
+ final generator = Argon2BytesGenerator()
+ ..init(
+ Argon2Parameters(
+ Argon2Parameters.ARGON2_id,
+ salt,
+ desiredKeyLength: _protonExportPasswordKeyLength,
+ iterations: 2,
+ memory: 19 * 1024,
+ lanes: 1,
+ version: Argon2Parameters.ARGON2_VERSION_13,
+ ),
+ );
+
+ return generator.process(Uint8List.fromList(utf8.encode(password)));
+}
diff --git a/mobile/apps/auth/test/ui/settings/data/import/fixtures/proton_authenticator_backup.json b/mobile/apps/auth/test/ui/settings/data/import/fixtures/proton_authenticator_backup.json
new file mode 100644
index 0000000000..7149cd7bbe
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/data/import/fixtures/proton_authenticator_backup.json
@@ -0,0 +1 @@
+{"version":1,"entries":[{"id":"31122360-ffdc-49ec-a1e1-696cd67564b6","content":{"uri":"otpauth://totp/sean.hickey%2B2fa%40userlane.com?secret=J4YFC3TZKVYWCVCNIVBWIV2GHFAXUNDF&issuer=Userlane+Realm&algorithm=SHA1&digits=6&period=30","entry_type":"Totp","name":"[email protected]"},"note":null},{"id":"defcaa63-c551-41f1-82b7-810279c201fb","content":{"uri":"otpauth://totp/john.appleseed%40example.org?secret=554vbdogjrldg2jv&algorithm=SHA1&digits=6&period=30","entry_type":"Totp","name":"[email protected]"},"note":null},{"id":"ca7e81f3-8959-4b25-9714-150a01a0971e","content":{"uri":"otpauth://totp/ravin%40prontomarketing.com?secret=PIBTGMBYQYVSLN5PVZYQUTKYHOBRYYT7&issuer=Simplesat&algorithm=SHA1&digits=6&period=30","entry_type":"Totp","name":"[email protected]"},"note":null},{"id":"61cb558f-eca9-4c77-9347-c8e461df54e5","content":{"uri":"otpauth://totp/dele%40countersoft.com?secret=MI4GCOJSGIZTKLJSGMZWKLJUGEZDQLJYG5STILJSMUYDIYTCMQ3TSOJRGI&issuer=Gemini&algorithm=SHA1&digits=6&period=30","entry_type":"Totp","name":"[email protected]"},"note":null}]}
diff --git a/mobile/apps/auth/test/ui/settings/data/import/fixtures/proton_authenticator_backup_encrypted_1231246.json b/mobile/apps/auth/test/ui/settings/data/import/fixtures/proton_authenticator_backup_encrypted_1231246.json
new file mode 100644
index 0000000000..d32e65a4fe
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/data/import/fixtures/proton_authenticator_backup_encrypted_1231246.json
@@ -0,0 +1 @@
+{"version":1,"salt":"ahTn0MTM/OG3vGs+nkLGVg==","content":"YYQI+yGhcpoGRGZYxrhN17UQquHgy0veJAW3DlhFFLnnAAFBKK5D0esMcw03I268WauJPszVI++EV3m2okNidzQKS2/zTBBFVxdtJEyiD7t7zPukRRgt9wvjO3R7z56/RhZaWAgJzF8Rw1ZtB9nRYByrGEpSJ6YI+YfT9l7bT3dQOw/r45Ec+I2rEhGN4/0kVRyhPXCAy4roztBJogxNZs+0wIx6rTHYK2Mlsx37YFejWaDHorCz1ukYoBYIV2HP5WswMyyvYdVsXULKePvhrBSLmy3un1s/T/qcMHndFR86nMXRsCXtIFL0BZDbvaOCJkAQh9rF0Zf9E8SdsM33H2qjTxWBVafJoqLOTjbsuhITszHc+UCLcgS/A0GPyqmTXvEH/AwM5UHQs7Ts+6lqnzVZnFOHEzKQzRj1u4VBdc+XGGyOOszbnMASUb2kKVHSisP/VhqO3NxHDoeSbiJxBxii7bSWC1l82sjxtSu41pmKB9ZhFDji5n6ABO2flIc943W4Jfg8gN0KYy6q2rpL0K9krg+m4ckz+/bZ76dD5l55hOLdBzXOEtlrUKWxw8+STdrCGAtXmceEHXtfC7F3cwCuyvfvg2TD4tgrR5o+YqHBMqZwEINaQxQWLw7Q5pI5QS3m3QgUpBs/nQ82ZkM+594+GoLTmumrn1GbZ5gCu4VqDrPpdP/mRf0Ib7b+wASEPs7IITeqvrUxMi5czyhrEAqt6F+/YpFeGc7vvmoOCMWyLqpDIKueRKE1HZp6QabPHbnjfYrFonLzwNjrmkaLMoyXU7QM0CoKzuxkTiv0hwG908rUDPgqY7ZWiOpBP6EXmhu6lTSEw3seC7w2dubtMBTzqcebLHjH1Csiac+7xYDevPOvp+8y18mgf10FfVL1GOZ+/dGvUOcK/0y71OxDRqVn2Q8ILxBSvjf73edPiI/uk0U3Nqe1WbEGLwn4bkb9Bn8D5rQZag2fotpJDn7905ZhdWrUv585sUf19qDI8rukD05WeHVafIbfCMji3BE85dwGi1TXs8fju+CAdo5LX72/8L2VY2q4n1+xmNAcZZkppDJb4syEEMcZQhjVNe0VxrIZapG946Fd9O0IvX0fA9EJnn1SaCsgQlmcEOQQemUiKbuk4RPCr3FJ3elkp0S93nfysufXrMs2pptQnsAgAb8SQ3dyUXgETcKlfIjBOxGYDFdTe4VbNcADnrQs9BLOFaSMz/okXuSwv46dwxwOGeLKWbix4kIlTcd7yGiugC4reIaxjU7lWZC2Cr4eEFLOMNC+r/AqbsdUAZJfwhN2Zytc8PQm9ijTG+sLar4Vz0hwkHGcjE7hMxiVxUkkZLlCA0jTmWcrb7roz5WPHnRfhqNWycadTkq8lBNIjP06aOrunO8dJf7ktwtV4oC6DUf+GdyvuqYmoNfUJyYKQctBd1Tqw/kCMwjaJjxNxb46U165GZgCr5qLosnRI3UlYOI6FWMCygkQx2XiPlIC"}
diff --git a/mobile/apps/auth/test/ui/settings/data/import/proton_import_parser_test.dart b/mobile/apps/auth/test/ui/settings/data/import/proton_import_parser_test.dart
new file mode 100644
index 0000000000..0939bc1acf
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/data/import/proton_import_parser_test.dart
@@ -0,0 +1,70 @@
+import 'dart:io';
+
+import 'package:ente_auth/models/code.dart';
+import 'package:ente_auth/ui/settings/data/import/proton_import_parser.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+void main() {
+ group('Proton import parser', () {
+ test('parses plaintext Proton exports from fixture', () async {
+ final exportJson = decodeProtonExportJson(
+ await _fixture('proton_authenticator_backup.json').readAsString(),
+ );
+
+ final codes = parseProtonExport(exportJson);
+
+ expect(codes, hasLength(4));
+
+ expect(codes.first.type, Type.totp);
+ expect(codes.first.issuer, 'Userlane Realm');
+ expect(codes.first.account, '[email protected]');
+
+ expect(codes[1].issuer, '[email protected]');
+ expect(codes[1].account, '[email protected]');
+
+ expect(codes[2].issuer, 'Simplesat');
+ expect(codes[2].account, '[email protected]');
+
+ expect(codes[3].issuer, 'Gemini');
+ expect(codes[3].account, '[email protected]');
+ });
+
+ test('decrypts password protected Proton exports from fixture', () async {
+ final encryptedJson = decodeProtonExportJson(
+ await _fixture(
+ 'proton_authenticator_backup_encrypted_1231246.json',
+ ).readAsString(),
+ );
+
+ expect(isEncryptedProtonExport(encryptedJson), isTrue);
+
+ final decryptedJson = decryptProtonExport(
+ encryptedJson,
+ password: '1231246',
+ );
+ final codes = parseProtonExport(decodeProtonExportJson(decryptedJson));
+
+ expect(codes, hasLength(4));
+ expect(codes.first.issuer, 'Userlane Realm');
+ expect(codes.last.issuer, 'Gemini');
+ });
+
+ test('fails to decrypt password protected Proton exports with bad password',
+ () async {
+ final encryptedJson = decodeProtonExportJson(
+ await _fixture(
+ 'proton_authenticator_backup_encrypted_1231246.json',
+ ).readAsString(),
+ );
+
+ expect(
+ () => decryptProtonExport(encryptedJson, password: 'wrong-password'),
+ throwsA(isA<Exception>()),
+ );
+ });
+ });
+}
+
+File _fixture(String name) => File(
+ 'test/ui/settings/data/import/fixtures/$name',
+ );
diff --git a/mobile/apps/auth/test/ui/settings/data/import/proton_import_test.dart b/mobile/apps/auth/test/ui/settings/data/import/proton_import_test.dart
new file mode 100644
index 0000000000..b01b553225
--- /dev/null
+++ b/mobile/apps/auth/test/ui/settings/data/import/proton_import_test.dart
@@ -0,0 +1,150 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:ente_auth/models/code.dart';
+import 'package:ente_auth/ui/settings/data/import/proton_import_parser.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:pointycastle/export.dart';
+
+void main() {
+ test('parses Proton Authenticator exports', () {
+ final codes = parseProtonExport({
+ 'version': 1,
+ 'entries': [
+ {
+ 'id': 'totp-id',
+ 'content': {
+ 'uri':
+ 'otpauth://totp/GitHub:alice?secret=JBSWY3DPEHPK3PXP&issuer=GitHub&algorithm=SHA1&digits=6&period=30',
+ 'entry_type': 'Totp',
+ 'name': 'alice',
+ },
+ 'note': 'work account',
+ },
+ {
+ 'id': 'steam-id',
+ 'content': {
+ 'uri': 'steam://STEAMSECRET',
+ 'entry_type': 'Steam',
+ 'name': 'Steam',
+ },
+ 'note': 'gaming',
+ },
+ ],
+ });
+
+ expect(codes, hasLength(2));
+
+ expect(codes[0].type, Type.totp);
+ expect(codes[0].issuer, 'GitHub');
+ expect(codes[0].account, 'alice');
+ expect(codes[0].note, 'work account');
+
+ expect(codes[1].type, Type.steam);
+ expect(codes[1].issuer, 'Steam');
+ expect(codes[1].secret, 'STEAMSECRET');
+ expect(codes[1].note, 'gaming');
+ });
+
+ test('detects password protected Proton exports', () {
+ final encryptedExport = _createEncryptedExport(
+ jsonEncode({
+ 'version': 1,
+ 'entries': [
+ {
+ 'id': 'totp-id',
+ 'content': {
+ 'uri':
+ 'otpauth://totp/GitHub:alice?secret=JBSWY3DPEHPK3PXP&issuer=GitHub&algorithm=SHA1&digits=6&period=30',
+ 'entry_type': 'Totp',
+ 'name': 'alice',
+ },
+ },
+ ],
+ }),
+ password: 'secret',
+ );
+
+ expect(isEncryptedProtonExport(encryptedExport), isTrue);
+ });
+
+ test('decrypts password protected Proton exports', () {
+ final encryptedExport = _createEncryptedExport(
+ jsonEncode({
+ 'version': 1,
+ 'entries': [
+ {
+ 'id': 'steam-id',
+ 'content': {
+ 'uri': 'steam://STEAMSECRET',
+ 'entry_type': 'Steam',
+ 'name': 'Steam',
+ },
+ 'note': 'gaming',
+ },
+ ],
+ }),
+ password: 'secret',
+ );
+
+ final decryptedJson = decryptProtonExport(
+ encryptedExport,
+ password: 'secret',
+ );
+ final codes = parseProtonExport(decodeProtonExportJson(decryptedJson));
+
+ expect(codes, hasLength(1));
+ expect(codes.single.type, Type.steam);
+ expect(codes.single.secret, 'STEAMSECRET');
+ expect(codes.single.note, 'gaming');
+ });
+}
+
+Map<String, dynamic> _createEncryptedExport(
+ String plaintextExport, {
+ required String password,
+}) {
+ final salt = Uint8List.fromList(List<int>.generate(16, (index) => index + 1));
+ final nonce = Uint8List.fromList(
+ List<int>.generate(12, (index) => index + 31),
+ );
+ final derivedKey = _deriveProtonPasswordKey(password, salt);
+
+ final cipher = GCMBlockCipher(AESEngine())
+ ..init(
+ true,
+ AEADParameters(
+ KeyParameter(derivedKey),
+ 128,
+ nonce,
+ Uint8List.fromList(utf8.encode('proton.authenticator.export.v1')),
+ ),
+ );
+ final encryptedBytes = cipher.process(
+ Uint8List.fromList(utf8.encode(plaintextExport)),
+ );
+ final payload = Uint8List.fromList([...nonce, ...encryptedBytes]);
+
+ return {
+ 'version': 1,
+ 'salt': base64Encode(salt),
+ 'content': base64Encode(payload),
+ };
+}
+
+Uint8List _deriveProtonPasswordKey(String password, Uint8List salt) {
+ final generator = Argon2BytesGenerator()
+ ..init(
+ Argon2Parameters(
+ Argon2Parameters.ARGON2_id,
+ salt,
+ desiredKeyLength: 32,
+ iterations: 2,
+ memory: 19 * 1024,
+ lanes: 1,
+ version: Argon2Parameters.ARGON2_VERSION_13,
+ ),
+ );
+
+ return generator.process(Uint8List.fromList(utf8.encode(password)));
+}