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