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