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 KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY = "kitkat_password_encrypted_textview_visibility";
88 private final String OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY = "open_keychain_required_textview_visibility";
89 private final String FILE_LOCATION_CARD_VIEW = "file_location_card_view";
90 private final String FILE_NAME_LINEARLAYOUT_VISIBILITY = "file_name_linearlayout_visibility";
91 private final String OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY = "open_keychain_import_instructions_textview_visibility";
92 private final String IMPORT_EXPORT_BUTTON_VISIBILITY = "import_export_button_visibility";
93 private final String FILE_NAME_TEXT = "file_name_text";
94 private final String IMPORT_EXPORT_BUTTON_TEXT = "import_export_button_text";
96 // Define the class views.
97 Spinner encryptionSpinner;
98 TextInputLayout encryptionPasswordTextInputLayout;
99 EditText encryptionPasswordEditText;
100 TextView kitKatPasswordEncryptionTextView;
101 TextView openKeychainRequiredTextView;
102 CardView fileLocationCardView;
103 RadioButton importRadioButton;
104 LinearLayout fileNameLinearLayout;
105 EditText fileNameEditText;
106 TextView openKeychainImportInstructionsTextView;
107 Button importExportButton;
109 // Define the class variables.
110 private boolean openKeychainInstalled;
111 private File temporaryPgpEncryptedImportFile;
112 private File temporaryPreEncryptedExportFile;
115 public void onCreate(Bundle savedInstanceState) {
116 // Get a handle for the shared preferences.
117 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
119 // Get the preferences.
120 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
121 boolean bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
123 // Disable screenshots if not allowed.
124 if (!allowScreenshots) {
125 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
129 setTheme(R.style.PrivacyBrowser);
131 // Run the default commands.
132 super.onCreate(savedInstanceState);
134 // Set the content view.
136 setContentView(R.layout.import_export_bottom_appbar);
138 setContentView(R.layout.import_export_top_appbar);
141 // Get a handle for the toolbar.
142 Toolbar toolbar = findViewById(R.id.import_export_toolbar);
144 // Set the support action bar.
145 setSupportActionBar(toolbar);
147 // Get a handle for the action bar.
148 ActionBar actionBar = getSupportActionBar();
150 // Remove the incorrect lint warning that the action bar might be null.
151 assert actionBar != null;
153 // Display the home arrow on the support action bar.
154 actionBar.setDisplayHomeAsUpEnabled(true);
156 // Find out if OpenKeychain is installed.
158 openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
159 } catch (PackageManager.NameNotFoundException exception) {
160 openKeychainInstalled = false;
163 // Get handles for the views that need to be modified.
164 encryptionSpinner = findViewById(R.id.encryption_spinner);
165 encryptionPasswordTextInputLayout = findViewById(R.id.encryption_password_textinputlayout);
166 encryptionPasswordEditText = findViewById(R.id.encryption_password_edittext);
167 openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
168 fileLocationCardView = findViewById(R.id.file_location_cardview);
169 importRadioButton = findViewById(R.id.import_radiobutton);
170 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
171 fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
172 fileNameEditText = findViewById(R.id.file_name_edittext);
173 openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
174 importExportButton = findViewById(R.id.import_export_button);
176 // Create an array adapter for the spinner.
177 ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
179 // Set the drop down view resource on the spinner.
180 encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
182 // Set the array adapter for the spinner.
183 encryptionSpinner.setAdapter(encryptionArrayAdapter);
185 // Update the UI when the spinner changes.
186 encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
188 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
191 // Hide the unneeded layout items.
192 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
193 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
194 openKeychainRequiredTextView.setVisibility(View.GONE);
195 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
197 // Show the file location card.
198 fileLocationCardView.setVisibility(View.VISIBLE);
200 // Show the file name linear layout if either import or export is checked.
201 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
202 fileNameLinearLayout.setVisibility(View.VISIBLE);
205 // Reset the text of the import button, which may have been changed to `Decrypt`.
206 if (importRadioButton.isChecked()) {
207 importExportButton.setText(R.string.import_button);
210 // Enable the import/export button if the file name is populated.
211 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
214 case PASSWORD_ENCRYPTION:
215 // Hide the OpenPGP layout items.
216 openKeychainRequiredTextView.setVisibility(View.GONE);
217 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
219 // Show the password encryption layout items.
220 encryptionPasswordTextInputLayout.setVisibility(View.VISIBLE);
222 // Show the file location card.
223 fileLocationCardView.setVisibility(View.VISIBLE);
225 // Show the file name linear layout if either import or export is checked.
226 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
227 fileNameLinearLayout.setVisibility(View.VISIBLE);
230 // Reset the text of the import button, which may have been changed to `Decrypt`.
231 if (importRadioButton.isChecked()) {
232 importExportButton.setText(R.string.import_button);
235 // Enable the import/button if both the password and the file name are populated.
236 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
239 case OPENPGP_ENCRYPTION:
240 // Hide the password encryption layout items.
241 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
242 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
244 // Updated items based on the installation status of OpenKeychain.
245 if (openKeychainInstalled) { // OpenKeychain is installed.
246 // Show the file location card.
247 fileLocationCardView.setVisibility(View.VISIBLE);
249 if (importRadioButton.isChecked()) {
250 // Show the file name linear layout and the OpenKeychain import instructions.
251 fileNameLinearLayout.setVisibility(View.VISIBLE);
252 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
254 // Set the text of the import button to be `Decrypt`.
255 importExportButton.setText(R.string.decrypt);
257 // Enable the import button if the file name is populated.
258 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
259 } else if (exportRadioButton.isChecked()) {
260 // Hide the file name linear layout and the OpenKeychain import instructions.
261 fileNameLinearLayout.setVisibility(View.GONE);
262 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
264 // Enable the export button.
265 importExportButton.setEnabled(true);
267 } else { // OpenKeychain is not installed.
268 // Show the OpenPGP required layout item.
269 openKeychainRequiredTextView.setVisibility(View.VISIBLE);
271 // Hide the file location card.
272 fileLocationCardView.setVisibility(View.GONE);
279 public void onNothingSelected(AdapterView<?> parent) {
284 // Update the status of the import/export button when the password changes.
285 encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
287 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
292 public void onTextChanged(CharSequence s, int start, int before, int count) {
297 public void afterTextChanged(Editable s) {
298 // Enable the import/export button if both the file string and the password are populated.
299 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
303 // Update the UI when the file name EditText changes.
304 fileNameEditText.addTextChangedListener(new TextWatcher() {
306 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
311 public void onTextChanged(CharSequence s, int start, int before, int count) {
316 public void afterTextChanged(Editable s) {
317 // Adjust the UI according to the encryption spinner position.
318 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) {
319 // Enable the import/export button if both the file name and the password are populated.
320 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
322 // Enable the export button if the file name is populated.
323 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
328 // Check to see if the activity has been restarted.
329 if (savedInstanceState == null) { // The app has not been restarted.
330 // Initially hide the unneeded views.
331 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
332 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
333 openKeychainRequiredTextView.setVisibility(View.GONE);
334 fileNameLinearLayout.setVisibility(View.GONE);
335 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
336 importExportButton.setVisibility(View.GONE);
337 } else { // The app has been restarted.
338 // Restore the visibility of the views.
339 encryptionPasswordTextInputLayout.setVisibility(savedInstanceState.getInt(ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY));
340 kitKatPasswordEncryptionTextView.setVisibility(savedInstanceState.getInt(KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY));
341 openKeychainRequiredTextView.setVisibility(savedInstanceState.getInt(OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY));
342 fileLocationCardView.setVisibility(savedInstanceState.getInt(FILE_LOCATION_CARD_VIEW));
343 fileNameLinearLayout.setVisibility(savedInstanceState.getInt(FILE_NAME_LINEARLAYOUT_VISIBILITY));
344 openKeychainImportInstructionsTextView.setVisibility(savedInstanceState.getInt(OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY));
345 importExportButton.setVisibility(savedInstanceState.getInt(IMPORT_EXPORT_BUTTON_VISIBILITY));
348 fileNameEditText.post(() -> fileNameEditText.setText(savedInstanceState.getString(FILE_NAME_TEXT)));
349 importExportButton.setText(savedInstanceState.getString(IMPORT_EXPORT_BUTTON_TEXT));
354 public void onSaveInstanceState (@NonNull Bundle savedInstanceState) {
355 // Run the default commands.
356 super.onSaveInstanceState(savedInstanceState);
358 // Save the visibility of the views.
359 savedInstanceState.putInt(ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY, encryptionPasswordTextInputLayout.getVisibility());
360 savedInstanceState.putInt(KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY, kitKatPasswordEncryptionTextView.getVisibility());
361 savedInstanceState.putInt(OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY, openKeychainRequiredTextView.getVisibility());
362 savedInstanceState.putInt(FILE_LOCATION_CARD_VIEW, fileLocationCardView.getVisibility());
363 savedInstanceState.putInt(FILE_NAME_LINEARLAYOUT_VISIBILITY, fileNameLinearLayout.getVisibility());
364 savedInstanceState.putInt(OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY, openKeychainImportInstructionsTextView.getVisibility());
365 savedInstanceState.putInt(IMPORT_EXPORT_BUTTON_VISIBILITY, importExportButton.getVisibility());
368 savedInstanceState.putString(FILE_NAME_TEXT, fileNameEditText.getText().toString());
369 savedInstanceState.putString(IMPORT_EXPORT_BUTTON_TEXT, importExportButton.getText().toString());
372 public void onClickRadioButton(View view) {
373 // Get the current file name.
374 String fileNameString = fileNameEditText.getText().toString();
376 // Convert the file name string to a file.
377 File file = new File(fileNameString);
379 // Check to see if import or export was selected.
380 if (view.getId() == R.id.import_radiobutton) { // The import radio button is selected.
381 // Check to see if OpenPGP encryption is selected.
382 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption selected.
383 // Show the OpenKeychain import instructions.
384 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
386 // Set the text on the import/export button to be `Decrypt`.
387 importExportButton.setText(R.string.decrypt);
388 } else { // OpenPGP encryption not selected.
389 // Hide the OpenKeychain import instructions.
390 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
392 // Set the text on the import/export button to be `Import`.
393 importExportButton.setText(R.string.import_button);
396 // Display the file name views.
397 fileNameLinearLayout.setVisibility(View.VISIBLE);
398 importExportButton.setVisibility(View.VISIBLE);
400 // Check to see if the file exists.
401 if (file.exists()) { // The file exists.
402 // Check to see if password encryption is selected.
403 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) { // Password encryption is selected.
404 // Enable the import button if the encryption password is populated.
405 importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
406 } else { // Password encryption is not selected.
407 // Enable the import/decrypt button.
408 importExportButton.setEnabled(true);
410 } else { // The file does not exist.
411 // Disable the import/decrypt button.
412 importExportButton.setEnabled(false);
414 } else { // The export radio button is selected.
415 // Hide the OpenKeychain import instructions.
416 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
418 // Set the text on the import/export button to be `Export`.
419 importExportButton.setText(R.string.export);
421 // Show the import/export button.
422 importExportButton.setVisibility(View.VISIBLE);
424 // Check to see if OpenPGP encryption is selected.
425 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption is selected.
426 // Hide the file name views.
427 fileNameLinearLayout.setVisibility(View.GONE);
429 // Enable the export button.
430 importExportButton.setEnabled(true);
431 } else { // OpenPGP encryption is not selected.
432 // Show the file name view.
433 fileNameLinearLayout.setVisibility(View.VISIBLE);
435 // Check the encryption type.
436 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
437 // Enable the export button if the file name is populated.
438 importExportButton.setEnabled(!fileNameString.isEmpty());
439 } else { // Password encryption is selected.
440 // Enable the export button if the file name and the password are populated.
441 importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
447 public void browse(View view) {
448 // Check to see if import or export is selected.
449 if (importRadioButton.isChecked()) { // Import is selected.
450 // Create the file picker intent.
451 Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
453 // Set the intent MIME type to include all files so that everything is visible.
454 importBrowseIntent.setType("*/*");
456 // Request a file that can be opened.
457 importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
459 // Launch the file picker.
460 startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
461 } else { // Export is selected
462 // Create the file picker intent.
463 Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
465 // Set the intent MIME type to include all files so that everything is visible.
466 exportBrowseIntent.setType("*/*");
468 // Set the initial export file name according to the encryption type.
469 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
470 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
471 } else { // Password encryption is selected.
472 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs.aes");
475 // Request a file that can be opened.
476 exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
478 // Launch the file picker.
479 startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
484 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
485 // Run the default commands.
486 super.onActivityResult(requestCode, resultCode, returnedIntent);
488 switch (requestCode) {
489 case (BROWSE_RESULT_CODE):
490 // Only do something if the user didn't press back from the file picker.
491 if (resultCode == Activity.RESULT_OK) {
492 // Get the file path URI from the intent.
493 Uri fileNameUri = returnedIntent.getData();
495 // Get the file name string from the URI.
496 String fileNameString = fileNameUri.toString();
498 // Set the file name name text.
499 fileNameEditText.setText(fileNameString);
501 // Move the cursor to the end of the file name edit text.
502 fileNameEditText.setSelection(fileNameString.length());
506 case OPENPGP_IMPORT_RESULT_CODE:
507 // Delete the temporary PGP encrypted import file.
508 if (temporaryPgpEncryptedImportFile.exists()) {
509 //noinspection ResultOfMethodCallIgnored
510 temporaryPgpEncryptedImportFile.delete();
514 case OPENPGP_EXPORT_RESULT_CODE:
515 // Delete the temporary pre-encrypted export file if it exists.
516 if (temporaryPreEncryptedExportFile.exists()) {
517 //noinspection ResultOfMethodCallIgnored
518 temporaryPreEncryptedExportFile.delete();
524 public void importExport(View view) {
525 // Instantiate the import export database helper.
526 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
528 // Check to see if import or export is selected.
529 if (importRadioButton.isChecked()) { // Import is selected.
530 // Initialize the import status string
531 String importStatus = "";
533 // Get the file name string.
534 String fileNameString = fileNameEditText.getText().toString();
536 // Import according to the encryption type.
537 switch (encryptionSpinner.getSelectedItemPosition()) {
540 // Get an input stream for the file name.
541 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
543 // Import the unencrypted file.
544 importStatus = importExportDatabaseHelper.importUnencrypted(inputStream, this);
545 } catch (FileNotFoundException exception) {
546 // Update the import status.
547 importStatus = exception.toString();
550 // Restart Privacy Browser if successful.
551 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
552 restartPrivacyBrowser();
556 case PASSWORD_ENCRYPTION:
558 // Get the encryption password.
559 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
561 // Get an input stream for the file name.
562 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
564 // Get the salt from the beginning of the import file.
565 byte[] saltByteArray = new byte[32];
566 //noinspection ResultOfMethodCallIgnored
567 inputStream.read(saltByteArray);
569 // Get the initialization vector from the import file.
570 byte[] initializationVector = new byte[12];
571 //noinspection ResultOfMethodCallIgnored
572 inputStream.read(initializationVector);
574 // Convert the encryption password to a byte array.
575 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
577 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
578 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
579 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
580 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
582 // Get a SHA-512 message digest.
583 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
585 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
586 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
588 // Truncate the encryption password byte array to 256 bits (32 bytes).
589 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
591 // Create an AES secret key from the encryption password byte array.
592 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
594 // 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.
595 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
597 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
598 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
600 // Initialize the cipher.
601 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
603 // Create a cipher input stream.
604 CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
606 // 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.
607 int numberOfBytesRead;
608 byte[] decryptedBytes = new byte[16];
611 // Create a private temporary unencrypted import file.
612 File temporaryUnencryptedImportFile = File.createTempFile("temporary_unencrypted_import_file", null, getApplicationContext().getCacheDir());
614 // Create an temporary unencrypted import file output stream.
615 FileOutputStream temporaryUnencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
618 // 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.
619 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
620 // Write the data to the temporary unencrypted import file output stream.
621 temporaryUnencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
625 // Flush the temporary unencrypted import file output stream.
626 temporaryUnencryptedImportFileOutputStream.flush();
628 // Close the streams.
629 temporaryUnencryptedImportFileOutputStream.close();
630 cipherInputStream.close();
633 // Wipe the encryption data from memory.
634 //noinspection UnusedAssignment
635 encryptionPasswordString = "";
636 Arrays.fill(saltByteArray, (byte) 0);
637 Arrays.fill(initializationVector, (byte) 0);
638 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
639 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
640 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
641 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
642 Arrays.fill(decryptedBytes, (byte) 0);
644 // Create a temporary unencrypted import file input stream.
645 FileInputStream temporaryUnencryptedImportFileInputStream = new FileInputStream(temporaryUnencryptedImportFile);
647 // Import the temporary unencrypted import file.
648 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFileInputStream, this);
650 // Close the temporary unencrypted import file input stream.
651 temporaryUnencryptedImportFileInputStream.close();
653 // Delete the temporary unencrypted import file.
654 //noinspection ResultOfMethodCallIgnored
655 temporaryUnencryptedImportFile.delete();
657 // Restart Privacy Browser if successful.
658 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
659 restartPrivacyBrowser();
661 } catch (Exception exception) {
662 // Update the import status.
663 importStatus = exception.toString();
667 case OPENPGP_ENCRYPTION:
669 // Set the temporary PGP encrypted import file.
670 temporaryPgpEncryptedImportFile = File.createTempFile("temporary_pgp_encrypted_import_file", null, getApplicationContext().getCacheDir());
672 // Create a temporary PGP encrypted import file output stream.
673 FileOutputStream temporaryPgpEncryptedImportFileOutputStream = new FileOutputStream(temporaryPgpEncryptedImportFile);
675 // Get an input stream for the file name.
676 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
678 // Create a transfer byte array.
679 byte[] transferByteArray = new byte[1024];
681 // Create an integer to track the number of bytes read.
684 // Copy the input stream to the temporary PGP encrypted import file.
685 while ((bytesRead = inputStream.read(transferByteArray)) > 0) {
686 temporaryPgpEncryptedImportFileOutputStream.write(transferByteArray, 0, bytesRead);
689 // Flush the temporary PGP encrypted import file output stream.
690 temporaryPgpEncryptedImportFileOutputStream.flush();
692 // Close the streams.
694 temporaryPgpEncryptedImportFileOutputStream.close();
696 // Create an decryption intent for OpenKeychain.
697 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
699 // Include the URI to be decrypted.
700 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPgpEncryptedImportFile));
702 // Allow OpenKeychain to read the file URI.
703 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
705 // Send the intent to the OpenKeychain package.
706 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
709 startActivityForResult(openKeychainDecryptIntent, OPENPGP_IMPORT_RESULT_CODE);
711 // Update the import status.
712 importStatus = ImportExportDatabaseHelper.IMPORT_SUCCESSFUL;
713 } catch (Exception exception) {
714 // Update the import status.
715 importStatus = exception.toString();
720 // Respond to the import status.
721 if (!importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
722 // Display a snack bar with the import error.
723 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();
725 } else { // Export is selected.
726 // Export according to the encryption type.
727 switch (encryptionSpinner.getSelectedItemPosition()) {
729 // Get the file name string.
730 String noEncryptionFileNameString = fileNameEditText.getText().toString();
733 // Get the export file output stream.
734 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(noEncryptionFileNameString));
736 // Export the unencrypted file.
737 String noEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(exportFileOutputStream, this);
739 // Display an export disposition snackbar.
740 if (noEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
741 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
743 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + noEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
745 } catch (FileNotFoundException fileNotFoundException) {
746 // Display a snackbar with the exception.
747 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + fileNotFoundException, Snackbar.LENGTH_INDEFINITE).show();
751 case PASSWORD_ENCRYPTION:
753 // Create a temporary unencrypted export file.
754 File temporaryUnencryptedExportFile = File.createTempFile("temporary_unencrypted_export_file", null, getApplicationContext().getCacheDir());
756 // Create a temporary unencrypted export output stream.
757 FileOutputStream temporaryUnencryptedExportOutputStream = new FileOutputStream(temporaryUnencryptedExportFile);
759 // Populate the temporary unencrypted export.
760 String passwordEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportOutputStream, this);
762 // Close the temporary unencrypted export output stream.
763 temporaryUnencryptedExportOutputStream.close();
765 // Create an unencrypted export file input stream.
766 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
768 // Get the encryption password.
769 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
771 // Initialize a secure random number generator.
772 SecureRandom secureRandom = new SecureRandom();
774 // Get a 256 bit (32 byte) random salt.
775 byte[] saltByteArray = new byte[32];
776 secureRandom.nextBytes(saltByteArray);
778 // Convert the encryption password to a byte array.
779 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
781 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
782 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
783 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
784 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
786 // Get a SHA-512 message digest.
787 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
789 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
790 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
792 // Truncate the encryption password byte array to 256 bits (32 bytes).
793 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
795 // Create an AES secret key from the encryption password byte array.
796 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
798 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
799 byte[] initializationVector = new byte[12];
800 secureRandom.nextBytes(initializationVector);
802 // 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.
803 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
805 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
806 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
808 // Initialize the cipher.
809 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
811 // Get the file name string.
812 String passwordEncryptionFileNameString = fileNameEditText.getText().toString();
814 // Get the export file output stream.
815 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(passwordEncryptionFileNameString));
817 // Add the salt and the initialization vector to the export file output stream.
818 exportFileOutputStream.write(saltByteArray);
819 exportFileOutputStream.write(initializationVector);
821 // Create a cipher output stream.
822 CipherOutputStream cipherOutputStream = new CipherOutputStream(exportFileOutputStream, cipher);
824 // 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.
825 int numberOfBytesRead;
826 byte[] encryptedBytes = new byte[16];
828 // 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.
829 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
830 // Write the data to the cipher output stream.
831 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
834 // Close the streams.
835 cipherOutputStream.flush();
836 cipherOutputStream.close();
837 exportFileOutputStream.close();
838 unencryptedExportFileInputStream.close();
840 // Wipe the encryption data from memory.
841 //noinspection UnusedAssignment
842 encryptionPasswordString = "";
843 Arrays.fill(saltByteArray, (byte) 0);
844 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
845 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
846 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
847 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
848 Arrays.fill(initializationVector, (byte) 0);
849 Arrays.fill(encryptedBytes, (byte) 0);
851 // Delete the temporary unencrypted export file.
852 //noinspection ResultOfMethodCallIgnored
853 temporaryUnencryptedExportFile.delete();
855 // Display an export disposition snackbar.
856 if (passwordEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
857 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
859 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + passwordEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
861 } catch (Exception exception) {
862 // Display a snackbar with the exception.
863 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
867 case OPENPGP_ENCRYPTION:
869 // Set the temporary pre-encrypted export file.
870 temporaryPreEncryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
872 // Delete the temporary pre-encrypted export file if it already exists.
873 if (temporaryPreEncryptedExportFile.exists()) {
874 //noinspection ResultOfMethodCallIgnored
875 temporaryPreEncryptedExportFile.delete();
878 // Create a temporary pre-encrypted export output stream.
879 FileOutputStream temporaryPreEncryptedExportOutputStream = new FileOutputStream(temporaryPreEncryptedExportFile);
881 // Populate the temporary pre-encrypted export file.
882 String openpgpEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryPreEncryptedExportOutputStream, this);
884 // Flush the temporary pre-encryption export output stream.
885 temporaryPreEncryptedExportOutputStream.flush();
887 // Close the temporary pre-encryption export output stream.
888 temporaryPreEncryptedExportOutputStream.close();
890 // Display an export error snackbar if the temporary pre-encrypted export failed.
891 if (!openpgpEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
892 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + openpgpEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
895 // Create an encryption intent for OpenKeychain.
896 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
898 // Include the temporary unencrypted export file URI.
899 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPreEncryptedExportFile));
901 // Allow OpenKeychain to read the file URI.
902 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
904 // Send the intent to the OpenKeychain package.
905 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
908 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
909 } catch (Exception exception) {
910 // Display a snackbar with the exception.
911 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
918 private void restartPrivacyBrowser() {
919 // Create an intent to restart Privacy Browser.
920 Intent restartIntent = getParentActivityIntent();
922 // Assert that the intent is not null to remove the lint error below.
923 assert restartIntent != null;
925 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
926 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
928 // Create a restart handler.
929 Handler restartHandler = new Handler();
931 // Create a restart runnable.
932 Runnable restartRunnable = () -> {
933 // Restart Privacy Browser.
934 startActivity(restartIntent);
936 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
940 // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
941 restartHandler.postDelayed(restartRunnable, 150);