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);
126 // Run the default commands.
127 super.onCreate(savedInstanceState);
129 // Set the content view.
131 setContentView(R.layout.import_export_bottom_appbar);
133 setContentView(R.layout.import_export_top_appbar);
136 // Get a handle for the toolbar.
137 Toolbar toolbar = findViewById(R.id.import_export_toolbar);
139 // Set the support action bar.
140 setSupportActionBar(toolbar);
142 // Get a handle for the action bar.
143 ActionBar actionBar = getSupportActionBar();
145 // Remove the incorrect lint warning that the action bar might be null.
146 assert actionBar != null;
148 // Display the home arrow on the support action bar.
149 actionBar.setDisplayHomeAsUpEnabled(true);
151 // Find out if OpenKeychain is installed.
153 openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
154 } catch (PackageManager.NameNotFoundException exception) {
155 openKeychainInstalled = false;
158 // Get handles for the views that need to be modified.
159 encryptionSpinner = findViewById(R.id.encryption_spinner);
160 encryptionPasswordTextInputLayout = findViewById(R.id.encryption_password_textinputlayout);
161 encryptionPasswordEditText = findViewById(R.id.encryption_password_edittext);
162 openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
163 fileLocationCardView = findViewById(R.id.file_location_cardview);
164 importRadioButton = findViewById(R.id.import_radiobutton);
165 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
166 fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
167 fileNameEditText = findViewById(R.id.file_name_edittext);
168 openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
169 importExportButton = findViewById(R.id.import_export_button);
171 // Create an array adapter for the spinner.
172 ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
174 // Set the drop down view resource on the spinner.
175 encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
177 // Set the array adapter for the spinner.
178 encryptionSpinner.setAdapter(encryptionArrayAdapter);
180 // Update the UI when the spinner changes.
181 encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
183 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
186 // Hide the unneeded layout items.
187 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
188 openKeychainRequiredTextView.setVisibility(View.GONE);
189 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
191 // Show the file location card.
192 fileLocationCardView.setVisibility(View.VISIBLE);
194 // Show the file name linear layout if either import or export is checked.
195 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
196 fileNameLinearLayout.setVisibility(View.VISIBLE);
199 // Reset the text of the import button, which may have been changed to `Decrypt`.
200 if (importRadioButton.isChecked()) {
201 importExportButton.setText(R.string.import_button);
204 // Enable the import/export button if the file name is populated.
205 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
208 case PASSWORD_ENCRYPTION:
209 // Hide the OpenPGP layout items.
210 openKeychainRequiredTextView.setVisibility(View.GONE);
211 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
213 // Show the password encryption layout items.
214 encryptionPasswordTextInputLayout.setVisibility(View.VISIBLE);
216 // Show the file location card.
217 fileLocationCardView.setVisibility(View.VISIBLE);
219 // Show the file name linear layout if either import or export is checked.
220 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
221 fileNameLinearLayout.setVisibility(View.VISIBLE);
224 // Reset the text of the import button, which may have been changed to `Decrypt`.
225 if (importRadioButton.isChecked()) {
226 importExportButton.setText(R.string.import_button);
229 // Enable the import/button if both the password and the file name are populated.
230 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
233 case OPENPGP_ENCRYPTION:
234 // Hide the password encryption layout items.
235 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
237 // Updated items based on the installation status of OpenKeychain.
238 if (openKeychainInstalled) { // OpenKeychain is installed.
239 // Show the file location card.
240 fileLocationCardView.setVisibility(View.VISIBLE);
242 if (importRadioButton.isChecked()) {
243 // Show the file name linear layout and the OpenKeychain import instructions.
244 fileNameLinearLayout.setVisibility(View.VISIBLE);
245 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
247 // Set the text of the import button to be `Decrypt`.
248 importExportButton.setText(R.string.decrypt);
250 // Enable the import button if the file name is populated.
251 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
252 } else if (exportRadioButton.isChecked()) {
253 // Hide the file name linear layout and the OpenKeychain import instructions.
254 fileNameLinearLayout.setVisibility(View.GONE);
255 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
257 // Enable the export button.
258 importExportButton.setEnabled(true);
260 } else { // OpenKeychain is not installed.
261 // Show the OpenPGP required layout item.
262 openKeychainRequiredTextView.setVisibility(View.VISIBLE);
264 // Hide the file location card.
265 fileLocationCardView.setVisibility(View.GONE);
272 public void onNothingSelected(AdapterView<?> parent) {
277 // Update the status of the import/export button when the password changes.
278 encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
280 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
285 public void onTextChanged(CharSequence s, int start, int before, int count) {
290 public void afterTextChanged(Editable s) {
291 // Enable the import/export button if both the file string and the password are populated.
292 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
296 // Update the UI when the file name EditText changes.
297 fileNameEditText.addTextChangedListener(new TextWatcher() {
299 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
304 public void onTextChanged(CharSequence s, int start, int before, int count) {
309 public void afterTextChanged(Editable s) {
310 // Adjust the UI according to the encryption spinner position.
311 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) {
312 // Enable the import/export button if both the file name and the password are populated.
313 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
315 // Enable the export button if the file name is populated.
316 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
321 // Check to see if the activity has been restarted.
322 if (savedInstanceState == null) { // The app has not been restarted.
323 // Initially hide the unneeded views.
324 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
325 openKeychainRequiredTextView.setVisibility(View.GONE);
326 fileNameLinearLayout.setVisibility(View.GONE);
327 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
328 importExportButton.setVisibility(View.GONE);
329 } else { // The app has been restarted.
330 // Restore the visibility of the views.
331 encryptionPasswordTextInputLayout.setVisibility(savedInstanceState.getInt(ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY));
332 openKeychainRequiredTextView.setVisibility(savedInstanceState.getInt(OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY));
333 fileLocationCardView.setVisibility(savedInstanceState.getInt(FILE_LOCATION_CARD_VIEW));
334 fileNameLinearLayout.setVisibility(savedInstanceState.getInt(FILE_NAME_LINEARLAYOUT_VISIBILITY));
335 openKeychainImportInstructionsTextView.setVisibility(savedInstanceState.getInt(OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY));
336 importExportButton.setVisibility(savedInstanceState.getInt(IMPORT_EXPORT_BUTTON_VISIBILITY));
339 fileNameEditText.post(() -> fileNameEditText.setText(savedInstanceState.getString(FILE_NAME_TEXT)));
340 importExportButton.setText(savedInstanceState.getString(IMPORT_EXPORT_BUTTON_TEXT));
345 public void onSaveInstanceState (@NonNull Bundle savedInstanceState) {
346 // Run the default commands.
347 super.onSaveInstanceState(savedInstanceState);
349 // Save the visibility of the views.
350 savedInstanceState.putInt(ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY, encryptionPasswordTextInputLayout.getVisibility());
351 savedInstanceState.putInt(OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY, openKeychainRequiredTextView.getVisibility());
352 savedInstanceState.putInt(FILE_LOCATION_CARD_VIEW, fileLocationCardView.getVisibility());
353 savedInstanceState.putInt(FILE_NAME_LINEARLAYOUT_VISIBILITY, fileNameLinearLayout.getVisibility());
354 savedInstanceState.putInt(OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY, openKeychainImportInstructionsTextView.getVisibility());
355 savedInstanceState.putInt(IMPORT_EXPORT_BUTTON_VISIBILITY, importExportButton.getVisibility());
358 savedInstanceState.putString(FILE_NAME_TEXT, fileNameEditText.getText().toString());
359 savedInstanceState.putString(IMPORT_EXPORT_BUTTON_TEXT, importExportButton.getText().toString());
362 public void onClickRadioButton(View view) {
363 // Get the current file name.
364 String fileNameString = fileNameEditText.getText().toString();
366 // Convert the file name string to a file.
367 File file = new File(fileNameString);
369 // Check to see if import or export was selected.
370 if (view.getId() == R.id.import_radiobutton) { // The import radio button is selected.
371 // Check to see if OpenPGP encryption is selected.
372 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption selected.
373 // Show the OpenKeychain import instructions.
374 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
376 // Set the text on the import/export button to be `Decrypt`.
377 importExportButton.setText(R.string.decrypt);
378 } else { // OpenPGP encryption not selected.
379 // Hide the OpenKeychain import instructions.
380 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
382 // Set the text on the import/export button to be `Import`.
383 importExportButton.setText(R.string.import_button);
386 // Display the file name views.
387 fileNameLinearLayout.setVisibility(View.VISIBLE);
388 importExportButton.setVisibility(View.VISIBLE);
390 // Check to see if the file exists.
391 if (file.exists()) { // The file exists.
392 // Check to see if password encryption is selected.
393 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) { // Password encryption is selected.
394 // Enable the import button if the encryption password is populated.
395 importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
396 } else { // Password encryption is not selected.
397 // Enable the import/decrypt button.
398 importExportButton.setEnabled(true);
400 } else { // The file does not exist.
401 // Disable the import/decrypt button.
402 importExportButton.setEnabled(false);
404 } else { // The export radio button is selected.
405 // Hide the OpenKeychain import instructions.
406 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
408 // Set the text on the import/export button to be `Export`.
409 importExportButton.setText(R.string.export);
411 // Show the import/export button.
412 importExportButton.setVisibility(View.VISIBLE);
414 // Check to see if OpenPGP encryption is selected.
415 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption is selected.
416 // Hide the file name views.
417 fileNameLinearLayout.setVisibility(View.GONE);
419 // Enable the export button.
420 importExportButton.setEnabled(true);
421 } else { // OpenPGP encryption is not selected.
422 // Show the file name view.
423 fileNameLinearLayout.setVisibility(View.VISIBLE);
425 // Check the encryption type.
426 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
427 // Enable the export button if the file name is populated.
428 importExportButton.setEnabled(!fileNameString.isEmpty());
429 } else { // Password encryption is selected.
430 // Enable the export button if the file name and the password are populated.
431 importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
437 public void browse(View view) {
438 // Check to see if import or export is selected.
439 if (importRadioButton.isChecked()) { // Import is selected.
440 // Create the file picker intent.
441 Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
443 // Set the intent MIME type to include all files so that everything is visible.
444 importBrowseIntent.setType("*/*");
446 // Request a file that can be opened.
447 importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
449 // Launch the file picker.
450 startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
451 } else { // Export is selected
452 // Create the file picker intent.
453 Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
455 // Set the intent MIME type to include all files so that everything is visible.
456 exportBrowseIntent.setType("*/*");
458 // Set the initial export file name according to the encryption type.
459 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
460 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
461 } else { // Password encryption is selected.
462 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs.aes");
465 // Request a file that can be opened.
466 exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
468 // Launch the file picker.
469 startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
474 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
475 // Run the default commands.
476 super.onActivityResult(requestCode, resultCode, returnedIntent);
478 switch (requestCode) {
479 case (BROWSE_RESULT_CODE):
480 // Only do something if the user didn't press back from the file picker.
481 if (resultCode == Activity.RESULT_OK) {
482 // Get the file path URI from the intent.
483 Uri fileNameUri = returnedIntent.getData();
485 // Get the file name string from the URI.
486 String fileNameString = fileNameUri.toString();
488 // Set the file name name text.
489 fileNameEditText.setText(fileNameString);
491 // Move the cursor to the end of the file name edit text.
492 fileNameEditText.setSelection(fileNameString.length());
496 case OPENPGP_IMPORT_RESULT_CODE:
497 // Delete the temporary PGP encrypted import file.
498 if (temporaryPgpEncryptedImportFile.exists()) {
499 //noinspection ResultOfMethodCallIgnored
500 temporaryPgpEncryptedImportFile.delete();
504 case OPENPGP_EXPORT_RESULT_CODE:
505 // Delete the temporary pre-encrypted export file if it exists.
506 if (temporaryPreEncryptedExportFile.exists()) {
507 //noinspection ResultOfMethodCallIgnored
508 temporaryPreEncryptedExportFile.delete();
514 public void importExport(View view) {
515 // Instantiate the import export database helper.
516 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
518 // Check to see if import or export is selected.
519 if (importRadioButton.isChecked()) { // Import is selected.
520 // Initialize the import status string
521 String importStatus = "";
523 // Get the file name string.
524 String fileNameString = fileNameEditText.getText().toString();
526 // Import according to the encryption type.
527 switch (encryptionSpinner.getSelectedItemPosition()) {
530 // Get an input stream for the file name.
531 // A file may be opened directly once the minimum API >= 29. <https://developer.android.com/reference/kotlin/android/content/ContentResolver#openfile>
532 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
534 // Import the unencrypted file.
535 importStatus = importExportDatabaseHelper.importUnencrypted(inputStream, this);
536 } catch (FileNotFoundException exception) {
537 // Update the import status.
538 importStatus = exception.toString();
541 // Restart Privacy Browser if successful.
542 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
543 restartPrivacyBrowser();
547 case PASSWORD_ENCRYPTION:
549 // Get the encryption password.
550 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
552 // Get an input stream for the file name.
553 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
555 // Get the salt from the beginning of the import file.
556 byte[] saltByteArray = new byte[32];
557 //noinspection ResultOfMethodCallIgnored
558 inputStream.read(saltByteArray);
560 // Get the initialization vector from the import file.
561 byte[] initializationVector = new byte[12];
562 //noinspection ResultOfMethodCallIgnored
563 inputStream.read(initializationVector);
565 // Convert the encryption password to a byte array.
566 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
568 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
569 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
570 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
571 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
573 // Get a SHA-512 message digest.
574 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
576 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
577 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
579 // Truncate the encryption password byte array to 256 bits (32 bytes).
580 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
582 // Create an AES secret key from the encryption password byte array.
583 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
585 // 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.
586 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
588 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
589 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
591 // Initialize the cipher.
592 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
594 // Create a cipher input stream.
595 CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
597 // 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.
598 int numberOfBytesRead;
599 byte[] decryptedBytes = new byte[16];
602 // Create a private temporary unencrypted import file.
603 File temporaryUnencryptedImportFile = File.createTempFile("temporary_unencrypted_import_file", null, getApplicationContext().getCacheDir());
605 // Create an temporary unencrypted import file output stream.
606 FileOutputStream temporaryUnencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
609 // 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.
610 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
611 // Write the data to the temporary unencrypted import file output stream.
612 temporaryUnencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
616 // Flush the temporary unencrypted import file output stream.
617 temporaryUnencryptedImportFileOutputStream.flush();
619 // Close the streams.
620 temporaryUnencryptedImportFileOutputStream.close();
621 cipherInputStream.close();
624 // Wipe the encryption data from memory.
625 //noinspection UnusedAssignment
626 encryptionPasswordString = "";
627 Arrays.fill(saltByteArray, (byte) 0);
628 Arrays.fill(initializationVector, (byte) 0);
629 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
630 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
631 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
632 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
633 Arrays.fill(decryptedBytes, (byte) 0);
635 // Create a temporary unencrypted import file input stream.
636 FileInputStream temporaryUnencryptedImportFileInputStream = new FileInputStream(temporaryUnencryptedImportFile);
638 // Import the temporary unencrypted import file.
639 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFileInputStream, this);
641 // Close the temporary unencrypted import file input stream.
642 temporaryUnencryptedImportFileInputStream.close();
644 // Delete the temporary unencrypted import file.
645 //noinspection ResultOfMethodCallIgnored
646 temporaryUnencryptedImportFile.delete();
648 // Restart Privacy Browser if successful.
649 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
650 restartPrivacyBrowser();
652 } catch (Exception exception) {
653 // Update the import status.
654 importStatus = exception.toString();
658 case OPENPGP_ENCRYPTION:
660 // Set the temporary PGP encrypted import file.
661 temporaryPgpEncryptedImportFile = File.createTempFile("temporary_pgp_encrypted_import_file", null, getApplicationContext().getCacheDir());
663 // Create a temporary PGP encrypted import file output stream.
664 FileOutputStream temporaryPgpEncryptedImportFileOutputStream = new FileOutputStream(temporaryPgpEncryptedImportFile);
666 // Get an input stream for the file name.
667 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
669 // Create a transfer byte array.
670 byte[] transferByteArray = new byte[1024];
672 // Create an integer to track the number of bytes read.
675 // Copy the input stream to the temporary PGP encrypted import file.
676 while ((bytesRead = inputStream.read(transferByteArray)) > 0) {
677 temporaryPgpEncryptedImportFileOutputStream.write(transferByteArray, 0, bytesRead);
680 // Flush the temporary PGP encrypted import file output stream.
681 temporaryPgpEncryptedImportFileOutputStream.flush();
683 // Close the streams.
685 temporaryPgpEncryptedImportFileOutputStream.close();
687 // Create an decryption intent for OpenKeychain.
688 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
690 // Include the URI to be decrypted.
691 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPgpEncryptedImportFile));
693 // Allow OpenKeychain to read the file URI.
694 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
696 // Send the intent to the OpenKeychain package.
697 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
700 startActivityForResult(openKeychainDecryptIntent, OPENPGP_IMPORT_RESULT_CODE);
702 // Update the import status.
703 importStatus = ImportExportDatabaseHelper.IMPORT_SUCCESSFUL;
704 } catch (Exception exception) {
705 // Update the import status.
706 importStatus = exception.toString();
711 // Respond to the import status.
712 if (!importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
713 // Display a snack bar with the import error.
714 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();
716 } else { // Export is selected.
717 // Export according to the encryption type.
718 switch (encryptionSpinner.getSelectedItemPosition()) {
720 // Get the file name string.
721 String noEncryptionFileNameString = fileNameEditText.getText().toString();
724 // Get the export file output stream.
725 // A file may be opened directly once the minimum API >= 29. <https://developer.android.com/reference/kotlin/android/content/ContentResolver#openfile>
726 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(noEncryptionFileNameString));
728 // Export the unencrypted file.
729 String noEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(exportFileOutputStream, this);
731 // Display an export disposition snackbar.
732 if (noEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
733 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
735 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + noEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
737 } catch (FileNotFoundException fileNotFoundException) {
738 // Display a snackbar with the exception.
739 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + fileNotFoundException, Snackbar.LENGTH_INDEFINITE).show();
743 case PASSWORD_ENCRYPTION:
745 // Create a temporary unencrypted export file.
746 File temporaryUnencryptedExportFile = File.createTempFile("temporary_unencrypted_export_file", null, getApplicationContext().getCacheDir());
748 // Create a temporary unencrypted export output stream.
749 FileOutputStream temporaryUnencryptedExportOutputStream = new FileOutputStream(temporaryUnencryptedExportFile);
751 // Populate the temporary unencrypted export.
752 String passwordEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportOutputStream, this);
754 // Close the temporary unencrypted export output stream.
755 temporaryUnencryptedExportOutputStream.close();
757 // Create an unencrypted export file input stream.
758 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
760 // Get the encryption password.
761 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
763 // Initialize a secure random number generator.
764 SecureRandom secureRandom = new SecureRandom();
766 // Get a 256 bit (32 byte) random salt.
767 byte[] saltByteArray = new byte[32];
768 secureRandom.nextBytes(saltByteArray);
770 // Convert the encryption password to a byte array.
771 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
773 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
774 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
775 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
776 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
778 // Get a SHA-512 message digest.
779 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
781 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
782 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
784 // Truncate the encryption password byte array to 256 bits (32 bytes).
785 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
787 // Create an AES secret key from the encryption password byte array.
788 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
790 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
791 byte[] initializationVector = new byte[12];
792 secureRandom.nextBytes(initializationVector);
794 // 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.
795 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
797 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
798 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
800 // Initialize the cipher.
801 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
803 // Get the file name string.
804 String passwordEncryptionFileNameString = fileNameEditText.getText().toString();
806 // Get the export file output stream.
807 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(passwordEncryptionFileNameString));
809 // Add the salt and the initialization vector to the export file output stream.
810 exportFileOutputStream.write(saltByteArray);
811 exportFileOutputStream.write(initializationVector);
813 // Create a cipher output stream.
814 CipherOutputStream cipherOutputStream = new CipherOutputStream(exportFileOutputStream, cipher);
816 // 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.
817 int numberOfBytesRead;
818 byte[] encryptedBytes = new byte[16];
820 // 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.
821 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
822 // Write the data to the cipher output stream.
823 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
826 // Close the streams.
827 cipherOutputStream.flush();
828 cipherOutputStream.close();
829 exportFileOutputStream.close();
830 unencryptedExportFileInputStream.close();
832 // Wipe the encryption data from memory.
833 //noinspection UnusedAssignment
834 encryptionPasswordString = "";
835 Arrays.fill(saltByteArray, (byte) 0);
836 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
837 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
838 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
839 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
840 Arrays.fill(initializationVector, (byte) 0);
841 Arrays.fill(encryptedBytes, (byte) 0);
843 // Delete the temporary unencrypted export file.
844 //noinspection ResultOfMethodCallIgnored
845 temporaryUnencryptedExportFile.delete();
847 // Display an export disposition snackbar.
848 if (passwordEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
849 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
851 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + passwordEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
853 } catch (Exception exception) {
854 // Display a snackbar with the exception.
855 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
859 case OPENPGP_ENCRYPTION:
861 // Set the temporary pre-encrypted export file.
862 temporaryPreEncryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
864 // Delete the temporary pre-encrypted export file if it already exists.
865 if (temporaryPreEncryptedExportFile.exists()) {
866 //noinspection ResultOfMethodCallIgnored
867 temporaryPreEncryptedExportFile.delete();
870 // Create a temporary pre-encrypted export output stream.
871 FileOutputStream temporaryPreEncryptedExportOutputStream = new FileOutputStream(temporaryPreEncryptedExportFile);
873 // Populate the temporary pre-encrypted export file.
874 String openpgpEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryPreEncryptedExportOutputStream, this);
876 // Flush the temporary pre-encryption export output stream.
877 temporaryPreEncryptedExportOutputStream.flush();
879 // Close the temporary pre-encryption export output stream.
880 temporaryPreEncryptedExportOutputStream.close();
882 // Display an export error snackbar if the temporary pre-encrypted export failed.
883 if (!openpgpEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
884 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + openpgpEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
887 // Create an encryption intent for OpenKeychain.
888 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
890 // Include the temporary unencrypted export file URI.
891 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPreEncryptedExportFile));
893 // Allow OpenKeychain to read the file URI.
894 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
896 // Send the intent to the OpenKeychain package.
897 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
900 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
901 } catch (Exception exception) {
902 // Display a snackbar with the exception.
903 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
910 private void restartPrivacyBrowser() {
911 // Create an intent to restart Privacy Browser.
912 Intent restartIntent = getParentActivityIntent();
914 // Assert that the intent is not null to remove the lint error below.
915 assert restartIntent != null;
917 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
918 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
920 // Create a restart handler.
921 Handler restartHandler = new Handler();
923 // Create a restart runnable.
924 Runnable restartRunnable = () -> {
925 // Restart Privacy Browser.
926 startActivity(restartIntent);
928 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
932 // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
933 restartHandler.postDelayed(restartRunnable, 150);