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