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