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 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
536 // Import the unencrypted file.
537 importStatus = importExportDatabaseHelper.importUnencrypted(inputStream, this);
538 } catch (FileNotFoundException exception) {
539 // Update the import status.
540 importStatus = exception.toString();
543 // Restart Privacy Browser if successful.
544 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
545 restartPrivacyBrowser();
549 case PASSWORD_ENCRYPTION:
551 // Get the encryption password.
552 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
554 // Get an input stream for the file name.
555 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
557 // Get the salt from the beginning of the import file.
558 byte[] saltByteArray = new byte[32];
559 //noinspection ResultOfMethodCallIgnored
560 inputStream.read(saltByteArray);
562 // Get the initialization vector from the import file.
563 byte[] initializationVector = new byte[12];
564 //noinspection ResultOfMethodCallIgnored
565 inputStream.read(initializationVector);
567 // Convert the encryption password to a byte array.
568 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
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);
575 // Get a SHA-512 message digest.
576 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
578 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
579 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
581 // Truncate the encryption password byte array to 256 bits (32 bytes).
582 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
584 // Create an AES secret key from the encryption password byte array.
585 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
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");
590 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
591 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
593 // Initialize the cipher.
594 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
596 // Create a cipher input stream.
597 CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
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];
604 // Create a private temporary unencrypted import file.
605 File temporaryUnencryptedImportFile = File.createTempFile("temporary_unencrypted_import_file", null, getApplicationContext().getCacheDir());
607 // Create an temporary unencrypted import file output stream.
608 FileOutputStream temporaryUnencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
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);
618 // Flush the temporary unencrypted import file output stream.
619 temporaryUnencryptedImportFileOutputStream.flush();
621 // Close the streams.
622 temporaryUnencryptedImportFileOutputStream.close();
623 cipherInputStream.close();
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);
637 // Create a temporary unencrypted import file input stream.
638 FileInputStream temporaryUnencryptedImportFileInputStream = new FileInputStream(temporaryUnencryptedImportFile);
640 // Import the temporary unencrypted import file.
641 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFileInputStream, this);
643 // Close the temporary unencrypted import file input stream.
644 temporaryUnencryptedImportFileInputStream.close();
646 // Delete the temporary unencrypted import file.
647 //noinspection ResultOfMethodCallIgnored
648 temporaryUnencryptedImportFile.delete();
650 // Restart Privacy Browser if successful.
651 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
652 restartPrivacyBrowser();
654 } catch (Exception exception) {
655 // Update the import status.
656 importStatus = exception.toString();
660 case OPENPGP_ENCRYPTION:
662 // Set the temporary PGP encrypted import file.
663 temporaryPgpEncryptedImportFile = File.createTempFile("temporary_pgp_encrypted_import_file", null, getApplicationContext().getCacheDir());
665 // Create a temporary PGP encrypted import file output stream.
666 FileOutputStream temporaryPgpEncryptedImportFileOutputStream = new FileOutputStream(temporaryPgpEncryptedImportFile);
668 // Get an input stream for the file name.
669 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
671 // Create a transfer byte array.
672 byte[] transferByteArray = new byte[1024];
674 // Create an integer to track the number of bytes read.
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);
682 // Flush the temporary PGP encrypted import file output stream.
683 temporaryPgpEncryptedImportFileOutputStream.flush();
685 // Close the streams.
687 temporaryPgpEncryptedImportFileOutputStream.close();
689 // Create an decryption intent for OpenKeychain.
690 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
692 // Include the URI to be decrypted.
693 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPgpEncryptedImportFile));
695 // Allow OpenKeychain to read the file URI.
696 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
698 // Send the intent to the OpenKeychain package.
699 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
702 startActivityForResult(openKeychainDecryptIntent, OPENPGP_IMPORT_RESULT_CODE);
704 // Update the import status.
705 importStatus = ImportExportDatabaseHelper.IMPORT_SUCCESSFUL;
706 } catch (Exception exception) {
707 // Update the import status.
708 importStatus = exception.toString();
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();
718 } else { // Export is selected.
719 // Export according to the encryption type.
720 switch (encryptionSpinner.getSelectedItemPosition()) {
722 // Get the file name string.
723 String noEncryptionFileNameString = fileNameEditText.getText().toString();
726 // Get the export file output stream.
727 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(noEncryptionFileNameString));
729 // Export the unencrypted file.
730 String noEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(exportFileOutputStream, this);
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();
736 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + noEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
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();
744 case PASSWORD_ENCRYPTION:
746 // Create a temporary unencrypted export file.
747 File temporaryUnencryptedExportFile = File.createTempFile("temporary_unencrypted_export_file", null, getApplicationContext().getCacheDir());
749 // Create a temporary unencrypted export output stream.
750 FileOutputStream temporaryUnencryptedExportOutputStream = new FileOutputStream(temporaryUnencryptedExportFile);
752 // Populate the temporary unencrypted export.
753 String passwordEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportOutputStream, this);
755 // Close the temporary unencrypted export output stream.
756 temporaryUnencryptedExportOutputStream.close();
758 // Create an unencrypted export file input stream.
759 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
761 // Get the encryption password.
762 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
764 // Initialize a secure random number generator.
765 SecureRandom secureRandom = new SecureRandom();
767 // Get a 256 bit (32 byte) random salt.
768 byte[] saltByteArray = new byte[32];
769 secureRandom.nextBytes(saltByteArray);
771 // Convert the encryption password to a byte array.
772 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
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);
779 // Get a SHA-512 message digest.
780 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
782 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
783 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
785 // Truncate the encryption password byte array to 256 bits (32 bytes).
786 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
788 // Create an AES secret key from the encryption password byte array.
789 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
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);
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");
798 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
799 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
801 // Initialize the cipher.
802 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
804 // Get the file name string.
805 String passwordEncryptionFileNameString = fileNameEditText.getText().toString();
807 // Get the export file output stream.
808 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(passwordEncryptionFileNameString));
810 // Add the salt and the initialization vector to the export file output stream.
811 exportFileOutputStream.write(saltByteArray);
812 exportFileOutputStream.write(initializationVector);
814 // Create a cipher output stream.
815 CipherOutputStream cipherOutputStream = new CipherOutputStream(exportFileOutputStream, cipher);
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];
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);
827 // Close the streams.
828 cipherOutputStream.flush();
829 cipherOutputStream.close();
830 exportFileOutputStream.close();
831 unencryptedExportFileInputStream.close();
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);
844 // Delete the temporary unencrypted export file.
845 //noinspection ResultOfMethodCallIgnored
846 temporaryUnencryptedExportFile.delete();
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();
852 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + passwordEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
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();
860 case OPENPGP_ENCRYPTION:
862 // Set the temporary pre-encrypted export file.
863 temporaryPreEncryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
865 // Delete the temporary pre-encrypted export file if it already exists.
866 if (temporaryPreEncryptedExportFile.exists()) {
867 //noinspection ResultOfMethodCallIgnored
868 temporaryPreEncryptedExportFile.delete();
871 // Create a temporary pre-encrypted export output stream.
872 FileOutputStream temporaryPreEncryptedExportOutputStream = new FileOutputStream(temporaryPreEncryptedExportFile);
874 // Populate the temporary pre-encrypted export file.
875 String openpgpEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryPreEncryptedExportOutputStream, this);
877 // Flush the temporary pre-encryption export output stream.
878 temporaryPreEncryptedExportOutputStream.flush();
880 // Close the temporary pre-encryption export output stream.
881 temporaryPreEncryptedExportOutputStream.close();
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();
888 // Create an encryption intent for OpenKeychain.
889 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
891 // Include the temporary unencrypted export file URI.
892 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPreEncryptedExportFile));
894 // Allow OpenKeychain to read the file URI.
895 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
897 // Send the intent to the OpenKeychain package.
898 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
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();
911 private void restartPrivacyBrowser() {
912 // Create an intent to restart Privacy Browser.
913 Intent restartIntent = getParentActivityIntent();
915 // Assert that the intent is not null to remove the lint error below.
916 assert restartIntent != null;
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);
921 // Create a restart handler.
922 Handler restartHandler = new Handler();
924 // Create a restart runnable.
925 Runnable restartRunnable = () -> {
926 // Restart Privacy Browser.
927 startActivity(restartIntent);
929 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
933 // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
934 restartHandler.postDelayed(restartRunnable, 150);