2 * Copyright © 2018-2022 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser Android <https://www.stoutner.com/privacy-browser-android>.
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.
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.
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/>.
20 package com.stoutner.privacybrowser.activities;
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;
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;
50 import com.google.android.material.snackbar.Snackbar;
51 import com.google.android.material.textfield.TextInputLayout;
53 import com.stoutner.privacybrowser.BuildConfig;
54 import com.stoutner.privacybrowser.R;
55 import com.stoutner.privacybrowser.helpers.ImportExportDatabaseHelper;
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;
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;
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;
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;
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";
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;
107 // Define the class variables.
108 private boolean openKeychainInstalled;
109 private File temporaryPgpEncryptedImportFile;
110 private File temporaryPreEncryptedExportFile;
113 public void onCreate(Bundle savedInstanceState) {
114 // Get a handle for the shared preferences.
115 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
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);
121 // Disable screenshots if not allowed.
122 if (!allowScreenshots) {
123 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
127 setTheme(R.style.PrivacyBrowser);
129 // Run the default commands.
130 super.onCreate(savedInstanceState);
132 // Set the content view.
134 setContentView(R.layout.import_export_bottom_appbar);
136 setContentView(R.layout.import_export_top_appbar);
139 // Get a handle for the toolbar.
140 Toolbar toolbar = findViewById(R.id.import_export_toolbar);
142 // Set the support action bar.
143 setSupportActionBar(toolbar);
145 // Get a handle for the action bar.
146 ActionBar actionBar = getSupportActionBar();
148 // Remove the incorrect lint warning that the action bar might be null.
149 assert actionBar != null;
151 // Display the home arrow on the support action bar.
152 actionBar.setDisplayHomeAsUpEnabled(true);
154 // Find out if OpenKeychain is installed.
156 openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
157 } catch (PackageManager.NameNotFoundException exception) {
158 openKeychainInstalled = false;
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);
174 // Create an array adapter for the spinner.
175 ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
177 // Set the drop down view resource on the spinner.
178 encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
180 // Set the array adapter for the spinner.
181 encryptionSpinner.setAdapter(encryptionArrayAdapter);
183 // Update the UI when the spinner changes.
184 encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
186 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
189 // Hide the unneeded layout items.
190 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
191 openKeychainRequiredTextView.setVisibility(View.GONE);
192 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
194 // Show the file location card.
195 fileLocationCardView.setVisibility(View.VISIBLE);
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);
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);
207 // Enable the import/export button if the file name is populated.
208 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
211 case PASSWORD_ENCRYPTION:
212 // Hide the OpenPGP layout items.
213 openKeychainRequiredTextView.setVisibility(View.GONE);
214 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
216 // Show the password encryption layout items.
217 encryptionPasswordTextInputLayout.setVisibility(View.VISIBLE);
219 // Show the file location card.
220 fileLocationCardView.setVisibility(View.VISIBLE);
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);
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);
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());
236 case OPENPGP_ENCRYPTION:
237 // Hide the password encryption layout items.
238 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
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);
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);
250 // Set the text of the import button to be `Decrypt`.
251 importExportButton.setText(R.string.decrypt);
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);
260 // Enable the export button.
261 importExportButton.setEnabled(true);
263 } else { // OpenKeychain is not installed.
264 // Show the OpenPGP required layout item.
265 openKeychainRequiredTextView.setVisibility(View.VISIBLE);
267 // Hide the file location card.
268 fileLocationCardView.setVisibility(View.GONE);
275 public void onNothingSelected(AdapterView<?> parent) {
280 // Update the status of the import/export button when the password changes.
281 encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
283 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
288 public void onTextChanged(CharSequence s, int start, int before, int count) {
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());
299 // Update the UI when the file name EditText changes.
300 fileNameEditText.addTextChangedListener(new TextWatcher() {
302 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
307 public void onTextChanged(CharSequence s, int start, int before, int count) {
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());
318 // Enable the export button if the file name is populated.
319 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
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));
342 fileNameEditText.post(() -> fileNameEditText.setText(savedInstanceState.getString(FILE_NAME_TEXT)));
343 importExportButton.setText(savedInstanceState.getString(IMPORT_EXPORT_BUTTON_TEXT));
348 public void onSaveInstanceState (@NonNull Bundle savedInstanceState) {
349 // Run the default commands.
350 super.onSaveInstanceState(savedInstanceState);
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());
361 savedInstanceState.putString(FILE_NAME_TEXT, fileNameEditText.getText().toString());
362 savedInstanceState.putString(IMPORT_EXPORT_BUTTON_TEXT, importExportButton.getText().toString());
365 public void onClickRadioButton(View view) {
366 // Get the current file name.
367 String fileNameString = fileNameEditText.getText().toString();
369 // Convert the file name string to a file.
370 File file = new File(fileNameString);
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);
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);
385 // Set the text on the import/export button to be `Import`.
386 importExportButton.setText(R.string.import_button);
389 // Display the file name views.
390 fileNameLinearLayout.setVisibility(View.VISIBLE);
391 importExportButton.setVisibility(View.VISIBLE);
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);
403 } else { // The file does not exist.
404 // Disable the import/decrypt button.
405 importExportButton.setEnabled(false);
407 } else { // The export radio button is selected.
408 // Hide the OpenKeychain import instructions.
409 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
411 // Set the text on the import/export button to be `Export`.
412 importExportButton.setText(R.string.export);
414 // Show the import/export button.
415 importExportButton.setVisibility(View.VISIBLE);
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);
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);
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());
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);
446 // Set the intent MIME type to include all files so that everything is visible.
447 importBrowseIntent.setType("*/*");
449 // Request a file that can be opened.
450 importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
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);
458 // Set the intent MIME type to include all files so that everything is visible.
459 exportBrowseIntent.setType("*/*");
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");
468 // Request a file that can be opened.
469 exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
471 // Launch the file picker.
472 startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
477 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
478 // Run the default commands.
479 super.onActivityResult(requestCode, resultCode, returnedIntent);
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();
488 // Get the file name string from the URI.
489 String fileNameString = fileNameUri.toString();
491 // Set the file name name text.
492 fileNameEditText.setText(fileNameString);
494 // Move the cursor to the end of the file name edit text.
495 fileNameEditText.setSelection(fileNameString.length());
499 case OPENPGP_IMPORT_RESULT_CODE:
500 // Delete the temporary PGP encrypted import file.
501 if (temporaryPgpEncryptedImportFile.exists()) {
502 //noinspection ResultOfMethodCallIgnored
503 temporaryPgpEncryptedImportFile.delete();
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();
517 public void importExport(View view) {
518 // Instantiate the import export database helper.
519 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
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 = "";
526 // Get the file name string.
527 String fileNameString = fileNameEditText.getText().toString();
529 // Import according to the encryption type.
530 switch (encryptionSpinner.getSelectedItemPosition()) {
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));
537 // Import the unencrypted file.
538 importStatus = importExportDatabaseHelper.importUnencrypted(inputStream, this);
539 } catch (FileNotFoundException exception) {
540 // Update the import status.
541 importStatus = exception.toString();
544 // Restart Privacy Browser if successful.
545 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
546 restartPrivacyBrowser();
550 case PASSWORD_ENCRYPTION:
552 // Get the encryption password.
553 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
555 // Get an input stream for the file name.
556 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
558 // Get the salt from the beginning of the import file.
559 byte[] saltByteArray = new byte[32];
560 //noinspection ResultOfMethodCallIgnored
561 inputStream.read(saltByteArray);
563 // Get the initialization vector from the import file.
564 byte[] initializationVector = new byte[12];
565 //noinspection ResultOfMethodCallIgnored
566 inputStream.read(initializationVector);
568 // Convert the encryption password to a byte array.
569 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
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);
576 // Get a SHA-512 message digest.
577 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
579 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
580 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
582 // Truncate the encryption password byte array to 256 bits (32 bytes).
583 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
585 // Create an AES secret key from the encryption password byte array.
586 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
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");
591 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
592 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
594 // Initialize the cipher.
595 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
597 // Create a cipher input stream.
598 CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
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];
605 // Create a private temporary unencrypted import file.
606 File temporaryUnencryptedImportFile = File.createTempFile("temporary_unencrypted_import_file", null, getApplicationContext().getCacheDir());
608 // Create an temporary unencrypted import file output stream.
609 FileOutputStream temporaryUnencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
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);
619 // Flush the temporary unencrypted import file output stream.
620 temporaryUnencryptedImportFileOutputStream.flush();
622 // Close the streams.
623 temporaryUnencryptedImportFileOutputStream.close();
624 cipherInputStream.close();
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);
638 // Create a temporary unencrypted import file input stream.
639 FileInputStream temporaryUnencryptedImportFileInputStream = new FileInputStream(temporaryUnencryptedImportFile);
641 // Import the temporary unencrypted import file.
642 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFileInputStream, this);
644 // Close the temporary unencrypted import file input stream.
645 temporaryUnencryptedImportFileInputStream.close();
647 // Delete the temporary unencrypted import file.
648 //noinspection ResultOfMethodCallIgnored
649 temporaryUnencryptedImportFile.delete();
651 // Restart Privacy Browser if successful.
652 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
653 restartPrivacyBrowser();
655 } catch (Exception exception) {
656 // Update the import status.
657 importStatus = exception.toString();
661 case OPENPGP_ENCRYPTION:
663 // Set the temporary PGP encrypted import file.
664 temporaryPgpEncryptedImportFile = File.createTempFile("temporary_pgp_encrypted_import_file", null, getApplicationContext().getCacheDir());
666 // Create a temporary PGP encrypted import file output stream.
667 FileOutputStream temporaryPgpEncryptedImportFileOutputStream = new FileOutputStream(temporaryPgpEncryptedImportFile);
669 // Get an input stream for the file name.
670 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
672 // Create a transfer byte array.
673 byte[] transferByteArray = new byte[1024];
675 // Create an integer to track the number of bytes read.
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);
683 // Flush the temporary PGP encrypted import file output stream.
684 temporaryPgpEncryptedImportFileOutputStream.flush();
686 // Close the streams.
688 temporaryPgpEncryptedImportFileOutputStream.close();
690 // Create an decryption intent for OpenKeychain.
691 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
693 // Include the URI to be decrypted.
694 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPgpEncryptedImportFile));
696 // Allow OpenKeychain to read the file URI.
697 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
699 // Send the intent to the OpenKeychain package.
700 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
703 startActivityForResult(openKeychainDecryptIntent, OPENPGP_IMPORT_RESULT_CODE);
705 // Update the import status.
706 importStatus = ImportExportDatabaseHelper.IMPORT_SUCCESSFUL;
707 } catch (Exception exception) {
708 // Update the import status.
709 importStatus = exception.toString();
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();
719 } else { // Export is selected.
720 // Export according to the encryption type.
721 switch (encryptionSpinner.getSelectedItemPosition()) {
723 // Get the file name string.
724 String noEncryptionFileNameString = fileNameEditText.getText().toString();
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));
731 // Export the unencrypted file.
732 String noEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(exportFileOutputStream, this);
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();
738 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + noEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
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();
746 case PASSWORD_ENCRYPTION:
748 // Create a temporary unencrypted export file.
749 File temporaryUnencryptedExportFile = File.createTempFile("temporary_unencrypted_export_file", null, getApplicationContext().getCacheDir());
751 // Create a temporary unencrypted export output stream.
752 FileOutputStream temporaryUnencryptedExportOutputStream = new FileOutputStream(temporaryUnencryptedExportFile);
754 // Populate the temporary unencrypted export.
755 String passwordEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportOutputStream, this);
757 // Close the temporary unencrypted export output stream.
758 temporaryUnencryptedExportOutputStream.close();
760 // Create an unencrypted export file input stream.
761 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
763 // Get the encryption password.
764 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
766 // Initialize a secure random number generator.
767 SecureRandom secureRandom = new SecureRandom();
769 // Get a 256 bit (32 byte) random salt.
770 byte[] saltByteArray = new byte[32];
771 secureRandom.nextBytes(saltByteArray);
773 // Convert the encryption password to a byte array.
774 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
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);
781 // Get a SHA-512 message digest.
782 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
784 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
785 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
787 // Truncate the encryption password byte array to 256 bits (32 bytes).
788 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
790 // Create an AES secret key from the encryption password byte array.
791 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
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);
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");
800 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
801 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
803 // Initialize the cipher.
804 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
806 // Get the file name string.
807 String passwordEncryptionFileNameString = fileNameEditText.getText().toString();
809 // Get the export file output stream.
810 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(passwordEncryptionFileNameString));
812 // Add the salt and the initialization vector to the export file output stream.
813 exportFileOutputStream.write(saltByteArray);
814 exportFileOutputStream.write(initializationVector);
816 // Create a cipher output stream.
817 CipherOutputStream cipherOutputStream = new CipherOutputStream(exportFileOutputStream, cipher);
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];
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);
829 // Close the streams.
830 cipherOutputStream.flush();
831 cipherOutputStream.close();
832 exportFileOutputStream.close();
833 unencryptedExportFileInputStream.close();
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);
846 // Delete the temporary unencrypted export file.
847 //noinspection ResultOfMethodCallIgnored
848 temporaryUnencryptedExportFile.delete();
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();
854 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + passwordEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
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();
862 case OPENPGP_ENCRYPTION:
864 // Set the temporary pre-encrypted export file.
865 temporaryPreEncryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
867 // Delete the temporary pre-encrypted export file if it already exists.
868 if (temporaryPreEncryptedExportFile.exists()) {
869 //noinspection ResultOfMethodCallIgnored
870 temporaryPreEncryptedExportFile.delete();
873 // Create a temporary pre-encrypted export output stream.
874 FileOutputStream temporaryPreEncryptedExportOutputStream = new FileOutputStream(temporaryPreEncryptedExportFile);
876 // Populate the temporary pre-encrypted export file.
877 String openpgpEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryPreEncryptedExportOutputStream, this);
879 // Flush the temporary pre-encryption export output stream.
880 temporaryPreEncryptedExportOutputStream.flush();
882 // Close the temporary pre-encryption export output stream.
883 temporaryPreEncryptedExportOutputStream.close();
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();
890 // Create an encryption intent for OpenKeychain.
891 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
893 // Include the temporary unencrypted export file URI.
894 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPreEncryptedExportFile));
896 // Allow OpenKeychain to read the file URI.
897 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
899 // Send the intent to the OpenKeychain package.
900 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
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();
913 private void restartPrivacyBrowser() {
914 // Create an intent to restart Privacy Browser.
915 Intent restartIntent = getParentActivityIntent();
917 // Assert that the intent is not null to remove the lint error below.
918 assert restartIntent != null;
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);
923 // Create a restart handler.
924 Handler restartHandler = new Handler();
926 // Create a restart runnable.
927 Runnable restartRunnable = () -> {
928 // Restart Privacy Browser.
929 startActivity(restartIntent);
931 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
935 // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
936 restartHandler.postDelayed(restartRunnable, 150);