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 screenshot preference.
121 boolean allowScreenshots = sharedPreferences.getBoolean("allow_screenshots", 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.
135 setContentView(R.layout.import_export_coordinatorlayout);
137 // Set the support action bar.
138 Toolbar toolbar = findViewById(R.id.import_export_toolbar);
139 setSupportActionBar(toolbar);
141 // Get a handle for the action bar.
142 ActionBar actionBar = getSupportActionBar();
144 // Remove the incorrect lint warning that the action bar might be null.
145 assert actionBar != null;
147 // Display the home arrow on the support action bar.
148 actionBar.setDisplayHomeAsUpEnabled(true);
150 // Find out if the system is running KitKat
151 boolean runningKitKat = (Build.VERSION.SDK_INT == 19);
153 // Find out if OpenKeychain is installed.
155 openKeychainInstalled = !getPackageManager().getPackageInfo("org.sufficientlysecure.keychain", 0).versionName.isEmpty();
156 } catch (PackageManager.NameNotFoundException exception) {
157 openKeychainInstalled = false;
160 // Get handles for the views that need to be modified.
161 encryptionSpinner = findViewById(R.id.encryption_spinner);
162 encryptionPasswordTextInputLayout = findViewById(R.id.encryption_password_textinputlayout);
163 encryptionPasswordEditText = findViewById(R.id.encryption_password_edittext);
164 kitKatPasswordEncryptionTextView = findViewById(R.id.kitkat_password_encryption_textview);
165 openKeychainRequiredTextView = findViewById(R.id.openkeychain_required_textview);
166 fileLocationCardView = findViewById(R.id.file_location_cardview);
167 importRadioButton = findViewById(R.id.import_radiobutton);
168 RadioButton exportRadioButton = findViewById(R.id.export_radiobutton);
169 fileNameLinearLayout = findViewById(R.id.file_name_linearlayout);
170 fileNameEditText = findViewById(R.id.file_name_edittext);
171 openKeychainImportInstructionsTextView = findViewById(R.id.openkeychain_import_instructions_textview);
172 importExportButton = findViewById(R.id.import_export_button);
174 // Create an array adapter for the spinner.
175 ArrayAdapter<CharSequence> encryptionArrayAdapter = ArrayAdapter.createFromResource(this, R.array.encryption_type, R.layout.spinner_item);
177 // Set the drop down view resource on the spinner.
178 encryptionArrayAdapter.setDropDownViewResource(R.layout.spinner_dropdown_items);
180 // Set the array adapter for the spinner.
181 encryptionSpinner.setAdapter(encryptionArrayAdapter);
183 // Update the UI when the spinner changes.
184 encryptionSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
186 public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
189 // Hide the unneeded layout items.
190 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
191 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
192 openKeychainRequiredTextView.setVisibility(View.GONE);
193 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
195 // Show the file location card.
196 fileLocationCardView.setVisibility(View.VISIBLE);
198 // Show the file name linear layout if either import or export is checked.
199 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
200 fileNameLinearLayout.setVisibility(View.VISIBLE);
203 // Reset the text of the import button, which may have been changed to `Decrypt`.
204 if (importRadioButton.isChecked()) {
205 importExportButton.setText(R.string.import_button);
208 // Enable the import/export button if the file name is populated.
209 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
212 case PASSWORD_ENCRYPTION:
214 // Show the KitKat password encryption message.
215 kitKatPasswordEncryptionTextView.setVisibility(View.VISIBLE);
217 // Hide the OpenPGP required text view and the file location card.
218 openKeychainRequiredTextView.setVisibility(View.GONE);
219 fileLocationCardView.setVisibility(View.GONE);
221 // Hide the OpenPGP layout items.
222 openKeychainRequiredTextView.setVisibility(View.GONE);
223 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
225 // Show the password encryption layout items.
226 encryptionPasswordTextInputLayout.setVisibility(View.VISIBLE);
228 // Show the file location card.
229 fileLocationCardView.setVisibility(View.VISIBLE);
231 // Show the file name linear layout if either import or export is checked.
232 if (importRadioButton.isChecked() || exportRadioButton.isChecked()) {
233 fileNameLinearLayout.setVisibility(View.VISIBLE);
236 // Reset the text of the import button, which may have been changed to `Decrypt`.
237 if (importRadioButton.isChecked()) {
238 importExportButton.setText(R.string.import_button);
241 // Enable the import/button if both the password and the file name are populated.
242 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
246 case OPENPGP_ENCRYPTION:
247 // Hide the password encryption layout items.
248 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
249 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
251 // Updated items based on the installation status of OpenKeychain.
252 if (openKeychainInstalled) { // OpenKeychain is installed.
253 // Show the file location card.
254 fileLocationCardView.setVisibility(View.VISIBLE);
256 if (importRadioButton.isChecked()) {
257 // Show the file name linear layout and the OpenKeychain import instructions.
258 fileNameLinearLayout.setVisibility(View.VISIBLE);
259 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
261 // Set the text of the import button to be `Decrypt`.
262 importExportButton.setText(R.string.decrypt);
264 // Enable the import button if the file name is populated.
265 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
266 } else if (exportRadioButton.isChecked()) {
267 // Hide the file name linear layout and the OpenKeychain import instructions.
268 fileNameLinearLayout.setVisibility(View.GONE);
269 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
271 // Enable the export button.
272 importExportButton.setEnabled(true);
274 } else { // OpenKeychain is not installed.
275 // Show the OpenPGP required layout item.
276 openKeychainRequiredTextView.setVisibility(View.VISIBLE);
278 // Hide the file location card.
279 fileLocationCardView.setVisibility(View.GONE);
286 public void onNothingSelected(AdapterView<?> parent) {
291 // Update the status of the import/export button when the password changes.
292 encryptionPasswordEditText.addTextChangedListener(new TextWatcher() {
294 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
299 public void onTextChanged(CharSequence s, int start, int before, int count) {
304 public void afterTextChanged(Editable s) {
305 // Enable the import/export button if both the file string and the password are populated.
306 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
310 // Update the UI when the file name EditText changes.
311 fileNameEditText.addTextChangedListener(new TextWatcher() {
313 public void beforeTextChanged(CharSequence s, int start, int count, int after) {
318 public void onTextChanged(CharSequence s, int start, int before, int count) {
323 public void afterTextChanged(Editable s) {
324 // Adjust the UI according to the encryption spinner position.
325 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) {
326 // Enable the import/export button if both the file name and the password are populated.
327 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
329 // Enable the export button if the file name is populated.
330 importExportButton.setEnabled(!fileNameEditText.getText().toString().isEmpty());
335 // Check to see if the activity has been restarted.
336 if (savedInstanceState == null) { // The app has not been restarted.
337 // Initially hide the unneeded views.
338 encryptionPasswordTextInputLayout.setVisibility(View.GONE);
339 kitKatPasswordEncryptionTextView.setVisibility(View.GONE);
340 openKeychainRequiredTextView.setVisibility(View.GONE);
341 fileNameLinearLayout.setVisibility(View.GONE);
342 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
343 importExportButton.setVisibility(View.GONE);
344 } else { // The app has been restarted.
345 // Restore the visibility of the views.
346 encryptionPasswordTextInputLayout.setVisibility(savedInstanceState.getInt(ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY));
347 kitKatPasswordEncryptionTextView.setVisibility(savedInstanceState.getInt(KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY));
348 openKeychainRequiredTextView.setVisibility(savedInstanceState.getInt(OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY));
349 fileLocationCardView.setVisibility(savedInstanceState.getInt(FILE_LOCATION_CARD_VIEW));
350 fileNameLinearLayout.setVisibility(savedInstanceState.getInt(FILE_NAME_LINEARLAYOUT_VISIBILITY));
351 openKeychainImportInstructionsTextView.setVisibility(savedInstanceState.getInt(OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY));
352 importExportButton.setVisibility(savedInstanceState.getInt(IMPORT_EXPORT_BUTTON_VISIBILITY));
355 fileNameEditText.post(() -> fileNameEditText.setText(savedInstanceState.getString(FILE_NAME_TEXT)));
356 importExportButton.setText(savedInstanceState.getString(IMPORT_EXPORT_BUTTON_TEXT));
361 public void onSaveInstanceState (@NonNull Bundle savedInstanceState) {
362 // Run the default commands.
363 super.onSaveInstanceState(savedInstanceState);
365 // Save the visibility of the views.
366 savedInstanceState.putInt(ENCRYPTION_PASSWORD_TEXTINPUTLAYOUT_VISIBILITY, encryptionPasswordTextInputLayout.getVisibility());
367 savedInstanceState.putInt(KITKAT_PASSWORD_ENCRYPTED_TEXTVIEW_VISIBILITY, kitKatPasswordEncryptionTextView.getVisibility());
368 savedInstanceState.putInt(OPEN_KEYCHAIN_REQUIRED_TEXTVIEW_VISIBILITY, openKeychainRequiredTextView.getVisibility());
369 savedInstanceState.putInt(FILE_LOCATION_CARD_VIEW, fileLocationCardView.getVisibility());
370 savedInstanceState.putInt(FILE_NAME_LINEARLAYOUT_VISIBILITY, fileNameLinearLayout.getVisibility());
371 savedInstanceState.putInt(OPEN_KEYCHAIN_IMPORT_INSTRUCTIONS_TEXTVIEW_VISIBILITY, openKeychainImportInstructionsTextView.getVisibility());
372 savedInstanceState.putInt(IMPORT_EXPORT_BUTTON_VISIBILITY, importExportButton.getVisibility());
375 savedInstanceState.putString(FILE_NAME_TEXT, fileNameEditText.getText().toString());
376 savedInstanceState.putString(IMPORT_EXPORT_BUTTON_TEXT, importExportButton.getText().toString());
379 public void onClickRadioButton(View view) {
380 // Get the current file name.
381 String fileNameString = fileNameEditText.getText().toString();
383 // Convert the file name string to a file.
384 File file = new File(fileNameString);
386 // Check to see if import or export was selected.
387 if (view.getId() == R.id.import_radiobutton) { // The import radio button is selected.
388 // Check to see if OpenPGP encryption is selected.
389 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption selected.
390 // Show the OpenKeychain import instructions.
391 openKeychainImportInstructionsTextView.setVisibility(View.VISIBLE);
393 // Set the text on the import/export button to be `Decrypt`.
394 importExportButton.setText(R.string.decrypt);
395 } else { // OpenPGP encryption not selected.
396 // Hide the OpenKeychain import instructions.
397 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
399 // Set the text on the import/export button to be `Import`.
400 importExportButton.setText(R.string.import_button);
403 // Display the file name views.
404 fileNameLinearLayout.setVisibility(View.VISIBLE);
405 importExportButton.setVisibility(View.VISIBLE);
407 // Check to see if the file exists.
408 if (file.exists()) { // The file exists.
409 // Check to see if password encryption is selected.
410 if (encryptionSpinner.getSelectedItemPosition() == PASSWORD_ENCRYPTION) { // Password encryption is selected.
411 // Enable the import button if the encryption password is populated.
412 importExportButton.setEnabled(!encryptionPasswordEditText.getText().toString().isEmpty());
413 } else { // Password encryption is not selected.
414 // Enable the import/decrypt button.
415 importExportButton.setEnabled(true);
417 } else { // The file does not exist.
418 // Disable the import/decrypt button.
419 importExportButton.setEnabled(false);
421 } else { // The export radio button is selected.
422 // Hide the OpenKeychain import instructions.
423 openKeychainImportInstructionsTextView.setVisibility(View.GONE);
425 // Set the text on the import/export button to be `Export`.
426 importExportButton.setText(R.string.export);
428 // Show the import/export button.
429 importExportButton.setVisibility(View.VISIBLE);
431 // Check to see if OpenPGP encryption is selected.
432 if (encryptionSpinner.getSelectedItemPosition() == OPENPGP_ENCRYPTION) { // OpenPGP encryption is selected.
433 // Hide the file name views.
434 fileNameLinearLayout.setVisibility(View.GONE);
436 // Enable the export button.
437 importExportButton.setEnabled(true);
438 } else { // OpenPGP encryption is not selected.
439 // Show the file name view.
440 fileNameLinearLayout.setVisibility(View.VISIBLE);
442 // Check the encryption type.
443 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
444 // Enable the export button if the file name is populated.
445 importExportButton.setEnabled(!fileNameString.isEmpty());
446 } else { // Password encryption is selected.
447 // Enable the export button if the file name and the password are populated.
448 importExportButton.setEnabled(!fileNameString.isEmpty() && !encryptionPasswordEditText.getText().toString().isEmpty());
454 public void browse(View view) {
455 // Check to see if import or export is selected.
456 if (importRadioButton.isChecked()) { // Import is selected.
457 // Create the file picker intent.
458 Intent importBrowseIntent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
460 // Set the intent MIME type to include all files so that everything is visible.
461 importBrowseIntent.setType("*/*");
463 // Request a file that can be opened.
464 importBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
466 // Launch the file picker.
467 startActivityForResult(importBrowseIntent, BROWSE_RESULT_CODE);
468 } else { // Export is selected
469 // Create the file picker intent.
470 Intent exportBrowseIntent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
472 // Set the intent MIME type to include all files so that everything is visible.
473 exportBrowseIntent.setType("*/*");
475 // Set the initial export file name according to the encryption type.
476 if (encryptionSpinner.getSelectedItemPosition() == NO_ENCRYPTION) { // No encryption is selected.
477 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
478 } else { // Password encryption is selected.
479 exportBrowseIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs.aes");
482 // Request a file that can be opened.
483 exportBrowseIntent.addCategory(Intent.CATEGORY_OPENABLE);
485 // Launch the file picker.
486 startActivityForResult(exportBrowseIntent, BROWSE_RESULT_CODE);
491 public void onActivityResult(int requestCode, int resultCode, Intent returnedIntent) {
492 // Run the default commands.
493 super.onActivityResult(requestCode, resultCode, returnedIntent);
495 switch (requestCode) {
496 case (BROWSE_RESULT_CODE):
497 // Only do something if the user didn't press back from the file picker.
498 if (resultCode == Activity.RESULT_OK) {
499 // Get the file path URI from the intent.
500 Uri fileNameUri = returnedIntent.getData();
502 // Get the file name string from the URI.
503 String fileNameString = fileNameUri.toString();
505 // Set the file name name text.
506 fileNameEditText.setText(fileNameString);
508 // Move the cursor to the end of the file name edit text.
509 fileNameEditText.setSelection(fileNameString.length());
513 case OPENPGP_IMPORT_RESULT_CODE:
514 // Delete the temporary PGP encrypted import file.
515 if (temporaryPgpEncryptedImportFile.exists()) {
516 //noinspection ResultOfMethodCallIgnored
517 temporaryPgpEncryptedImportFile.delete();
521 case OPENPGP_EXPORT_RESULT_CODE:
522 // Delete the temporary pre-encrypted export file if it exists.
523 if (temporaryPreEncryptedExportFile.exists()) {
524 //noinspection ResultOfMethodCallIgnored
525 temporaryPreEncryptedExportFile.delete();
531 public void importExport(View view) {
532 // Instantiate the import export database helper.
533 ImportExportDatabaseHelper importExportDatabaseHelper = new ImportExportDatabaseHelper();
535 // Check to see if import or export is selected.
536 if (importRadioButton.isChecked()) { // Import is selected.
537 // Initialize the import status string
538 String importStatus = "";
540 // Get the file name string.
541 String fileNameString = fileNameEditText.getText().toString();
543 // Import according to the encryption type.
544 switch (encryptionSpinner.getSelectedItemPosition()) {
547 // Get an input stream for the file name.
548 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
550 // Import the unencrypted file.
551 importStatus = importExportDatabaseHelper.importUnencrypted(inputStream, this);
552 } catch (FileNotFoundException exception) {
553 // Update the import status.
554 importStatus = exception.toString();
557 // Restart Privacy Browser if successful.
558 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
559 restartPrivacyBrowser();
563 case PASSWORD_ENCRYPTION:
565 // Get the encryption password.
566 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
568 // Get an input stream for the file name.
569 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
571 // Get the salt from the beginning of the import file.
572 byte[] saltByteArray = new byte[32];
573 //noinspection ResultOfMethodCallIgnored
574 inputStream.read(saltByteArray);
576 // Get the initialization vector from the import file.
577 byte[] initializationVector = new byte[12];
578 //noinspection ResultOfMethodCallIgnored
579 inputStream.read(initializationVector);
581 // Convert the encryption password to a byte array.
582 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
584 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
585 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
586 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
587 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
589 // Get a SHA-512 message digest.
590 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
592 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
593 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
595 // Truncate the encryption password byte array to 256 bits (32 bytes).
596 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
598 // Create an AES secret key from the encryption password byte array.
599 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
601 // 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.
602 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
604 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
605 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
607 // Initialize the cipher.
608 cipher.init(Cipher.DECRYPT_MODE, secretKey, gcmParameterSpec);
610 // Create a cipher input stream.
611 CipherInputStream cipherInputStream = new CipherInputStream(inputStream, cipher);
613 // 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.
614 int numberOfBytesRead;
615 byte[] decryptedBytes = new byte[16];
618 // Create a private temporary unencrypted import file.
619 File temporaryUnencryptedImportFile = File.createTempFile("temporary_unencrypted_import_file", null, getApplicationContext().getCacheDir());
621 // Create an temporary unencrypted import file output stream.
622 FileOutputStream temporaryUnencryptedImportFileOutputStream = new FileOutputStream(temporaryUnencryptedImportFile);
625 // 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.
626 while ((numberOfBytesRead = cipherInputStream.read(decryptedBytes)) != -1) {
627 // Write the data to the temporary unencrypted import file output stream.
628 temporaryUnencryptedImportFileOutputStream.write(decryptedBytes, 0, numberOfBytesRead);
632 // Flush the temporary unencrypted import file output stream.
633 temporaryUnencryptedImportFileOutputStream.flush();
635 // Close the streams.
636 temporaryUnencryptedImportFileOutputStream.close();
637 cipherInputStream.close();
640 // Wipe the encryption data from memory.
641 //noinspection UnusedAssignment
642 encryptionPasswordString = "";
643 Arrays.fill(saltByteArray, (byte) 0);
644 Arrays.fill(initializationVector, (byte) 0);
645 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
646 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
647 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
648 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
649 Arrays.fill(decryptedBytes, (byte) 0);
651 // Create a temporary unencrypted import file input stream.
652 FileInputStream temporaryUnencryptedImportFileInputStream = new FileInputStream(temporaryUnencryptedImportFile);
654 // Import the temporary unencrypted import file.
655 importStatus = importExportDatabaseHelper.importUnencrypted(temporaryUnencryptedImportFileInputStream, this);
657 // Close the temporary unencrypted import file input stream.
658 temporaryUnencryptedImportFileInputStream.close();
660 // Delete the temporary unencrypted import file.
661 //noinspection ResultOfMethodCallIgnored
662 temporaryUnencryptedImportFile.delete();
664 // Restart Privacy Browser if successful.
665 if (importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
666 restartPrivacyBrowser();
668 } catch (Exception exception) {
669 // Update the import status.
670 importStatus = exception.toString();
674 case OPENPGP_ENCRYPTION:
676 // Set the temporary PGP encrypted import file.
677 temporaryPgpEncryptedImportFile = File.createTempFile("temporary_pgp_encrypted_import_file", null, getApplicationContext().getCacheDir());
679 // Create a temporary PGP encrypted import file output stream.
680 FileOutputStream temporaryPgpEncryptedImportFileOutputStream = new FileOutputStream(temporaryPgpEncryptedImportFile);
682 // Get an input stream for the file name.
683 InputStream inputStream = getContentResolver().openInputStream(Uri.parse(fileNameString));
685 // Create a transfer byte array.
686 byte[] transferByteArray = new byte[1024];
688 // Create an integer to track the number of bytes read.
691 // Copy the input stream to the temporary PGP encrypted import file.
692 while ((bytesRead = inputStream.read(transferByteArray)) > 0) {
693 temporaryPgpEncryptedImportFileOutputStream.write(transferByteArray, 0, bytesRead);
696 // Flush the temporary PGP encrypted import file output stream.
697 temporaryPgpEncryptedImportFileOutputStream.flush();
699 // Close the streams.
701 temporaryPgpEncryptedImportFileOutputStream.flush();
704 // Create an decryption intent for OpenKeychain.
705 Intent openKeychainDecryptIntent = new Intent("org.sufficientlysecure.keychain.action.DECRYPT_DATA");
707 // Include the URI to be decrypted.
708 openKeychainDecryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPgpEncryptedImportFile));
710 // Allow OpenKeychain to read the file URI.
711 openKeychainDecryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
713 // Send the intent to the OpenKeychain package.
714 openKeychainDecryptIntent.setPackage("org.sufficientlysecure.keychain");
717 startActivityForResult(openKeychainDecryptIntent, OPENPGP_IMPORT_RESULT_CODE);
719 // Update the import status.
720 importStatus = ImportExportDatabaseHelper.IMPORT_SUCCESSFUL;
721 } catch (Exception exception) {
722 // Update the import status.
723 importStatus = exception.toString();
728 // Respond to the import status.
729 if (!importStatus.equals(ImportExportDatabaseHelper.IMPORT_SUCCESSFUL)) {
730 // Display a snack bar with the import error.
731 Snackbar.make(fileNameEditText, getString(R.string.import_failed) + " " + importStatus, Snackbar.LENGTH_INDEFINITE).show();
733 } else { // Export is selected.
734 // Export according to the encryption type.
735 switch (encryptionSpinner.getSelectedItemPosition()) {
737 // Get the file name string.
738 String noEncryptionFileNameString = fileNameEditText.getText().toString();
741 // Get the export file output stream.
742 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(noEncryptionFileNameString));
744 // Export the unencrypted file.
745 String noEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(exportFileOutputStream, this);
747 // Display an export disposition snackbar.
748 if (noEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
749 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
751 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + noEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
753 } catch (FileNotFoundException fileNotFoundException) {
754 // Display a snackbar with the exception.
755 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + fileNotFoundException, Snackbar.LENGTH_INDEFINITE).show();
759 case PASSWORD_ENCRYPTION:
761 // Create a temporary unencrypted export file.
762 File temporaryUnencryptedExportFile = File.createTempFile("temporary_unencrypted_export_file", null, getApplicationContext().getCacheDir());
764 // Create a temporary unencrypted export output stream.
765 FileOutputStream temporaryUnencryptedExportOutputStream = new FileOutputStream(temporaryUnencryptedExportFile);
767 // Populate the temporary unencrypted export.
768 String passwordEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryUnencryptedExportOutputStream, this);
770 // Close the temporary unencrypted export output stream.
771 temporaryUnencryptedExportOutputStream.close();
773 // Create an unencrypted export file input stream.
774 FileInputStream unencryptedExportFileInputStream = new FileInputStream(temporaryUnencryptedExportFile);
776 // Get the encryption password.
777 String encryptionPasswordString = encryptionPasswordEditText.getText().toString();
779 // Initialize a secure random number generator.
780 SecureRandom secureRandom = new SecureRandom();
782 // Get a 256 bit (32 byte) random salt.
783 byte[] saltByteArray = new byte[32];
784 secureRandom.nextBytes(saltByteArray);
786 // Convert the encryption password to a byte array.
787 byte[] encryptionPasswordByteArray = encryptionPasswordString.getBytes(StandardCharsets.UTF_8);
789 // Append the salt to the encryption password byte array. This protects against rainbow table attacks.
790 byte[] encryptionPasswordWithSaltByteArray = new byte[encryptionPasswordByteArray.length + saltByteArray.length];
791 System.arraycopy(encryptionPasswordByteArray, 0, encryptionPasswordWithSaltByteArray, 0, encryptionPasswordByteArray.length);
792 System.arraycopy(saltByteArray, 0, encryptionPasswordWithSaltByteArray, encryptionPasswordByteArray.length, saltByteArray.length);
794 // Get a SHA-512 message digest.
795 MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
797 // Hash the salted encryption password. Otherwise, any characters after the 32nd character in the password are ignored.
798 byte[] hashedEncryptionPasswordWithSaltByteArray = messageDigest.digest(encryptionPasswordWithSaltByteArray);
800 // Truncate the encryption password byte array to 256 bits (32 bytes).
801 byte[] truncatedHashedEncryptionPasswordWithSaltByteArray = Arrays.copyOf(hashedEncryptionPasswordWithSaltByteArray, 32);
803 // Create an AES secret key from the encryption password byte array.
804 SecretKeySpec secretKey = new SecretKeySpec(truncatedHashedEncryptionPasswordWithSaltByteArray, "AES");
806 // Generate a random 12 byte initialization vector. According to NIST, a 12 byte initialization vector is more secure than a 16 byte one.
807 byte[] initializationVector = new byte[12];
808 secureRandom.nextBytes(initializationVector);
810 // 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.
811 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
813 // Set the GCM tag length to be 128 bits (the maximum) and apply the initialization vector.
814 GCMParameterSpec gcmParameterSpec = new GCMParameterSpec(128, initializationVector);
816 // Initialize the cipher.
817 cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmParameterSpec);
819 // Get the file name string.
820 String passwordEncryptionFileNameString = fileNameEditText.getText().toString();
822 // Get the export file output stream.
823 OutputStream exportFileOutputStream = getContentResolver().openOutputStream(Uri.parse(passwordEncryptionFileNameString));
825 // Add the salt and the initialization vector to the export file output stream.
826 exportFileOutputStream.write(saltByteArray);
827 exportFileOutputStream.write(initializationVector);
829 // Create a cipher output stream.
830 CipherOutputStream cipherOutputStream = new CipherOutputStream(exportFileOutputStream, cipher);
832 // 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.
833 int numberOfBytesRead;
834 byte[] encryptedBytes = new byte[16];
836 // 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.
837 while ((numberOfBytesRead = unencryptedExportFileInputStream.read(encryptedBytes)) != -1) {
838 // Write the data to the cipher output stream.
839 cipherOutputStream.write(encryptedBytes, 0, numberOfBytesRead);
842 // Close the streams.
843 cipherOutputStream.flush();
844 cipherOutputStream.close();
845 exportFileOutputStream.close();
846 unencryptedExportFileInputStream.close();
848 // Wipe the encryption data from memory.
849 //noinspection UnusedAssignment
850 encryptionPasswordString = "";
851 Arrays.fill(saltByteArray, (byte) 0);
852 Arrays.fill(encryptionPasswordByteArray, (byte) 0);
853 Arrays.fill(encryptionPasswordWithSaltByteArray, (byte) 0);
854 Arrays.fill(hashedEncryptionPasswordWithSaltByteArray, (byte) 0);
855 Arrays.fill(truncatedHashedEncryptionPasswordWithSaltByteArray, (byte) 0);
856 Arrays.fill(initializationVector, (byte) 0);
857 Arrays.fill(encryptedBytes, (byte) 0);
859 // Delete the temporary unencrypted export file.
860 //noinspection ResultOfMethodCallIgnored
861 temporaryUnencryptedExportFile.delete();
863 // Display an export disposition snackbar.
864 if (passwordEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
865 Snackbar.make(fileNameEditText, getString(R.string.export_successful), Snackbar.LENGTH_SHORT).show();
867 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + passwordEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
869 } catch (Exception exception) {
870 // Display a snackbar with the exception.
871 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
875 case OPENPGP_ENCRYPTION:
877 // Set the temporary pre-encrypted export file.
878 temporaryPreEncryptedExportFile = new File(getApplicationContext().getCacheDir() + "/" + getString(R.string.settings) + " " + BuildConfig.VERSION_NAME + ".pbs");
880 // Delete the temporary pre-encrypted export file if it already exists.
881 if (temporaryPreEncryptedExportFile.exists()) {
882 //noinspection ResultOfMethodCallIgnored
883 temporaryPreEncryptedExportFile.delete();
886 // Create a temporary pre-encrypted export output stream.
887 FileOutputStream temporaryPreEncryptedExportOutputStream = new FileOutputStream(temporaryPreEncryptedExportFile);
889 // Populate the temporary pre-encrypted export file.
890 String openpgpEncryptionExportStatus = importExportDatabaseHelper.exportUnencrypted(temporaryPreEncryptedExportOutputStream, this);
892 // Flush the temporary pre-encryption export output stream.
893 temporaryPreEncryptedExportOutputStream.flush();
895 // Close the temporary pre-encryption export output stream.
896 temporaryPreEncryptedExportOutputStream.close();
898 // Display an export error snackbar if the temporary pre-encrypted export failed.
899 if (!openpgpEncryptionExportStatus.equals(ImportExportDatabaseHelper.EXPORT_SUCCESSFUL)) {
900 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + openpgpEncryptionExportStatus, Snackbar.LENGTH_INDEFINITE).show();
903 // Create an encryption intent for OpenKeychain.
904 Intent openKeychainEncryptIntent = new Intent("org.sufficientlysecure.keychain.action.ENCRYPT_DATA");
906 // Include the temporary unencrypted export file URI.
907 openKeychainEncryptIntent.setData(FileProvider.getUriForFile(this, getString(R.string.file_provider), temporaryPreEncryptedExportFile));
909 // Allow OpenKeychain to read the file URI.
910 openKeychainEncryptIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
912 // Send the intent to the OpenKeychain package.
913 openKeychainEncryptIntent.setPackage("org.sufficientlysecure.keychain");
916 startActivityForResult(openKeychainEncryptIntent, OPENPGP_EXPORT_RESULT_CODE);
917 } catch (Exception exception) {
918 // Display a snackbar with the exception.
919 Snackbar.make(fileNameEditText, getString(R.string.export_failed) + " " + exception, Snackbar.LENGTH_INDEFINITE).show();
926 private void restartPrivacyBrowser() {
927 // Create an intent to restart Privacy Browser.
928 Intent restartIntent = getParentActivityIntent();
930 // Assert that the intent is not null to remove the lint error below.
931 assert restartIntent != null;
933 // `Intent.FLAG_ACTIVITY_CLEAR_TASK` removes all activities from the stack. It requires `Intent.FLAG_ACTIVITY_NEW_TASK`.
934 restartIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
936 // Create a restart handler.
937 Handler restartHandler = new Handler();
939 // Create a restart runnable.
940 Runnable restartRunnable = () -> {
941 // Restart Privacy Browser.
942 startActivity(restartIntent);
944 // Kill this instance of Privacy Browser. Otherwise, the app exhibits sporadic behavior after the restart.
948 // Restart Privacy Browser after 150 milliseconds to allow enough time for the preferences to be saved.
949 restartHandler.postDelayed(restartRunnable, 150);