]> gitweb.stoutner.com Git - PrivacyBrowserAndroid.git/blob - app/src/main/java/com/stoutner/privacybrowser/activities/ImportExportActivity.java
Fix a crash when opening the Import/Export activity. https://redmine.stoutner.com...
[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                         InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
535
536                         // Import the unencrypted file.
537                         importStatus = importExportDatabaseHelper.importUnencrypted(inputStream, this);
538                     } catch (FileNotFoundException exception) {
539                         // Update the import status.
540                         importStatus = exception.toString();
541                     }
542
543                     // Restart Privacy Browser if successful.
544                     if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
545                         restartPrivacyBrowser();
546                     }
547                     break;
548
549                 case PASSWORD_ENCRYPTION:
550                     try {
551                         // Get the encryption password.
552                         String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
553
554                         // Get an input stream for the file name.
555                         InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
556
557                         // Get the salt from the beginning of the import file.
558                         byte[] saltByteArray = new byte[32];
559                         //noinspection ResultOfMethodCallIgnored
560                         inputStream.read(saltByteArray);
561
562                         // Get the initialization vector from the import file.
563                         byte[] initializationVector = new byte[12];
564                         //noinspection ResultOfMethodCallIgnored
565                         inputStream.read(initializationVector);
566
567                         // Convert the encryption password to a byte array.
568                         byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
569
570                         // Append the salt to the encryption password byte array.  This protects against rainbow table attacks.
571                         byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
572                         System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
573                         System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
574
575                         // Get a SHA-512 message digest.
576                         MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
577
578                         // Hash the salted encryption password.  Otherwise, any characters after the 32nd character in the password are ignored.
579                         byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
580
581                         // Truncate the encryption password byte array to 256 bits (32 bytes).
582                         byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
583
584                         // Create an AES secret key from the encryption password byte array.
585                         SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
586
587                         // 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.
588                         Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
589
590                         // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
591                         GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
592
593                         // Initialize the cipher.
594                         cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
595
596                         // Create a cipher input stream.
597                         CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
598
599                         // 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.
600                         int numberOfBytesRead;
601                         byte[] decryptedBytes = new byte[16];
602
603
604                         // Create a private temporary unencrypted import file.
605                         File temporaryUnencryptedImportFile = File.createTempFile("temporary_unencrypted_import_file", null, getApplicationContext().getCacheDir());
606
607                         // Create an temporary unencrypted import file output stream.
608                         FileOutputStream temporaryUnencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
609
610
611                         // 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.
612                         while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
613                             // Write the data to the temporary unencrypted import file output stream.
614                             temporaryUnencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
615                         }
616
617
618                         // Flush the temporary unencrypted import file output stream.
619                         temporaryUnencryptedImportFileOutputStream.flush();
620
621                         // Close the streams.
622                         temporaryUnencryptedImportFileOutputStream.close();
623                         cipherInputStream.close();
624                         inputStream.close();
625
626                         // Wipe the encryption data from memory.
627                         //noinspection UnusedAssignment
628                         encryptionPasswordString = "";
629                         Arrays.fill(saltByteArray, (byte) 0);
630                         Arrays.fill(initializationVector, (byte) 0);
631                         Arrays.fill(encryptionPasswordByteArray, (byte) 0);
632                         Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
633                         Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
634                         Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
635                         Arrays.fill(decryptedBytes, (byte) 0);
636
637                         // Create a temporary unencrypted import file input stream.
638                         FileInputStream temporaryUnencryptedImportFileInputStream = new FileInputStream(temporaryUnencryptedImportFile);
639
640                         // Import the temporary unencrypted import file.
641                         importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFileInputStream, this);
642
643                         // Close the temporary unencrypted import file input stream.
644                         temporaryUnencryptedImportFileInputStream.close();
645
646                         // Delete the temporary unencrypted import file.
647                         //noinspection ResultOfMethodCallIgnored
648                         temporaryUnencryptedImportFile.delete();
649
650                         // Restart Privacy Browser if successful.
651                         if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
652                             restartPrivacyBrowser();
653                         }
654                     } catch (Exception exception) {
655                         // Update the import status.
656                         importStatus = exception.toString();
657                     }
658                     break;
659
660                 case OPENPGP_ENCRYPTION:
661                     try {
662                         // Set the temporary PGP encrypted import file.
663                         temporaryPgpEncryptedImportFile = File.createTempFile("temporary_pgp_encrypted_import_file", null, getApplicationContext().getCacheDir());
664
665                         // Create a temporary PGP encrypted import file output stream.
666                         FileOutputStream temporaryPgpEncryptedImportFileOutputStream = new FileOutputStream(temporaryPgpEncryptedImportFile);
667
668                         // Get an input stream for the file name.
669                         InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
670
671                         // Create a transfer byte array.
672                         byte[] transferByteArray = new byte[1024];
673
674                         // Create an integer to track the number of bytes read.
675                         int bytesRead;
676
677                         // Copy the input stream to the temporary PGP encrypted import file.
678                         while ((bytesRead = inputStream.read(transferByteArray)) > 0) {
679                             temporaryPgpEncryptedImportFileOutputStream.write(transferByteArray, 0, bytesRead);
680                         }
681
682                         // Flush the temporary PGP encrypted import file output stream.
683                         temporaryPgpEncryptedImportFileOutputStream.flush();
684
685                         // Close the streams.
686                         inputStream.close();
687                         temporaryPgpEncryptedImportFileOutputStream.close();
688
689                         // Create an decryption intent for OpenKeychain.
690                         Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
691
692                         // Include the URI to be decrypted.
693                         openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPgpEncryptedImportFile));
694
695                         // Allow OpenKeychain to read the file URI.
696                         openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
697
698                         // Send the intent to the OpenKeychain package.
699                         openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
700
701                         // Make it so.
702                         startActivityForResult(openKeychainDecryptIntent, OPENPGP_IMPORT_RESULT_CODE);
703
704                         // Update the import status.
705                         importStatus = ImportExportDatabaseHelper.IMPORT_SUCCESSFUL;
706                     } catch (Exception exception) {
707                         // Update the import status.
708                         importStatus = exception.toString();
709                     }
710                     break;
711             }
712
713             // Respond to the import status.
714             if (!importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
715                 // Display a snack bar with the import error.
716                 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + "  " + importStatus, Snackbar.LENGTH_INDEFINITE).show();
717             }
718         } else {  // Export is selected.
719             // Export according to the encryption type.
720             switch (encryptionSpinner.getSelectedItemPosition()) {
721                 case NO_ENCRYPTION:
722                     // Get the file name string.
723                     String noEncryptionFileNameString = fileNameEditText.getText().toString();
724
725                     try {
726                         // Get the export file output stream.
727                         OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(noEncryptionFileNameString));
728
729                         // Export the unencrypted file.
730                         String noEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(exportFileOutputStream, this);
731
732                         // Display an export disposition snackbar.
733                         if (noEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
734                             Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
735                         } else {
736                             Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + noEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
737                         }
738                     } catch (FileNotFoundException fileNotFoundException) {
739                         // Display a snackbar with the exception.
740                         Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + fileNotFoundException, Snackbar.LENGTH_INDEFINITE).show();
741                     }
742                     break;
743
744                 case PASSWORD_ENCRYPTION:
745                     try {
746                         // Create a temporary unencrypted export file.
747                         File temporaryUnencryptedExportFile = File.createTempFile("temporary_unencrypted_export_file", null, getApplicationContext().getCacheDir());
748
749                         // Create a temporary unencrypted export output stream.
750                         FileOutputStream temporaryUnencryptedExportOutputStream = new FileOutputStream(temporaryUnencryptedExportFile);
751
752                         // Populate the temporary unencrypted export.
753                         String passwordEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportOutputStream, this);
754
755                         // Close the temporary unencrypted export output stream.
756                         temporaryUnencryptedExportOutputStream.close();
757
758                         // Create an unencrypted export file input stream.
759                         FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
760
761                         // Get the encryption password.
762                         String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
763
764                         // Initialize a secure random number generator.
765                         SecureRandom secureRandom = new SecureRandom();
766
767                         // Get a 256 bit (32 byte) random salt.
768                         byte[] saltByteArray = new byte[32];
769                         secureRandom.nextBytes(saltByteArray);
770
771                         // Convert the encryption password to a byte array.
772                         byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
773
774                         // Append the salt to the encryption password byte array.  This protects against rainbow table attacks.
775                         byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
776                         System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
777                         System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
778
779                         // Get a SHA-512 message digest.
780                         MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
781
782                         // Hash the salted encryption password.  Otherwise, any characters after the 32nd character in the password are ignored.
783                         byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
784
785                         // Truncate the encryption password byte array to 256 bits (32 bytes).
786                         byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
787
788                         // Create an AES secret key from the encryption password byte array.
789                         SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
790
791                         // Generate a random 12 byte initialization vector.  According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
792                         byte[] initializationVector = new byte[12];
793                         secureRandom.nextBytes(initializationVector);
794
795                         // 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.
796                         Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
797
798                         // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
799                         GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
800
801                         // Initialize the cipher.
802                         cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
803
804                         // Get the file name string.
805                         String passwordEncryptionFileNameString = fileNameEditText.getText().toString();
806
807                         // Get the export file output stream.
808                         OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(passwordEncryptionFileNameString));
809
810                         // Add the salt and the initialization vector to the export file output stream.
811                         exportFileOutputStream.write(saltByteArray);
812                         exportFileOutputStream.write(initializationVector);
813
814                         // Create a cipher output stream.
815                         CipherOutputStream cipherOutputStream = new CipherOutputStream(exportFileOutputStream, cipher);
816
817                         // 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.
818                         int numberOfBytesRead;
819                         byte[] encryptedBytes = new byte[16];
820
821                         // 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.
822                         while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
823                             // Write the data to the cipher output stream.
824                             cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
825                         }
826
827                         // Close the streams.
828                         cipherOutputStream.flush();
829                         cipherOutputStream.close();
830                         exportFileOutputStream.close();
831                         unencryptedExportFileInputStream.close();
832
833                         // Wipe the encryption data from memory.
834                         //noinspection UnusedAssignment
835                         encryptionPasswordString = "";
836                         Arrays.fill(saltByteArray, (byte) 0);
837                         Arrays.fill(encryptionPasswordByteArray, (byte) 0);
838                         Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
839                         Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
840                         Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
841                         Arrays.fill(initializationVector, (byte) 0);
842                         Arrays.fill(encryptedBytes, (byte) 0);
843
844                         // Delete the temporary unencrypted export file.
845                         //noinspection ResultOfMethodCallIgnored
846                         temporaryUnencryptedExportFile.delete();
847
848                         // Display an export disposition snackbar.
849                         if (passwordEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
850                             Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
851                         } else {
852                             Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + passwordEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
853                         }
854                     } catch (Exception exception) {
855                         // Display a snackbar with the exception.
856                         Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
857                     }
858                     break;
859
860                 case OPENPGP_ENCRYPTION:
861                     try {
862                         // Set the temporary pre-encrypted export file.
863                         temporaryPreEncryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
864
865                         // Delete the temporary pre-encrypted export file if it already exists.
866                         if (temporaryPreEncryptedExportFile.exists()) {
867                             //noinspection ResultOfMethodCallIgnored
868                             temporaryPreEncryptedExportFile.delete();
869                         }
870
871                         // Create a temporary pre-encrypted export output stream.
872                         FileOutputStream temporaryPreEncryptedExportOutputStream = new FileOutputStream(temporaryPreEncryptedExportFile);
873
874                         // Populate the temporary pre-encrypted export file.
875                         String openpgpEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryPreEncryptedExportOutputStream, this);
876
877                         // Flush the temporary pre-encryption export output stream.
878                         temporaryPreEncryptedExportOutputStream.flush();
879
880                         // Close the temporary pre-encryption export output stream.
881                         temporaryPreEncryptedExportOutputStream.close();
882
883                         // Display an export error snackbar if the temporary pre-encrypted export failed.
884                         if (!openpgpEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
885                             Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + openpgpEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
886                         }
887
888                         // Create an encryption intent for OpenKeychain.
889                         Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
890
891                         // Include the temporary unencrypted export file URI.
892                         openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPreEncryptedExportFile));
893
894                         // Allow OpenKeychain to read the file URI.
895                         openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
896
897                         // Send the intent to the OpenKeychain package.
898                         openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
899
900                         // Make it so.
901                         startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
902                     } catch (Exception exception) {
903                         // Display a snackbar with the exception.
904                         Snackbar.make(fileNameEditText, getString(R.string.export_failed) + "  " + exception, Snackbar.LENGTH_INDEFINITE).show();
905                     }
906                     break;
907             }
908         }
909     }
910
911     private void restartPrivacyBrowser() {
912         // Create an intent to restart Privacy Browser.
913         Intent restartIntent = getParentActivityIntent();
914
915         // Assert that the intent is not null to remove the lint error below.
916         assert restartIntent != null;
917
918         // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack.  It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
919         restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
920
921         // Create a restart handler.
922         Handler restartHandler = new Handler();
923
924         // Create a restart runnable.
925         Runnable restartRunnable =  () -> {
926             // Restart Privacy Browser.
927             startActivity(restartIntent);
928
929             // Kill this instance of Privacy Browser.  Otherwise, the app exhibits sporadic behavior after the restart.
930             System.exit(0);
931         };
932
933         // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
934         restartHandler.postDelayed(restartRunnable, 150);
935     }
936 }