]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/ImportExportActivity.java
Switch to the new Day/Night theme. https://redmine.stoutner.com/issues/522
[PrivacyBrowserAndroid.git] / app / src / main / java / com / stoutner / privacybrowser / activities / ImportExportActivity.java
1 /*
2  * Copyright © 2018-2020 Soren Stoutner <soren@stoutner.com>.
3  *
4  * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
5  *
6  * Privacy Browser is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * Privacy Browser is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with Privacy Browser.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 package com.stoutner.privacybrowser.activities;
21
22 import android.Manifest;
23 import android.app.Activity;
24 import android.content.Intent;
25 import android.content.SharedPreferences;
26 import android.content.pm.PackageManager;
27 import android.media.MediaScannerConnection;
28 import android.net.Uri;
29 import android.os.Build;
30 import android.os.Bundle;
31 import android.os.Environment;
32 import android.os.Handler;
33 import android.preference.PreferenceManager;
34 import android.provider.DocumentsContract;
35 import android.text.Editable;
36 import android.text.TextWatcher;
37 import android.view.View;
38 import android.view.WindowManager;
39 import android.widget.AdapterView;
40 import android.widget.ArrayAdapter;
41 import android.widget.Button;
42 import android.widget.EditText;
43 import android.widget.LinearLayout;
44 import android.widget.RadioButton;
45 import android.widget.Spinner;
46 import android.widget.TextView;
47
48 import androidx.annotation.NonNull;
49 import androidx.appcompat.app.ActionBar;
50 import androidx.appcompat.app.AppCompatActivity;
51 import androidx.appcompat.widget.Toolbar;
52 import androidx.cardview.widget.CardView;
53 import androidx.core.app.ActivityCompat;
54 import androidx.core.content.ContextCompat;
55 import androidx.core.content.FileProvider;
56 import androidx.fragment.app.DialogFragment;
57
58 import com.google.android.material.snackbar.Snackbar;
59 import com.google.android.material.textfield.TextInputLayout;
60
61 import com.stoutner.privacybrowser.R;
62 import com.stoutner.privacybrowser.dialogs.StoragePermissionDialog;
63 import com.stoutner.privacybrowser.helpers.DownloadLocationHelper;
64 import com.stoutner.privacybrowser.helpers.FileNameHelper;
65 import com.stoutner.privacybrowser.helpers.ImportExportDatabaseHelper;
66
67 import java.io.File;
68 import java.io.FileInputStream;
69 import java.io.FileOutputStream;
70 import java.nio.charset.StandardCharsets;
71 import java.security.MessageDigest;
72 import java.security.SecureRandom;
73 import java.util.Arrays;
74
75 import javax.crypto.Cipher;
76 import javax.crypto.CipherInputStream;
77 import javax.crypto.CipherOutputStream;
78 import javax.crypto.spec.GCMParameterSpec;
79 import javax.crypto.spec.SecretKeySpec;
80
81 public class ImportExportActivity extends AppCompatActivity implements StoragePermissionDialog.StoragePermissionDialogListener {
82     // Create the encryption constants.
83     private final int NO_ENCRYPTION = 0;
84     private final int PASSWORD_ENCRYPTION = 1;
85     private final int OPENPGP_ENCRYPTION = 2;
86
87     // Create the activity result constants.
88     private final int BROWSE_RESULT_CODE = 0;
89     private final int OPENPGP_EXPORT_RESULT_CODE = 1;
90
91     // `openKeychainInstalled` is accessed from an inner class.
92     private boolean openKeychainInstalled;
93
94     @Override
95     public void onCreate(Bundle savedInstanceState) {
96         // Get a handle for the shared preferences.
97         SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
98
99         // Get the screenshot preference.
100         boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", false);
101
102         // Disable screenshots if not allowed.
103         if (!allowScreenshots) {
104             getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
105         }
106
107         // Set the theme.
108         setTheme(R.style.PrivacyBrowser);
109
110         // Run the default commands.
111         super.onCreate(savedInstanceState);
112
113         // Set the content view.
114         setContentView(R.layout.import_export_coordinatorlayout);
115
116         // Set the support action bar.
117         Toolbar toolbar = findViewById(R.id.import_export_toolbar);
118         setSupportActionBar(toolbar);
119
120         // Get a handle for the action bar.
121         ActionBar actionBar = getSupportActionBar();
122
123         // Remove the incorrect lint warning that the action bar might be null.
124         assert actionBar != null;
125
126         // Display the home arrow on the support action bar.
127         actionBar.setDisplayHomeAsUpEnabled(true);
128
129         // Find out if the system is running KitKat
130         boolean runningKitKat = (Build.VERSION.SDK_INT == 19);
131
132         // Find out if OpenKeychain is installed.
133         try {
134             openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
135         } catch (PackageManager.NameNotFoundException exception) {
136             openKeychainInstalled = false;
137         }
138
139         // Get handles for the views that need to be modified.
140         Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
141         TextInputLayout passwordEncryptionTextInputLayout = findViewById(R.id.password_encryption_textinputlayout);
142         EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
143         TextView kitKatPasswordEncryptionTextView = findViewById(R.id.kitkat_password_encryption_textview);
144         TextView openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
145         CardView fileLocationCardView = findViewById(R.id.file_location_cardview);
146         RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
147         RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
148         LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
149         EditText fileNameEditText = findViewById(R.id.file_name_edittext);
150         TextView fileDoesNotExistTextView = findViewById(R.id.file_does_not_exist_textview);
151         TextView fileExistsWarningTextView = findViewById(R.id.file_exists_warning_textview);
152         TextView openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
153         Button importExportButton = findViewById(R.id.import_export_button);
154         TextView storagePermissionTextView = findViewById(R.id.import_export_storage_permission_textview);
155
156         // Create an array adapter for the spinner.
157         ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
158
159         // Set the drop down view resource on the spinner.
160         encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
161
162         // Set the array adapter for the spinner.
163         encryptionSpinner.setAdapter(encryptionArrayAdapter);
164
165         // Initially hide the unneeded views.
166         passwordEncryptionTextInputLayout.setVisibility(View.GONE);
167         kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
168         openKeychainRequiredTextView.setVisibility(View.GONE);
169         fileNameLinearLayout.setVisibility(View.GONE);
170         fileDoesNotExistTextView.setVisibility(View.GONE);
171         fileExistsWarningTextView.setVisibility(View.GONE);
172         openKeychainImportInstructionsTextView.setVisibility(View.GONE);
173         importExportButton.setVisibility(View.GONE);
174
175         // Instantiate the download location helper.
176         DownloadLocationHelper downloadLocationHelper = new DownloadLocationHelper();
177
178         // Get the default file path.
179         String defaultFilePath = downloadLocationHelper.getDownloadLocation(this) + "/" + getString(R.string.settings_pbs);
180
181         // Set the other default file paths.
182         String defaultPasswordEncryptionFilePath = defaultFilePath + ".aes";
183         String defaultPgpFilePath = defaultFilePath + ".pgp";
184
185         // Set the default file path.
186         fileNameEditText.setText(defaultFilePath);
187
188         // Hide the storage permission text view if the permission has already been granted.
189         if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
190             storagePermissionTextView.setVisibility(View.GONE);
191         }
192
193         // Update the UI when the spinner changes.
194         encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
195             @Override
196             public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
197                 switch (position) {
198                     case NO_ENCRYPTION:
199                         // Hide the unneeded layout items.
200                         passwordEncryptionTextInputLayout.setVisibility(View.GONE);
201                         kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
202                         openKeychainRequiredTextView.setVisibility(View.GONE);
203                         openKeychainImportInstructionsTextView.setVisibility(View.GONE);
204
205                         // Show the file location card.
206                         fileLocationCardView.setVisibility(View.VISIBLE);
207
208                         // Show the file name linear layout if either import or export is checked.
209                         if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
210                             fileNameLinearLayout.setVisibility(View.VISIBLE);
211                         }
212
213                         // Reset the text of the import button, which may have been changed to `Decrypt`.
214                         if (importRadioButton.isChecked()) {
215                             importExportButton.setText(R.string.import_button);
216                         }
217
218                         // Reset the default file path.
219                         fileNameEditText.setText(defaultFilePath);
220                         break;
221
222                     case PASSWORD_ENCRYPTION:
223                         if (runningKitKat) {
224                             // Show the KitKat password encryption message.
225                             kitKatPasswordEncryptionTextView.setVisibility(View.VISIBLE);
226
227                             // Hide the OpenPGP required text view and the file location card.
228                             openKeychainRequiredTextView.setVisibility(View.GONE);
229                             fileLocationCardView.setVisibility(View.GONE);
230                         } else {
231                             // Hide the OpenPGP layout items.
232                             openKeychainRequiredTextView.setVisibility(View.GONE);
233                             openKeychainImportInstructionsTextView.setVisibility(View.GONE);
234
235                             // Show the password encryption layout items.
236                             passwordEncryptionTextInputLayout.setVisibility(View.VISIBLE);
237
238                             // Show the file location card.
239                             fileLocationCardView.setVisibility(View.VISIBLE);
240
241                             // Show the file name linear layout if either import or export is checked.
242                             if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
243                                 fileNameLinearLayout.setVisibility(View.VISIBLE);
244                             }
245
246                             // Reset the text of the import button, which may have been changed to `Decrypt`.
247                             if (importRadioButton.isChecked()) {
248                                 importExportButton.setText(R.string.import_button);
249                             }
250
251                             // Update the default file path.
252                             fileNameEditText.setText(defaultPasswordEncryptionFilePath);
253                         }
254                         break;
255
256                     case OPENPGP_ENCRYPTION:
257                         // Hide the password encryption layout items.
258                         passwordEncryptionTextInputLayout.setVisibility(View.GONE);
259                         kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
260
261                         // Updated items based on the installation status of OpenKeychain.
262                         if (openKeychainInstalled) {  // OpenKeychain is installed.
263                             // Update the default file path.
264                             fileNameEditText.setText(defaultPgpFilePath);
265
266                             // Show the file location card.
267                             fileLocationCardView.setVisibility(View.VISIBLE);
268
269                             if (importRadioButton.isChecked()) {
270                                 // Show the file name linear layout and the OpenKeychain import instructions.
271                                 fileNameLinearLayout.setVisibility(View.VISIBLE);
272                                 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
273
274                                 // Set the text of the import button to be `Decrypt`.
275                                 importExportButton.setText(R.string.decrypt);
276                             } else if (exportRadioButton.isChecked()) {
277                                 // Hide the file name linear layout and the OpenKeychain import instructions.
278                                 fileNameLinearLayout.setVisibility(View.GONE);
279                                 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
280                             }
281                         } else {  // OpenKeychain is not installed.
282                             // Show the OpenPGP required layout item.
283                             openKeychainRequiredTextView.setVisibility(View.VISIBLE);
284
285                             // Hide the file location card.
286                             fileLocationCardView.setVisibility(View.GONE);
287                         }
288                         break;
289                 }
290             }
291
292             @Override
293             public void onNothingSelected(AdapterView<?> parent) {
294
295             }
296         });
297
298         // Update the status of the import/export button when the password changes.
299         encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
300             @Override
301             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
302                 // Do nothing.
303             }
304
305             @Override
306             public void onTextChanged(CharSequence s, int start, int before, int count) {
307                 // Do nothing.
308             }
309
310             @Override
311             public void afterTextChanged(Editable s) {
312                 // Get the current file name.
313                 String fileNameString = fileNameEditText.getText().toString();
314
315                 // Convert the file name string to a file.
316                 File file = new File(fileNameString);
317
318                 // Update the import/export button.
319                 if (importRadioButton.isChecked()) {  // The import radio button is checked.
320                     // Enable the import button if the file and the password exists.
321                     importExportButton.setEnabled(file.exists() && !encryptionPasswordEditText.getText().toString().isEmpty());
322                 } else if (exportRadioButton.isChecked()) {  // The export radio button is checked.
323                     // Enable the export button if the file string and the password exists.
324                     importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
325                 }
326             }
327         });
328
329         // Update the UI when the file name EditText changes.
330         fileNameEditText.addTextChangedListener(new TextWatcher() {
331             @Override
332             public void beforeTextChanged(CharSequence s, int start, int count, int after) {
333                 // Do nothing.
334             }
335
336             @Override
337             public void onTextChanged(CharSequence s, int start, int before, int count) {
338                 // Do nothing.
339             }
340
341             @Override
342             public void afterTextChanged(Editable s) {
343                 // Get the current file name.
344                 String fileNameString = fileNameEditText.getText().toString();
345
346                 // Convert the file name string to a file.
347                 File file = new File(fileNameString);
348
349                 // Adjust the UI according to the encryption spinner position.
350                 switch (encryptionSpinner.getSelectedItemPosition()) {
351                     case NO_ENCRYPTION:
352                         // Determine if import or export is checked.
353                         if (exportRadioButton.isChecked()) {  // The export radio button is checked.
354                             // Hide the file does not exist text view.
355                             fileDoesNotExistTextView.setVisibility(View.GONE);
356
357                             // Display a warning if the file already exists.
358                             if (file.exists()) {
359                                 fileExistsWarningTextView.setVisibility(View.VISIBLE);
360                             } else {
361                                 fileExistsWarningTextView.setVisibility(View.GONE);
362                             }
363
364                             // Enable the export button if the file name is populated.
365                             importExportButton.setEnabled(!fileNameString.isEmpty());
366                         } else if (importRadioButton.isChecked()) {  // The import radio button is checked.
367                             // Hide the file exists warning text view.
368                             fileExistsWarningTextView.setVisibility(View.GONE);
369
370                             // Check if the file exists.
371                             if (file.exists()) {  // The file exists.
372                                 // Hide the notification that the file does not exist.
373                                 fileDoesNotExistTextView.setVisibility(View.GONE);
374
375                                 // Enable the import button.
376                                 importExportButton.setEnabled(true);
377                             } else {  // The file does not exist.
378                                 // Show a notification that the file does not exist.
379                                 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
380
381                                 // Disable the import button.
382                                 importExportButton.setEnabled(false);
383                             }
384                         } else {  // Neither radio button is checked.
385                             // Hide the file notification text views.
386                             fileExistsWarningTextView.setVisibility(View.GONE);
387                             fileDoesNotExistTextView.setVisibility(View.GONE);
388                         }
389                         break;
390
391                     case PASSWORD_ENCRYPTION:
392                         // Determine if import or export is checked.
393                         if (exportRadioButton.isChecked()) {  // The export radio button is checked.
394                             // Hide the notification that the file does not exist.
395                             fileDoesNotExistTextView.setVisibility(View.GONE);
396
397                             // Display a warning if the file already exists.
398                             if (file.exists()) {
399                                 fileExistsWarningTextView.setVisibility(View.VISIBLE);
400                             } else {
401                                 fileExistsWarningTextView.setVisibility(View.GONE);
402                             }
403
404                             // Enable the export button if the file name and the password are populated.
405                             importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
406                         } else if (importRadioButton.isChecked()) {  // The import radio button is checked.
407                             // Hide the file exists warning text view.
408                             fileExistsWarningTextView.setVisibility(View.GONE);
409
410                             // Check if the file exists.
411                             if (file.exists()) {  // The file exists.
412                                 // Hide the notification that the file does not exist.
413                                 fileDoesNotExistTextView.setVisibility(View.GONE);
414
415                                 // Enable the import button if the password is populated.
416                                 importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
417                             } else {  // The file does not exist.
418                                 // Show a notification that the file does not exist.
419                                 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
420
421                                 // Disable the import button.
422                                 importExportButton.setEnabled(false);
423                             }
424                         } else {  // Neither radio button is checked.
425                             // Hide the file notification text views.
426                             fileExistsWarningTextView.setVisibility(View.GONE);
427                             fileDoesNotExistTextView.setVisibility(View.GONE);
428                         }
429                         break;
430
431                     case OPENPGP_ENCRYPTION:
432                         // Hide the file exists warning text view.
433                         fileExistsWarningTextView.setVisibility(View.GONE);
434
435                         if (importRadioButton.isChecked()) {  // The import radio button is checked.
436                             if (file.exists()) {  // The file exists.
437                                 // Hide the notification that the file does not exist.
438                                 fileDoesNotExistTextView.setVisibility(View.GONE);
439
440                                 // Enable the import button if OpenKeychain is installed.
441                                 importExportButton.setEnabled(openKeychainInstalled);
442                             } else {  // The file does not exist.
443                                 // Show the notification that the file does not exist.
444                                 fileDoesNotExistTextView.setVisibility(View.VISIBLE);
445
446                                 // Disable the import button.
447                                 importExportButton.setEnabled(false);
448                             }
449                         } else if (exportRadioButton.isChecked()){  // The export radio button is checked.
450                             // Hide the notification that the file does not exist.
451                             fileDoesNotExistTextView.setVisibility(View.GONE);
452
453                             // Enable the export button.
454                             importExportButton.setEnabled(true);
455                         } else {  // Neither radio button is checked.
456                             // Hide the notification that the file does not exist.
457                             fileDoesNotExistTextView.setVisibility(View.GONE);
458                         }
459                         break;
460                 }
461             }
462         });
463     }
464
465     public void onClickRadioButton(View view) {
466         // Get handles for the views.
467         Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
468         LinearLayout fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
469         EditText passwordEncryptionEditText = findViewById(R.id.password_encryption_edittext);
470         EditText fileNameEditText = findViewById(R.id.file_name_edittext);
471         TextView fileDoesNotExistTextView = findViewById(R.id.file_does_not_exist_textview);
472         TextView fileExistsWarningTextView = findViewById(R.id.file_exists_warning_textview);
473         TextView openKeychainImportInstructionTextView = findViewById(R.id.openkeychain_import_instructions_textview);
474         Button importExportButton = findViewById(R.id.import_export_button);
475
476         // Get the current file name.
477         String fileNameString = fileNameEditText.getText().toString();
478
479         // Convert the file name string to a file.
480         File file = new File(fileNameString);
481
482         // Check to see if import or export was selected.
483         switch (view.getId()) {
484             case R.id.import_radiobutton:
485                 // Check to see if OpenPGP encryption is selected.
486                 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) {  // OpenPGP encryption selected.
487                     // Show the OpenKeychain import instructions.
488                     openKeychainImportInstructionTextView.setVisibility(View.VISIBLE);
489
490                     // Set the text on the import/export button to be `Decrypt`.
491                     importExportButton.setText(R.string.decrypt);
492                 } else {  // OpenPGP encryption not selected.
493                     // Hide the OpenKeychain import instructions.
494                     openKeychainImportInstructionTextView.setVisibility(View.GONE);
495
496                     // Set the text on the import/export button to be `Import`.
497                     importExportButton.setText(R.string.import_button);
498                 }
499
500                 // Hide the file exists warning text view.
501                 fileExistsWarningTextView.setVisibility(View.GONE);
502
503                 // Display the file name views.
504                 fileNameLinearLayout.setVisibility(View.VISIBLE);
505                 importExportButton.setVisibility(View.VISIBLE);
506
507                 // Check to see if the file exists.
508                 if (file.exists()) {  // The file exists.
509                     // Hide the notification that the file does not exist.
510                     fileDoesNotExistTextView.setVisibility(View.GONE);
511
512                     // Check to see if password encryption is selected.
513                     if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) {  // Password encryption is selected.
514                         // Enable the import button if the encryption password is populated.
515                         importExportButton.setEnabled(!passwordEncryptionEditText.getText().toString().isEmpty());
516                     } else {  // Password encryption is not selected.
517                         // Enable the import/decrypt button.
518                         importExportButton.setEnabled(true);
519                     }
520                 } else {  // The file does not exist.
521                     // Show the notification that the file does not exist.
522                     fileDoesNotExistTextView.setVisibility(View.VISIBLE);
523
524                     // Disable the import/decrypt button.
525                     importExportButton.setEnabled(false);
526                 }
527                 break;
528
529             case R.id.export_radiobutton:
530                 // Hide the OpenKeychain import instructions.
531                 openKeychainImportInstructionTextView.setVisibility(View.GONE);
532
533                 // Set the text on the import/export button to be `Export`.
534                 importExportButton.setText(R.string.export);
535
536                 // Show the import/export button.
537                 importExportButton.setVisibility(View.VISIBLE);
538
539                 // Check to see if OpenPGP encryption is selected.
540                 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) {  // OpenPGP encryption is selected.
541                     // Hide the file name views.
542                     fileNameLinearLayout.setVisibility(View.GONE);
543                     fileDoesNotExistTextView.setVisibility(View.GONE);
544                     fileExistsWarningTextView.setVisibility(View.GONE);
545
546                     // Enable the export button.
547                     importExportButton.setEnabled(true);
548                 } else {  // OpenPGP encryption is not selected.
549                     // Show the file name view.
550                     fileNameLinearLayout.setVisibility(View.VISIBLE);
551
552                     // Hide the notification that the file name does not exist.
553                     fileDoesNotExistTextView.setVisibility(View.GONE);
554
555                     // Display a warning if the file already exists.
556                     if (file.exists()) {
557                         fileExistsWarningTextView.setVisibility(View.VISIBLE);
558                     } else {
559                         fileExistsWarningTextView.setVisibility(View.GONE);
560                     }
561
562                     // Check the encryption type.
563                     if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) {  // No encryption is selected.
564                         // Enable the export button if the file name is populated.
565                         importExportButton.setEnabled(!fileNameString.isEmpty());
566                     } else {  // Password encryption is selected.
567                         // Enable the export button if the file name and the password are populated.
568                         importExportButton.setEnabled(!fileNameString.isEmpty() && !passwordEncryptionEditText.getText().toString().isEmpty());
569                     }
570                 }
571                 break;
572         }
573     }
574
575     public void browse(View view) {
576         // Get a handle for the views.
577         Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
578         RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
579
580         // Check to see if import or export is selected.
581         if (importRadioButton.isChecked()) {  // Import is selected.
582             // Create the file picker intent.
583             Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
584
585             // Set the intent MIME type to include all files so that everything is visible.
586             importBrowseIntent.setType("*/*");
587
588             // Set the initial directory if the minimum API >= 26.
589             if (Build.VERSION.SDK_INT >= 26) {
590                 importBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
591             }
592
593             // Request a file that can be opened.
594             importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
595
596             // Launch the file picker.
597             startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
598         } else {  // Export is selected
599             // Create the file picker intent.
600             Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
601
602             // Set the intent MIME type to include all files so that everything is visible.
603             exportBrowseIntent.setType("*/*");
604
605             // Set the initial export file name according to the encryption type.
606             if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) {  // No encryption is selected.
607                 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings_pbs));
608             } else {  // Password encryption is selected.
609                 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings_pbs) + ".aes");
610             }
611
612             // Set the initial directory if the minimum API >= 26.
613             if (Build.VERSION.SDK_INT >= 26) {
614                 exportBrowseIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment.getExternalStorageDirectory());
615             }
616
617             // Request a file that can be opened.
618             exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
619
620             // Launch the file picker.
621             startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
622         }
623     }
624
625     public void importExport(View view) {
626         // Get a handle for the views.
627         Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
628         RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
629         RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
630
631         // Check to see if the storage permission is needed.
632         if ((encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) && exportRadioButton.isChecked()) {  // Permission not needed to export via OpenKeychain.
633             // Export the settings.
634             exportSettings();
635         } else if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {  // The storage permission has been granted.
636             // Check to see if import or export is selected.
637             if (importRadioButton.isChecked()) {  // Import is selected.
638                 // Import the settings.
639                 importSettings();
640             } else {  // Export is selected.
641                 // Export the settings.
642                 exportSettings();
643             }
644         } else {  // The storage permission has not been granted.
645             // Get a handle for the file name EditText.
646             EditText fileNameEditText = findViewById(R.id.file_name_edittext);
647
648             // Get the file name string.
649             String fileNameString = fileNameEditText.getText().toString();
650
651             // Get the external private directory `File`.
652             File externalPrivateDirectoryFile = getExternalFilesDir(null);
653
654             // Remove the incorrect lint error below that the file might be null.
655             assert externalPrivateDirectoryFile != null;
656
657             // Get the external private directory string.
658             String externalPrivateDirectory = externalPrivateDirectoryFile.toString();
659
660             // Check to see if the file path is in the external private directory.
661             if (fileNameString.startsWith(externalPrivateDirectory)) {  // The file path is in the external private directory.
662                 // Check to see if import or export is selected.
663                 if (importRadioButton.isChecked()) {  // Import is selected.
664                     // Import the settings.
665                     importSettings();
666                 } else {  // Export is selected.
667                     // Export the settings.
668                     exportSettings();
669                 }
670             } else {  // The file path is in a public directory.
671                 // Check if the user has previously denied the storage permission.
672                 if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {  // Show a dialog explaining the request first.
673                     // Instantiate the storage permission alert dialog.
674                     DialogFragment storagePermissionDialogFragment = StoragePermissionDialog.displayDialog(0);
675
676                     // Show the storage permission alert dialog.  The permission will be requested when the dialog is closed.
677                     storagePermissionDialogFragment.show(getSupportFragmentManager(), getString(R.string.storage_permission));
678                 } else {  // Show the permission request directly.
679                     // Request the storage permission.  The export will be run when it finishes.
680                     ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
681                 }
682             }
683         }
684     }
685
686     @Override
687     public void onCloseStoragePermissionDialog(int type) {
688         // Request the write external storage permission.  The import/export will be run when it finishes.
689         ActivityCompat.requestPermissions(this, new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0);
690     }
691
692     @Override
693     public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
694         // Get a handle for the import radiobutton.
695         RadioButton importRadioButton = findViewById(R.id.import_radiobutton);
696
697         // Check to see if the storage permission was granted.  If the dialog was canceled the grant results will be empty.
698         if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {  // The storage permission was granted.
699             // Run the import or export methods according to which radio button is selected.
700             if (importRadioButton.isChecked()) {  // Import is selected.
701                 // Import the settings.
702                 importSettings();
703             } else {  // Export is selected.
704                 // Export the settings.
705                 exportSettings();
706             }
707         } else {  // The storage permission was not granted.
708             // Display an error snackbar.
709             Snackbar.make(importRadioButton, getString(R.string.cannot_use_location), Snackbar.LENGTH_LONG).show();
710         }
711     }
712
713     @Override
714     public void onActivityResult(int requestCode, int resultCode, Intent intent) {
715         // Run the default commands.
716         super.onActivityResult(requestCode, resultCode, intent);
717
718         switch (requestCode) {
719             case (BROWSE_RESULT_CODE):
720                 // Don't do anything if the user pressed back from the file picker.
721                 if (resultCode == Activity.RESULT_OK) {
722                     // Get a handle for the views.
723                     EditText fileNameEditText = findViewById(R.id.file_name_edittext);
724                     TextView fileExistsWarningTextView = findViewById(R.id.file_exists_warning_textview);
725
726                     // Instantiate the file name helper.
727                     FileNameHelper fileNameHelper = new FileNameHelper();
728
729                     // Get the file path URI from the intent.
730                     Uri filePathUri = intent.getData();
731
732                     // Use the file path from the intent if it exists.
733                     if (filePathUri != null) {
734                         // Convert the file name URI to a file name path.
735                         String fileNamePath = fileNameHelper.convertUriToFileNamePath(filePathUri);
736
737                         // Set the file name path as the text of the file name edit text.
738                         fileNameEditText.setText(fileNamePath);
739
740                         // Hide the file exists warning text view, because the file picker will have just created a file if export was selected.
741                         fileExistsWarningTextView.setVisibility(View.GONE);
742                     }
743                 }
744                 break;
745
746             case OPENPGP_EXPORT_RESULT_CODE:
747                 // Get the temporary unencrypted export file.
748                 File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
749
750                 // Delete the temporary unencrypted export file if it exists.
751                 if (temporaryUnencryptedExportFile.exists()) {
752                     //noinspection ResultOfMethodCallIgnored
753                     temporaryUnencryptedExportFile.delete();
754                 }
755                 break;
756         }
757     }
758
759     private void exportSettings() {
760         // Get a handle for the views.
761         Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
762         EditText fileNameEditText = findViewById(R.id.file_name_edittext);
763
764         // Instantiate the import export database helper.
765         ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
766
767         // Get the export file string.
768         String exportFileString = fileNameEditText.getText().toString();
769
770         // Get the export and temporary unencrypted export files.
771         File exportFile = new File(exportFileString);
772         File temporaryUnencryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
773
774         // Create an export status string.
775         String exportStatus;
776
777         // Export according to the encryption type.
778         switch (encryptionSpinner.getSelectedItemPosition()) {
779             case NO_ENCRYPTION:
780                 // Export the unencrypted file.
781                 exportStatus = importExportDatabaseHelper.exportUnencrypted(exportFile, this);
782
783                 // Show a disposition snackbar.
784                 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
785                     Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
786                 } else {
787                     Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
788                 }
789                 break;
790
791             case PASSWORD_ENCRYPTION:
792                 // Create an unencrypted export in a private directory.
793                 exportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
794
795                 try {
796                     // Create an unencrypted export file input stream.
797                     FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
798
799                     // Delete the encrypted export file if it exists.
800                     if (exportFile.exists()) {
801                         //noinspection ResultOfMethodCallIgnored
802                         exportFile.delete();
803                     }
804
805                     // Create an encrypted export file output stream.
806                     FileOutputStream encryptedExportFileOutputStream = new FileOutputStream(exportFile);
807
808                     // Get a handle for the encryption password EditText.
809                     EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
810
811                     // Get the encryption password.
812                     String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
813
814                     // Initialize a secure random number generator.
815                     SecureRandom secureRandom = new SecureRandom();
816
817                     // Get a 256 bit (32 byte) random salt.
818                     byte[] saltByteArray = new byte[32];
819                     secureRandom.nextBytes(saltByteArray);
820
821                     // Convert the encryption password to a byte array.
822                     byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
823
824                     // Append the salt to the encryption password byte array.  This protects against rainbow table attacks.
825                     byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
826                     System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
827                     System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
828
829                     // Get a SHA-512 message digest.
830                     MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
831
832                     // Hash the salted encryption password.  Otherwise, any characters after the 32nd character in the password are ignored.
833                     byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
834
835                     // Truncate the encryption password byte array to 256 bits (32 bytes).
836                     byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
837
838                     // Create an AES secret key from the encryption password byte array.
839                     SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
840
841                     // Generate a random 12 byte initialization vector.  According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
842                     byte[] initializationVector = new byte[12];
843                     secureRandom.nextBytes(initializationVector);
844
845                     // Get a Advanced Encryption Standard, Galois/Counter Mode, No Padding cipher instance. Galois/Counter mode protects against modification of the ciphertext.  It doesn't use padding.
846                     Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
847
848                     // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
849                     GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
850
851                     // Initialize the cipher.
852                     cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
853
854                     // Add the salt and the initialization vector to the export file.
855                     encryptedExportFileOutputStream.write(saltByteArray);
856                     encryptedExportFileOutputStream.write(initializationVector);
857
858                     // Create a cipher output stream.
859                     CipherOutputStream cipherOutputStream = new CipherOutputStream(encryptedExportFileOutputStream, cipher);
860
861                     // Initialize variables to store data as it is moved from the unencrypted export file input stream to the cipher output stream.  Move 128 bits (16 bytes) at a time.
862                     int numberOfBytesRead;
863                     byte[] encryptedBytes = new byte[16];
864
865                     // Read up to 128 bits (16 bytes) of data from the unencrypted export file stream.  `-1` will be returned when the end of the file is reached.
866                     while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
867                         // Write the data to the cipher output stream.
868                         cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
869                     }
870
871                     // Close the streams.
872                     cipherOutputStream.flush();
873                     cipherOutputStream.close();
874                     encryptedExportFileOutputStream.close();
875                     unencryptedExportFileInputStream.close();
876
877                     // Wipe the encryption data from memory.
878                     //noinspection UnusedAssignment
879                     encryptionPasswordString = "";
880                     Arrays.fill(saltByteArray, (byte) 0);
881                     Arrays.fill(encryptionPasswordByteArray, (byte) 0);
882                     Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
883                     Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
884                     Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
885                     Arrays.fill(initializationVector, (byte) 0);
886                     Arrays.fill(encryptedBytes, (byte) 0);
887
888                     // Delete the temporary unencrypted export file.
889                     //noinspection ResultOfMethodCallIgnored
890                     temporaryUnencryptedExportFile.delete();
891                 } catch (Exception exception) {
892                     exportStatus = exception.toString();
893                 }
894
895                 // Show a disposition snackbar.
896                 if (exportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
897                     Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
898                 } else {
899                     Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + exportStatus, Snackbar.LENGTH_INDEFINITE).show();
900                 }
901                 break;
902
903             case OPENPGP_ENCRYPTION:
904                 // Create an unencrypted export in the private location.
905                 importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportFile, this);
906
907                 // Create an encryption intent for OpenKeychain.
908                 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
909
910                 // Include the temporary unencrypted export file URI.
911                 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryUnencryptedExportFile));
912
913                 // Allow OpenKeychain to read the file URI.
914                 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
915
916                 // Send the intent to the OpenKeychain package.
917                 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
918
919                 // Make it so.
920                 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
921                 break;
922         }
923
924         // Add the file to the list of recent files.  This doesn't currently work, but maybe it will someday.
925         MediaScannerConnection.scanFile(this, new String[] {exportFileString}, new String[] {"application/x-sqlite3"}, null);
926     }
927
928     private void importSettings() {
929         // Get a handle for the views.
930         Spinner encryptionSpinner = findViewById(R.id.encryption_spinner);
931         EditText fileNameEditText = findViewById(R.id.file_name_edittext);
932
933         // Instantiate the import export database helper.
934         ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
935
936         // Get the import file.
937         File importFile = new File(fileNameEditText.getText().toString());
938
939         // Initialize the import status string
940         String importStatus = "";
941
942         // Import according to the encryption type.
943         switch (encryptionSpinner.getSelectedItemPosition()) {
944             case NO_ENCRYPTION:
945                 // Import the unencrypted file.
946                 importStatus = importExportDatabaseHelper.importUnencrypted(importFile, this);
947                 break;
948
949             case PASSWORD_ENCRYPTION:
950                 // Use a private temporary import location.
951                 File temporaryUnencryptedImportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings_pbs));
952
953                 try {
954                     // Create an encrypted import file input stream.
955                     FileInputStream encryptedImportFileInputStream = new FileInputStream(importFile);
956
957                     // Delete the temporary import file if it exists.
958                     if (temporaryUnencryptedImportFile.exists()) {
959                         //noinspection ResultOfMethodCallIgnored
960                         temporaryUnencryptedImportFile.delete();
961                     }
962
963                     // Create an unencrypted import file output stream.
964                     FileOutputStream unencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
965
966                     // Get a handle for the encryption password EditText.
967                     EditText encryptionPasswordEditText = findViewById(R.id.password_encryption_edittext);
968
969                     // Get the encryption password.
970                     String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
971
972                     // Get the salt from the beginning of the import file.
973                     byte[] saltByteArray = new byte[32];
974                     //noinspection ResultOfMethodCallIgnored
975                     encryptedImportFileInputStream.read(saltByteArray);
976
977                     // Get the initialization vector from the import file.
978                     byte[] initializationVector = new byte[12];
979                     //noinspection ResultOfMethodCallIgnored
980                     encryptedImportFileInputStream.read(initializationVector);
981
982                     // Convert the encryption password to a byte array.
983                     byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
984
985                     // Append the salt to the encryption password byte array.  This protects against rainbow table attacks.
986                     byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
987                     System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
988                     System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
989
990                     // Get a SHA-512 message digest.
991                     MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
992
993                     // Hash the salted encryption password.  Otherwise, any characters after the 32nd character in the password are ignored.
994                     byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
995
996                     // Truncate the encryption password byte array to 256 bits (32 bytes).
997                     byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
998
999                     // Create an AES secret key from the encryption password byte array.
1000                     SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
1001
1002                     // Get a Advanced Encryption Standard, Galois/Counter Mode, No Padding cipher instance. Galois/Counter mode protects against modification of the ciphertext.  It doesn't use padding.
1003                     Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
1004
1005                     // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
1006                     GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
1007
1008                     // Initialize the cipher.
1009                     cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
1010
1011                     // Create a cipher input stream.
1012                     CipherInputStream cipherInputStream = new CipherInputStream(encryptedImportFileInputStream, cipher);
1013
1014                     // Initialize variables to store data as it is moved from the cipher input stream to the unencrypted import file output stream.  Move 128 bits (16 bytes) at a time.
1015                     int numberOfBytesRead;
1016                     byte[] decryptedBytes = new byte[16];
1017
1018                     // Read up to 128 bits (16 bytes) of data from the cipher input stream.  `-1` will be returned when the end fo the file is reached.
1019                     while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
1020                         // Write the data to the unencrypted import file output stream.
1021                         unencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
1022                     }
1023
1024                     // Close the streams.
1025                     unencryptedImportFileOutputStream.flush();
1026                     unencryptedImportFileOutputStream.close();
1027                     cipherInputStream.close();
1028                     encryptedImportFileInputStream.close();
1029
1030                     // Wipe the encryption data from memory.
1031                     //noinspection UnusedAssignment
1032                     encryptionPasswordString = "";
1033                     Arrays.fill(saltByteArray, (byte) 0);
1034                     Arrays.fill(initializationVector, (byte) 0);
1035                     Arrays.fill(encryptionPasswordByteArray, (byte) 0);
1036                     Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
1037                     Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
1038                     Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
1039                     Arrays.fill(decryptedBytes, (byte) 0);
1040
1041                     // Import the unencrypted database from the private location.
1042                     importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFile, this);
1043
1044                     // Delete the temporary unencrypted import file.
1045                     //noinspection ResultOfMethodCallIgnored
1046                     temporaryUnencryptedImportFile.delete();
1047                 } catch (Exception exception) {
1048                     importStatus = exception.toString();
1049                 }
1050                 break;
1051
1052             case OPENPGP_ENCRYPTION:
1053                 try {
1054                     // Create an decryption intent for OpenKeychain.
1055                     Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
1056
1057                     // Include the URI to be decrypted.
1058                     openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), importFile));
1059
1060                     // Allow OpenKeychain to read the file URI.
1061                     openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
1062
1063                     // Send the intent to the OpenKeychain package.
1064                     openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
1065
1066                     // Make it so.
1067                     startActivity(openKeychainDecryptIntent);
1068                 } catch (IllegalArgumentException exception) {  // The file import location is not valid.
1069                     // Display a snack bar with the import error.
1070                     Snackbar.make(fileNameEditText, getString(R.string.import_failed) + "  " + exception.toString(), Snackbar.LENGTH_INDEFINITE).show();
1071                 }
1072                 break;
1073         }
1074
1075         // Respond to the import disposition.
1076         if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {  // The import was successful.
1077             // Create an intent to restart Privacy Browser.
1078             Intent restartIntent = getParentActivityIntent();
1079
1080             // Assert that the intent is not null to remove the lint error below.
1081             assert restartIntent != null;
1082
1083             // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack.  It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
1084             restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
1085
1086             // Create a restart handler.
1087             Handler restartHandler = new Handler();
1088
1089             // Create a restart runnable.
1090             Runnable restartRunnable =  () -> {
1091                 // Restart Privacy Browser.
1092                 startActivity(restartIntent);
1093
1094                 // Kill this instance of Privacy Browser.  Otherwise, the app exhibits sporadic behavior after the restart.
1095                 System.exit(0);
1096             };
1097
1098             // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
1099             restartHandler.postDelayed(restartRunnable, 150);
1100
1101         } else if (!(encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION)){  // The import was not successful.
1102             // Display a snack bar with the import error.
1103             Snackbar.make(fileNameEditText, getString(R.string.import_failed) + "  " + importStatus, Snackbar.LENGTH_INDEFINITE).show();
1104         }
1105     }
1106 }