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