2 * Copyright © 2018-2021 Soren Stoutner <soren@stoutner.com>.
4 * This file is part of Privacy Browser <https://www.stoutner.com/privacy-browser>.
6 * Privacy Browser 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 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. 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.Build;
28 import android.os.Bundle;
29 import android.os.Handler;
30 import android.preference.PreferenceManager;
31 import android.text.Editable;
32 import android.text.TextWatcher;
33 import android.view.View;
34 import android.view.WindowManager;
35 import android.widget.AdapterView;
36 import android.widget.ArrayAdapter;
37 import android.widget.Button;
38 import android.widget.EditText;
39 import android.widget.LinearLayout;
40 import android.widget.RadioButton;
41 import android.widget.Spinner;
42 import android.widget.TextView;
44 import androidx.annotation.NonNull;
45 import androidx.appcompat.app.ActionBar;
46 import androidx.appcompat.app.AppCompatActivity;
47 import androidx.appcompat.widget.Toolbar;
48 import androidx.cardview.widget.CardView;
49 import androidx.core.content.FileProvider;
51 import com.google.android.material.snackbar.Snackbar;
52 import com.google.android.material.textfield.TextInputLayout;
54 import com.stoutner.privacybrowser.BuildConfig;
55 import com.stoutner.privacybrowser.R;
56 import com.stoutner.privacybrowser.helpers.ImportExportDatabaseHelper;
59 import java.io.FileInputStream;
60 import java.io.FileNotFoundException;
61 import java.io.FileOutputStream;
62 import java.io.InputStream;
63 import java.io.OutputStream;
64 import java.nio.charset.StandardCharsets;
65 import java.security.MessageDigest;
66 import java.security.SecureRandom;
67 import java.util.Arrays;
69 import javax.crypto.Cipher;
70 import javax.crypto.CipherInputStream;
71 import javax.crypto.CipherOutputStream;
72 import javax.crypto.spec.GCMParameterSpec;
73 import javax.crypto.spec.SecretKeySpec;
75 public class ImportExportActivity extends AppCompatActivity {
76 // Define the encryption constants.
77 private final int NO_ENCRYPTION = 0;
78 private final int PASSWORD_ENCRYPTION = 1;
79 private final int OPENPGP_ENCRYPTION = 2;
81 // Define the activity result constants.
82 private final int BROWSE_RESULT_CODE = 0;
83 private final int OPENPGP_IMPORT_RESULT_CODE = 1;
84 private final int OPENPGP_EXPORT_RESULT_CODE = 2;
86 // Define the saved instance state constants.
87 private final String ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY = "encryption_password_textinputlayout_visibility";
88 private final String KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY = "kitkat_password_encrypted_textview_visibility";
89 private final String OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY = "open_keychain_required_textview_visibility";
90 private final String FILE_LOCATION_CARD_VIEW = "file_location_card_view";
91 private final String FILE_NAME_LINEARLAYOUT_VISIBILITY = "file_name_linearlayout_visibility";
92 private final String OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY = "open_keychain_import_instructions_textview_visibility";
93 private final String IMPORT_EXPORT_BUTTON_VISIBILITY = "import_export_button_visibility";
94 private final String FILE_NAME_TEXT = "file_name_text";
95 private final String IMPORT_EXPORT_BUTTON_TEXT = "import_export_button_text";
97 // Define the class views.
98 Spinner encryptionSpinner;
99 TextInputLayout encryptionPasswordTextInputLayout;
100 EditText encryptionPasswordEditText;
101 TextView kitKatPasswordEncryptionTextView;
102 TextView openKeychainRequiredTextView;
103 CardView fileLocationCardView;
104 RadioButton importRadioButton;
105 LinearLayout fileNameLinearLayout;
106 EditText fileNameEditText;
107 TextView openKeychainImportInstructionsTextView;
108 Button importExportButton;
110 // Define the class variables.
111 private boolean openKeychainInstalled;
112 private File temporaryPgpEncryptedImportFile;
113 private File temporaryPreEncryptedExportFile;
116 public void onCreate(Bundle savedInstanceState) {
117 // Get a handle for the shared preferences.
118 SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
120 // Get the preferences.
121 boolean allowScreenshots = sharedPreferences.getBoolean(getString(R.string.allow_screenshots_key), false);
122 boolean bottomAppBar = sharedPreferences.getBoolean(getString(R.string.bottom_app_bar_key), false);
124 // Disable screenshots if not allowed.
125 if (!allowScreenshots) {
126 getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
130 setTheme(R.style.PrivacyBrowser);
132 // Run the default commands.
133 super.onCreate(savedInstanceState);
135 // Set the content view.
137 setContentView(R.layout.import_export_coordinatorlayout_bottom_appbar);
139 setContentView(R.layout.import_export_coordinatorlayout_top_appbar);
142 // Get a handle for the toolbar.
143 Toolbar toolbar = findViewById(R.id.import_export_toolbar);
145 // Set the support action bar.
146 setSupportActionBar(toolbar);
148 // Get a handle for the action bar.
149 ActionBar actionBar = getSupportActionBar();
151 // Remove the incorrect lint warning that the action bar might be null.
152 assert actionBar != null;
154 // Display the home arrow on the support action bar.
155 actionBar.setDisplayHomeAsUpEnabled(true);
157 // Find out if the system is running KitKat
158 boolean runningKitKat = (Build.VERSION.SDK_INT == 19);
160 // Find out if OpenKeychain is installed.
162 openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
163 } catch (PackageManager.NameNotFoundException exception) {
164 openKeychainInstalled = false;
167 // Get handles for the views that need to be modified.
168 encryptionSpinner = findViewById(R.id.encryption_spinner);
169 encryptionPasswordTextInputLayout = findViewById(R.id.encryption_password_textinputlayout);
170 encryptionPasswordEditText = findViewById(R.id.encryption_password_edittext);
171 kitKatPasswordEncryptionTextView = findViewById(R.id.kitkat_password_encryption_textview);
172 openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
173 fileLocationCardView = findViewById(R.id.file_location_cardview);
174 importRadioButton = findViewById(R.id.import_radiobutton);
175 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
176 fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
177 fileNameEditText = findViewById(R.id.file_name_edittext);
178 openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
179 importExportButton = findViewById(R.id.import_export_button);
181 // Create an array adapter for the spinner.
182 ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
184 // Set the drop down view resource on the spinner.
185 encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
187 // Set the array adapter for the spinner.
188 encryptionSpinner.setAdapter(encryptionArrayAdapter);
190 // Update the UI when the spinner changes.
191 encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
193 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
196 // Hide the unneeded layout items.
197 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
198 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
199 openKeychainRequiredTextView.setVisibility(View.GONE);
200 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
202 // Show the file location card.
203 fileLocationCardView.setVisibility(View.VISIBLE);
205 // Show the file name linear layout if either import or export is checked.
206 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
207 fileNameLinearLayout.setVisibility(View.VISIBLE);
210 // Reset the text of the import button, which may have been changed to `Decrypt`.
211 if (importRadioButton.isChecked()) {
212 importExportButton.setText(R.string.import_button);
215 // Enable the import/export button if the file name is populated.
216 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
219 case PASSWORD_ENCRYPTION:
221 // Show the KitKat password encryption message.
222 kitKatPasswordEncryptionTextView.setVisibility(View.VISIBLE);
224 // Hide the OpenPGP required text view and the file location card.
225 openKeychainRequiredTextView.setVisibility(View.GONE);
226 fileLocationCardView.setVisibility(View.GONE);
228 // Hide the OpenPGP layout items.
229 openKeychainRequiredTextView.setVisibility(View.GONE);
230 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
232 // Show the password encryption layout items.
233 encryptionPasswordTextInputLayout.setVisibility(View.VISIBLE);
235 // Show the file location card.
236 fileLocationCardView.setVisibility(View.VISIBLE);
238 // Show the file name linear layout if either import or export is checked.
239 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
240 fileNameLinearLayout.setVisibility(View.VISIBLE);
243 // Reset the text of the import button, which may have been changed to `Decrypt`.
244 if (importRadioButton.isChecked()) {
245 importExportButton.setText(R.string.import_button);
248 // Enable the import/button if both the password and the file name are populated.
249 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
253 case OPENPGP_ENCRYPTION:
254 // Hide the password encryption layout items.
255 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
256 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
258 // Updated items based on the installation status of OpenKeychain.
259 if (openKeychainInstalled) { // OpenKeychain is installed.
260 // Show the file location card.
261 fileLocationCardView.setVisibility(View.VISIBLE);
263 if (importRadioButton.isChecked()) {
264 // Show the file name linear layout and the OpenKeychain import instructions.
265 fileNameLinearLayout.setVisibility(View.VISIBLE);
266 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
268 // Set the text of the import button to be `Decrypt`.
269 importExportButton.setText(R.string.decrypt);
271 // Enable the import button if the file name is populated.
272 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
273 } else if (exportRadioButton.isChecked()) {
274 // Hide the file name linear layout and the OpenKeychain import instructions.
275 fileNameLinearLayout.setVisibility(View.GONE);
276 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
278 // Enable the export button.
279 importExportButton.setEnabled(true);
281 } else { // OpenKeychain is not installed.
282 // Show the OpenPGP required layout item.
283 openKeychainRequiredTextView.setVisibility(View.VISIBLE);
285 // Hide the file location card.
286 fileLocationCardView.setVisibility(View.GONE);
293 public void onNothingSelected(AdapterView<?> parent) {
298 // Update the status of the import/export button when the password changes.
299 encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
301 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
306 public void onTextChanged(CharSequence s, int start, int before, int count) {
311 public void afterTextChanged(Editable s) {
312 // Enable the import/export button if both the file string and the password are populated.
313 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
317 // Update the UI when the file name EditText changes.
318 fileNameEditText.addTextChangedListener(new TextWatcher() {
320 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
325 public void onTextChanged(CharSequence s, int start, int before, int count) {
330 public void afterTextChanged(Editable s) {
331 // Adjust the UI according to the encryption spinner position.
332 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) {
333 // Enable the import/export button if both the file name and the password are populated.
334 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
336 // Enable the export button if the file name is populated.
337 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
342 // Check to see if the activity has been restarted.
343 if (savedInstanceState == null) { // The app has not been restarted.
344 // Initially hide the unneeded views.
345 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
346 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
347 openKeychainRequiredTextView.setVisibility(View.GONE);
348 fileNameLinearLayout.setVisibility(View.GONE);
349 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
350 importExportButton.setVisibility(View.GONE);
351 } else { // The app has been restarted.
352 // Restore the visibility of the views.
353 encryptionPasswordTextInputLayout.setVisibility(savedInstanceState.getInt(ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY));
354 kitKatPasswordEncryptionTextView.setVisibility(savedInstanceState.getInt(KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY));
355 openKeychainRequiredTextView.setVisibility(savedInstanceState.getInt(OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY));
356 fileLocationCardView.setVisibility(savedInstanceState.getInt(FILE_LOCATION_CARD_VIEW));
357 fileNameLinearLayout.setVisibility(savedInstanceState.getInt(FILE_NAME_LINEARLAYOUT_VISIBILITY));
358 openKeychainImportInstructionsTextView.setVisibility(savedInstanceState.getInt(OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY));
359 importExportButton.setVisibility(savedInstanceState.getInt(IMPORT_EXPORT_BUTTON_VISIBILITY));
362 fileNameEditText.post(() -> fileNameEditText.setText(savedInstanceState.getString(FILE_NAME_TEXT)));
363 importExportButton.setText(savedInstanceState.getString(IMPORT_EXPORT_BUTTON_TEXT));
368 public void onSaveInstanceState (@NonNull Bundle savedInstanceState) {
369 // Run the default commands.
370 super.onSaveInstanceState(savedInstanceState);
372 // Save the visibility of the views.
373 savedInstanceState.putInt(ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY, encryptionPasswordTextInputLayout.getVisibility());
374 savedInstanceState.putInt(KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY, kitKatPasswordEncryptionTextView.getVisibility());
375 savedInstanceState.putInt(OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY, openKeychainRequiredTextView.getVisibility());
376 savedInstanceState.putInt(FILE_LOCATION_CARD_VIEW, fileLocationCardView.getVisibility());
377 savedInstanceState.putInt(FILE_NAME_LINEARLAYOUT_VISIBILITY, fileNameLinearLayout.getVisibility());
378 savedInstanceState.putInt(OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY, openKeychainImportInstructionsTextView.getVisibility());
379 savedInstanceState.putInt(IMPORT_EXPORT_BUTTON_VISIBILITY, importExportButton.getVisibility());
382 savedInstanceState.putString(FILE_NAME_TEXT, fileNameEditText.getText().toString());
383 savedInstanceState.putString(IMPORT_EXPORT_BUTTON_TEXT, importExportButton.getText().toString());
386 public void onClickRadioButton(View view) {
387 // Get the current file name.
388 String fileNameString = fileNameEditText.getText().toString();
390 // Convert the file name string to a file.
391 File file = new File(fileNameString);
393 // Check to see if import or export was selected.
394 if (view.getId() == R.id.import_radiobutton) { // The import radio button is selected.
395 // Check to see if OpenPGP encryption is selected.
396 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption selected.
397 // Show the OpenKeychain import instructions.
398 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
400 // Set the text on the import/export button to be `Decrypt`.
401 importExportButton.setText(R.string.decrypt);
402 } else { // OpenPGP encryption not selected.
403 // Hide the OpenKeychain import instructions.
404 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
406 // Set the text on the import/export button to be `Import`.
407 importExportButton.setText(R.string.import_button);
410 // Display the file name views.
411 fileNameLinearLayout.setVisibility(View.VISIBLE);
412 importExportButton.setVisibility(View.VISIBLE);
414 // Check to see if the file exists.
415 if (file.exists()) { // The file exists.
416 // Check to see if password encryption is selected.
417 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) { // Password encryption is selected.
418 // Enable the import button if the encryption password is populated.
419 importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
420 } else { // Password encryption is not selected.
421 // Enable the import/decrypt button.
422 importExportButton.setEnabled(true);
424 } else { // The file does not exist.
425 // Disable the import/decrypt button.
426 importExportButton.setEnabled(false);
428 } else { // The export radio button is selected.
429 // Hide the OpenKeychain import instructions.
430 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
432 // Set the text on the import/export button to be `Export`.
433 importExportButton.setText(R.string.export);
435 // Show the import/export button.
436 importExportButton.setVisibility(View.VISIBLE);
438 // Check to see if OpenPGP encryption is selected.
439 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption is selected.
440 // Hide the file name views.
441 fileNameLinearLayout.setVisibility(View.GONE);
443 // Enable the export button.
444 importExportButton.setEnabled(true);
445 } else { // OpenPGP encryption is not selected.
446 // Show the file name view.
447 fileNameLinearLayout.setVisibility(View.VISIBLE);
449 // Check the encryption type.
450 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
451 // Enable the export button if the file name is populated.
452 importExportButton.setEnabled(!fileNameString.isEmpty());
453 } else { // Password encryption is selected.
454 // Enable the export button if the file name and the password are populated.
455 importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
461 public void browse(View view) {
462 // Check to see if import or export is selected.
463 if (importRadioButton.isChecked()) { // Import is selected.
464 // Create the file picker intent.
465 Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
467 // Set the intent MIME type to include all files so that everything is visible.
468 importBrowseIntent.setType("*/*");
470 // Request a file that can be opened.
471 importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
473 // Launch the file picker.
474 startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
475 } else { // Export is selected
476 // Create the file picker intent.
477 Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
479 // Set the intent MIME type to include all files so that everything is visible.
480 exportBrowseIntent.setType("*/*");
482 // Set the initial export file name according to the encryption type.
483 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
484 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
485 } else { // Password encryption is selected.
486 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs.aes");
489 // Request a file that can be opened.
490 exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
492 // Launch the file picker.
493 startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
498 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
499 // Run the default commands.
500 super.onActivityResult(requestCode, resultCode, returnedIntent);
502 switch (requestCode) {
503 case (BROWSE_RESULT_CODE):
504 // Only do something if the user didn't press back from the file picker.
505 if (resultCode == Activity.RESULT_OK) {
506 // Get the file path URI from the intent.
507 Uri fileNameUri = returnedIntent.getData();
509 // Get the file name string from the URI.
510 String fileNameString = fileNameUri.toString();
512 // Set the file name name text.
513 fileNameEditText.setText(fileNameString);
515 // Move the cursor to the end of the file name edit text.
516 fileNameEditText.setSelection(fileNameString.length());
520 case OPENPGP_IMPORT_RESULT_CODE:
521 // Delete the temporary PGP encrypted import file.
522 if (temporaryPgpEncryptedImportFile.exists()) {
523 //noinspection ResultOfMethodCallIgnored
524 temporaryPgpEncryptedImportFile.delete();
528 case OPENPGP_EXPORT_RESULT_CODE:
529 // Delete the temporary pre-encrypted export file if it exists.
530 if (temporaryPreEncryptedExportFile.exists()) {
531 //noinspection ResultOfMethodCallIgnored
532 temporaryPreEncryptedExportFile.delete();
538 public void importExport(View view) {
539 // Instantiate the import export database helper.
540 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
542 // Check to see if import or export is selected.
543 if (importRadioButton.isChecked()) { // Import is selected.
544 // Initialize the import status string
545 String importStatus = "";
547 // Get the file name string.
548 String fileNameString = fileNameEditText.getText().toString();
550 // Import according to the encryption type.
551 switch (encryptionSpinner.getSelectedItemPosition()) {
554 // Get an input stream for the file name.
555 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
557 // Import the unencrypted file.
558 importStatus = importExportDatabaseHelper.importUnencrypted(inputStream, this);
559 } catch (FileNotFoundException exception) {
560 // Update the import status.
561 importStatus = exception.toString();
564 // Restart Privacy Browser if successful.
565 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
566 restartPrivacyBrowser();
570 case PASSWORD_ENCRYPTION:
572 // Get the encryption password.
573 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
575 // Get an input stream for the file name.
576 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
578 // Get the salt from the beginning of the import file.
579 byte[] saltByteArray = new byte[32];
580 //noinspection ResultOfMethodCallIgnored
581 inputStream.read(saltByteArray);
583 // Get the initialization vector from the import file.
584 byte[] initializationVector = new byte[12];
585 //noinspection ResultOfMethodCallIgnored
586 inputStream.read(initializationVector);
588 // Convert the encryption password to a byte array.
589 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
591 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
592 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
593 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
594 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
596 // Get a SHA-512 message digest.
597 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
599 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
600 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
602 // Truncate the encryption password byte array to 256 bits (32 bytes).
603 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
605 // Create an AES secret key from the encryption password byte array.
606 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
608 // 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.
609 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
611 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
612 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
614 // Initialize the cipher.
615 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
617 // Create a cipher input stream.
618 CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
620 // 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.
621 int numberOfBytesRead;
622 byte[] decryptedBytes = new byte[16];
625 // Create a private temporary unencrypted import file.
626 File temporaryUnencryptedImportFile = File.createTempFile("temporary_unencrypted_import_file", null, getApplicationContext().getCacheDir());
628 // Create an temporary unencrypted import file output stream.
629 FileOutputStream temporaryUnencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
632 // 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.
633 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
634 // Write the data to the temporary unencrypted import file output stream.
635 temporaryUnencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
639 // Flush the temporary unencrypted import file output stream.
640 temporaryUnencryptedImportFileOutputStream.flush();
642 // Close the streams.
643 temporaryUnencryptedImportFileOutputStream.close();
644 cipherInputStream.close();
647 // Wipe the encryption data from memory.
648 //noinspection UnusedAssignment
649 encryptionPasswordString = "";
650 Arrays.fill(saltByteArray, (byte) 0);
651 Arrays.fill(initializationVector, (byte) 0);
652 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
653 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
654 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
655 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
656 Arrays.fill(decryptedBytes, (byte) 0);
658 // Create a temporary unencrypted import file input stream.
659 FileInputStream temporaryUnencryptedImportFileInputStream = new FileInputStream(temporaryUnencryptedImportFile);
661 // Import the temporary unencrypted import file.
662 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFileInputStream, this);
664 // Close the temporary unencrypted import file input stream.
665 temporaryUnencryptedImportFileInputStream.close();
667 // Delete the temporary unencrypted import file.
668 //noinspection ResultOfMethodCallIgnored
669 temporaryUnencryptedImportFile.delete();
671 // Restart Privacy Browser if successful.
672 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
673 restartPrivacyBrowser();
675 } catch (Exception exception) {
676 // Update the import status.
677 importStatus = exception.toString();
681 case OPENPGP_ENCRYPTION:
683 // Set the temporary PGP encrypted import file.
684 temporaryPgpEncryptedImportFile = File.createTempFile("temporary_pgp_encrypted_import_file", null, getApplicationContext().getCacheDir());
686 // Create a temporary PGP encrypted import file output stream.
687 FileOutputStream temporaryPgpEncryptedImportFileOutputStream = new FileOutputStream(temporaryPgpEncryptedImportFile);
689 // Get an input stream for the file name.
690 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
692 // Create a transfer byte array.
693 byte[] transferByteArray = new byte[1024];
695 // Create an integer to track the number of bytes read.
698 // Copy the input stream to the temporary PGP encrypted import file.
699 while ((bytesRead = inputStream.read(transferByteArray)) > 0) {
700 temporaryPgpEncryptedImportFileOutputStream.write(transferByteArray, 0, bytesRead);
703 // Flush the temporary PGP encrypted import file output stream.
704 temporaryPgpEncryptedImportFileOutputStream.flush();
706 // Close the streams.
708 temporaryPgpEncryptedImportFileOutputStream.close();
710 // Create an decryption intent for OpenKeychain.
711 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
713 // Include the URI to be decrypted.
714 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPgpEncryptedImportFile));
716 // Allow OpenKeychain to read the file URI.
717 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
719 // Send the intent to the OpenKeychain package.
720 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
723 startActivityForResult(openKeychainDecryptIntent, OPENPGP_IMPORT_RESULT_CODE);
725 // Update the import status.
726 importStatus = ImportExportDatabaseHelper.IMPORT_SUCCESSFUL;
727 } catch (Exception exception) {
728 // Update the import status.
729 importStatus = exception.toString();
734 // Respond to the import status.
735 if (!importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
736 // Display a snack bar with the import error.
737 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();
739 } else { // Export is selected.
740 // Export according to the encryption type.
741 switch (encryptionSpinner.getSelectedItemPosition()) {
743 // Get the file name string.
744 String noEncryptionFileNameString = fileNameEditText.getText().toString();
747 // Get the export file output stream.
748 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(noEncryptionFileNameString));
750 // Export the unencrypted file.
751 String noEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(exportFileOutputStream, this);
753 // Display an export disposition snackbar.
754 if (noEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
755 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
757 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + noEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
759 } catch (FileNotFoundException fileNotFoundException) {
760 // Display a snackbar with the exception.
761 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + fileNotFoundException, Snackbar.LENGTH_INDEFINITE).show();
765 case PASSWORD_ENCRYPTION:
767 // Create a temporary unencrypted export file.
768 File temporaryUnencryptedExportFile = File.createTempFile("temporary_unencrypted_export_file", null, getApplicationContext().getCacheDir());
770 // Create a temporary unencrypted export output stream.
771 FileOutputStream temporaryUnencryptedExportOutputStream = new FileOutputStream(temporaryUnencryptedExportFile);
773 // Populate the temporary unencrypted export.
774 String passwordEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportOutputStream, this);
776 // Close the temporary unencrypted export output stream.
777 temporaryUnencryptedExportOutputStream.close();
779 // Create an unencrypted export file input stream.
780 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
782 // Get the encryption password.
783 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
785 // Initialize a secure random number generator.
786 SecureRandom secureRandom = new SecureRandom();
788 // Get a 256 bit (32 byte) random salt.
789 byte[] saltByteArray = new byte[32];
790 secureRandom.nextBytes(saltByteArray);
792 // Convert the encryption password to a byte array.
793 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
795 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
796 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
797 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
798 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
800 // Get a SHA-512 message digest.
801 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
803 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
804 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
806 // Truncate the encryption password byte array to 256 bits (32 bytes).
807 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
809 // Create an AES secret key from the encryption password byte array.
810 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
812 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
813 byte[] initializationVector = new byte[12];
814 secureRandom.nextBytes(initializationVector);
816 // 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.
817 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
819 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
820 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
822 // Initialize the cipher.
823 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
825 // Get the file name string.
826 String passwordEncryptionFileNameString = fileNameEditText.getText().toString();
828 // Get the export file output stream.
829 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(passwordEncryptionFileNameString));
831 // Add the salt and the initialization vector to the export file output stream.
832 exportFileOutputStream.write(saltByteArray);
833 exportFileOutputStream.write(initializationVector);
835 // Create a cipher output stream.
836 CipherOutputStream cipherOutputStream = new CipherOutputStream(exportFileOutputStream, cipher);
838 // 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.
839 int numberOfBytesRead;
840 byte[] encryptedBytes = new byte[16];
842 // 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.
843 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
844 // Write the data to the cipher output stream.
845 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
848 // Close the streams.
849 cipherOutputStream.flush();
850 cipherOutputStream.close();
851 exportFileOutputStream.close();
852 unencryptedExportFileInputStream.close();
854 // Wipe the encryption data from memory.
855 //noinspection UnusedAssignment
856 encryptionPasswordString = "";
857 Arrays.fill(saltByteArray, (byte) 0);
858 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
859 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
860 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
861 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
862 Arrays.fill(initializationVector, (byte) 0);
863 Arrays.fill(encryptedBytes, (byte) 0);
865 // Delete the temporary unencrypted export file.
866 //noinspection ResultOfMethodCallIgnored
867 temporaryUnencryptedExportFile.delete();
869 // Display an export disposition snackbar.
870 if (passwordEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
871 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
873 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + passwordEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
875 } catch (Exception exception) {
876 // Display a snackbar with the exception.
877 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
881 case OPENPGP_ENCRYPTION:
883 // Set the temporary pre-encrypted export file.
884 temporaryPreEncryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
886 // Delete the temporary pre-encrypted export file if it already exists.
887 if (temporaryPreEncryptedExportFile.exists()) {
888 //noinspection ResultOfMethodCallIgnored
889 temporaryPreEncryptedExportFile.delete();
892 // Create a temporary pre-encrypted export output stream.
893 FileOutputStream temporaryPreEncryptedExportOutputStream = new FileOutputStream(temporaryPreEncryptedExportFile);
895 // Populate the temporary pre-encrypted export file.
896 String openpgpEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryPreEncryptedExportOutputStream, this);
898 // Flush the temporary pre-encryption export output stream.
899 temporaryPreEncryptedExportOutputStream.flush();
901 // Close the temporary pre-encryption export output stream.
902 temporaryPreEncryptedExportOutputStream.close();
904 // Display an export error snackbar if the temporary pre-encrypted export failed.
905 if (!openpgpEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
906 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + openpgpEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
909 // Create an encryption intent for OpenKeychain.
910 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
912 // Include the temporary unencrypted export file URI.
913 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPreEncryptedExportFile));
915 // Allow OpenKeychain to read the file URI.
916 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
918 // Send the intent to the OpenKeychain package.
919 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
922 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
923 } catch (Exception exception) {
924 // Display a snackbar with the exception.
925 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
932 private void restartPrivacyBrowser() {
933 // Create an intent to restart Privacy Browser.
934 Intent restartIntent = getParentActivityIntent();
936 // Assert that the intent is not null to remove the lint error below.
937 assert restartIntent != null;
939 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
940 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
942 // Create a restart handler.
943 Handler restartHandler = new Handler();
945 // Create a restart runnable.
946 Runnable restartRunnable = () -> {
947 // Restart Privacy Browser.
948 startActivity(restartIntent);
950 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
954 // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
955 restartHandler.postDelayed(restartRunnable, 150);