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