diff --git a/app/build.gradle b/app/build.gradle index 7e66b65bc..b5afe4c87 100644 --- a/app/build.gradle +++ b/app/build.gradle @@ -1,13 +1,13 @@ apply plugin: 'com.android.application' android { - compileSdkVersion = 22 + compileSdkVersion = 23 buildToolsVersion = "25.0.0" defaultConfig { applicationId = "com.android.keepass" minSdkVersion = 3 - targetSdkVersion = 12 + targetSdkVersion 23 versionCode = 154 versionName = "2.0.6.4" diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index 639d195c3..bfa80725b 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -8,6 +8,7 @@ android:largeScreens="true" android:anyDensity="true" /> + = Build.VERSION_CODES.M) { + fingerPrintHelper = new FingerPrintHelper(this, this); + fingerprintView = findViewById(R.id.fingerprint); + confirmationView = (TextView) findViewById(R.id.fingerprint_label); + passwordView = (EditText) findViewById(R.id.password); + + // when text entered we can enable the logon/purchase button and if required update encryption/decryption mode + passwordView.addTextChangedListener(new TextWatcher() { + @Override + public void beforeTextChanged( + final CharSequence s, + final int start, + final int count, + final int after) { + + } + + @Override + public void onTextChanged( + final CharSequence s, + final int start, + final int before, + final int count) { + + } + + @Override + public void afterTextChanged(final Editable s) { + final boolean validInput = s.length() > 0; + // encrypt or decrypt mode based on how much input or not + confirmationView.setText(validInput ? R.string.store_with_fingerprint : R.string.scanning_fingerprint); + mode = validInput ? toggleMode(Cipher.ENCRYPT_MODE) : toggleMode(Cipher.DECRYPT_MODE); + + } + }); + + // callback for fingerprint findings + fingerPrintHelper.setAuthenticationCallback(new FingerprintManager.AuthenticationCallback() { + @Override + public void onAuthenticationError( + final int errorCode, + final CharSequence errString) { + + // this is triggered on stop/start listening done by helper to switch between modes so don't restart here + // errorCode = 5 + // errString = "Fingerprint operation canceled." + //onException(); + //confirmationView.setText(errString); + // true false fingerprint readings are handled otherwise with the toast messages, see below in code + } + + @Override + public void onAuthenticationHelp( + final int helpCode, + final CharSequence helpString) { + + onException(); + confirmationView.setText(helpString); + } + + @Override + public void onAuthenticationSucceeded(final FingerprintManager.AuthenticationResult result) { + + if (mode == Cipher.ENCRYPT_MODE) { + + final String password = passwordView.getText().toString(); + fingerPrintHelper.encryptData(password); + + } else if (mode == Cipher.DECRYPT_MODE) { + + // retrieve the encrypted value from preferences + final String encryptedValue = prefs.getString(getPreferenceKey(), null); + if (encryptedValue != null) { + fingerPrintHelper.decryptData(encryptedValue); + } + } + } + + @Override + public void onAuthenticationFailed() { + onException(); + } + }); + } + } + + private String getPreferenceKey() { + // TODO improve unique key per database generation, using complete path should be unique and seems to work + return PREF_KEY_PREFIX + mDbUri != null ? mDbUri.getPath() : "";//mDbUri.getLastPathSegment(); + } + + private int toggleMode(final int newMode) { + // check if mode is different so we can update fingerprint helper + if (mode != newMode) { + mode = newMode; + fingerPrintHelper.initForMode(mode); + return newMode; + } + // remains in current mode + return mode; + } + + @Override + protected void onPause() { + super.onPause(); + // stop listening when we go in background + if (fingerPrintHelper != null) { + fingerPrintHelper.stopListening(); + } + } + + private void checkAvailability() { + // fingerprint not supported (by API level or hardware) so keep option hidden + if (!fingerPrintHelper.isFingerprintSupported()) { + + fingerprintView.setVisibility(View.GONE); + // since this is a fingerprint example inform user, don't do this in your app + //confirmationView.setText(R.string.fingerprint_not_supported); + confirmationView.setVisibility(View.GONE); + } + // fingerprint is available but not configured show icon but in disabled state with some information + else if (!fingerPrintHelper.hasEnrolledFingerprints()) { + + fingerprintView.setVisibility(View.VISIBLE); + confirmationView.setVisibility(View.VISIBLE); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + fingerprintView.setAlpha(0.3f); + } + // This happens when no fingerprints are registered. Listening won't start + confirmationView.setText(R.string.configure_fingerprint); + } + // finally fingerprint available and configured so we can use it + else { + + fingerprintView.setVisibility(View.VISIBLE); + confirmationView.setVisibility(View.VISIBLE); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + fingerprintView.setAlpha(1f); + } + // all is set here so we can confirm to user and start listening for fingerprints + confirmationView.setText(R.string.scanning_fingerprint); + // listen for decryption by default + toggleMode(Cipher.DECRYPT_MODE); + } + } + + @Override + public void handleResult(final String value) { + if (mode == Cipher.ENCRYPT_MODE) { + + prefs.edit().putString(getPreferenceKey(), value).commit(); + // and remove visual input to reset UI + passwordView.setText(""); + confirmationView.setText(R.string.encrypted_value_stored); + + } else if (mode == Cipher.DECRYPT_MODE) { + + // on decrypt enter it for the purchase/login action + passwordView.setText(value); + // TODO also open DB right away + } + } + + @Override + public void onInvalidKeyException() { + Toast.makeText(this, R.string.fingerprint_invalid_key, Toast.LENGTH_SHORT).show(); + checkAvailability(); // restarts listening + } + + @Override + public void onException() { + Toast.makeText(this, R.string.fingerprint_error, Toast.LENGTH_SHORT).show(); + checkAvailability(); // restarts listening + } + private class DefaultCheckChange implements CompoundButton.OnCheckedChangeListener { @Override - public void onCheckedChanged(CompoundButton buttonView, + public void onCheckedChanged( + CompoundButton buttonView, boolean isChecked) { String newDefaultFileName; @@ -262,13 +466,16 @@ public class PasswordActivity extends LockingActivity { } } - private void loadDatabase(String pass, String keyfile) { + private void loadDatabase( + String pass, + String keyfile) { loadDatabase(pass, UriUtil.parseDefaultFile(keyfile)); } - private void loadDatabase(String pass, Uri keyfile) - { - if ( pass.length() == 0 && (keyfile == null || keyfile.toString().length() == 0)) { + private void loadDatabase( + String pass, + Uri keyfile) { + if (pass.length() == 0 && (keyfile == null || keyfile.toString().length() == 0)) { errorMessage(R.string.error_nopass); return; } @@ -290,9 +497,11 @@ public class PasswordActivity extends LockingActivity { return Util.getEditText(this, resId); } - private void setEditText(int resId, String str) { - TextView te = (TextView) findViewById(resId); - assert(te == null); + private void setEditText( + int resId, + String str) { + TextView te = (TextView) findViewById(resId); + assert (te == null); if (te != null) { te.setText(str); @@ -311,24 +520,27 @@ public class PasswordActivity extends LockingActivity { @Override public boolean onOptionsItemSelected(MenuItem item) { - switch ( item.getItemId() ) { - case R.id.menu_about: - AboutDialog dialog = new AboutDialog(this); - dialog.show(); - return true; + switch (item.getItemId()) { + case R.id.menu_about: + AboutDialog dialog = new AboutDialog(this); + dialog.show(); + return true; - case R.id.menu_app_settings: - AppSettingsActivity.Launch(this); - return true; + case R.id.menu_app_settings: + AppSettingsActivity.Launch(this); + return true; } return super.onOptionsItemSelected(item); } private final class AfterLoad extends OnFinish { + private Database db; - public AfterLoad(Handler handler, Database db) { + public AfterLoad( + Handler handler, + Database db) { super(handler); this.db = db; @@ -336,17 +548,19 @@ public class PasswordActivity extends LockingActivity { @Override public void run() { - if ( db.passwordEncodingError) { + if (db.passwordEncodingError) { PasswordEncodingDialogHelper dialog = new PasswordEncodingDialogHelper(); dialog.show(PasswordActivity.this, new OnClickListener() { @Override - public void onClick(DialogInterface dialog, int which) { + public void onClick( + DialogInterface dialog, + int which) { GroupActivity.Launch(PasswordActivity.this); } }); - } else if ( mSuccess ) { + } else if (mSuccess) { GroupActivity.Launch(PasswordActivity.this); } else { displayMessage(PasswordActivity.this); @@ -355,23 +569,24 @@ public class PasswordActivity extends LockingActivity { } private class InitTask extends AsyncTask { + String password = ""; boolean launch_immediately = false; @Override protected Integer doInBackground(Intent... args) { Intent i = args[0]; - String action = i.getAction();; - if ( action != null && action.equals(VIEW_INTENT) ) { + String action = i.getAction(); + ; + if (action != null && action.equals(VIEW_INTENT)) { Uri incoming = i.getData(); mDbUri = incoming; - mKeyUri = ClipDataCompat.getUriFromIntent(i, KEY_KEYFILE); + mKeyUri = ClipDataCompat.getUriFromIntent(i, KEY_KEYFILE); if (incoming == null) { return R.string.error_can_not_handle_uri; - } - else if (incoming.getScheme().equals("file")) { + } else if (incoming.getScheme().equals("file")) { String fileName = incoming.getPath(); if (fileName.length() == 0) { @@ -385,14 +600,14 @@ public class PasswordActivity extends LockingActivity { return R.string.FileNotFound; } - if(mKeyUri == null) - mKeyUri = getKeyFile(mDbUri); - } - else if (incoming.getScheme().equals("content")) { - if(mKeyUri == null) - mKeyUri = getKeyFile(mDbUri); - } - else { + if (mKeyUri == null) { + mKeyUri = getKeyFile(mDbUri); + } + } else if (incoming.getScheme().equals("content")) { + if (mKeyUri == null) { + mKeyUri = getKeyFile(mDbUri); + } + } else { return R.string.error_can_not_handle_uri; } password = i.getStringExtra(KEY_PASSWORD); @@ -404,7 +619,7 @@ public class PasswordActivity extends LockingActivity { password = i.getStringExtra(KEY_PASSWORD); launch_immediately = i.getBooleanExtra(KEY_LAUNCH_IMMEDIATELY, false); - if ( mKeyUri == null || mKeyUri.toString().length() == 0) { + if (mKeyUri == null || mKeyUri.toString().length() == 0) { mKeyUri = getKeyFile(mDbUri); } } @@ -412,7 +627,7 @@ public class PasswordActivity extends LockingActivity { } public void onPostExecute(Integer result) { - if(result != null) { + if (result != null) { Toast.makeText(PasswordActivity.this, result, Toast.LENGTH_LONG).show(); finish(); return; @@ -427,11 +642,12 @@ public class PasswordActivity extends LockingActivity { // Show or hide password checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() { - public void onCheckedChanged(CompoundButton buttonView, + public void onCheckedChanged( + CompoundButton buttonView, boolean isChecked) { TextView password = (TextView) findViewById(R.id.password); - if ( isChecked ) { + if (isChecked) { password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); } else { password.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); @@ -457,8 +673,7 @@ public class PasswordActivity extends LockingActivity { i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); startActivityForResult(i, OPEN_DOC); - } - else { + } else { Intent i = new Intent(Intent.ACTION_GET_CONTENT); i.addCategory(Intent.CATEGORY_OPENABLE); i.setType("*/*"); @@ -508,8 +723,9 @@ public class PasswordActivity extends LockingActivity { retrieveSettings(); - if (launch_immediately) + if (launch_immediately) { loadDatabase(password, mKeyUri); + } } } } diff --git a/app/src/main/java/com/keepassdroid/fingerprint/FingerPrintHelper.java b/app/src/main/java/com/keepassdroid/fingerprint/FingerPrintHelper.java new file mode 100644 index 000000000..295460878 --- /dev/null +++ b/app/src/main/java/com/keepassdroid/fingerprint/FingerPrintHelper.java @@ -0,0 +1,316 @@ +package com.keepassdroid.fingerprint; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.app.KeyguardManager; +import android.content.Context; +import android.hardware.fingerprint.FingerprintManager; +import android.os.Build; +import android.os.CancellationSignal; +import android.security.keystore.KeyGenParameterSpec; +import android.security.keystore.KeyPermanentlyInvalidatedException; +import android.security.keystore.KeyProperties; +import android.util.Base64; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.security.KeyStore; + +import javax.crypto.Cipher; +import javax.crypto.KeyGenerator; +import javax.crypto.SecretKey; +import javax.crypto.spec.IvParameterSpec; + +public class FingerPrintHelper { + + private int MINIMAL_REQUIRED_SDK_VERSION = Build.VERSION_CODES.M; + + private static final String ALIAS_KEY = "example-key"; + private static final String IV_FILE = "iv-file"; + + private FingerprintManager fingerprintManager; + private Context context; + private KeyStore keyStore = null; + private KeyGenerator keyGenerator = null; + private Cipher cipher = null; + private KeyguardManager keyguardManager = null; + private FingerprintManager.CryptoObject cryptoObject = null; + + private boolean initOk = false; + private IvParameterSpec spec; + private FingerPrintCallback fingerPrintCallback; + private CancellationSignal cancellationSignal; + private FingerprintManager.AuthenticationCallback authenticationCallback; + + public void setAuthenticationCallback(final FingerprintManager.AuthenticationCallback authenticationCallback) { + this.authenticationCallback = authenticationCallback; + } + + @SuppressLint("NewApi") + public void startListening() { + // no need to start listening when not initialised + if (!isFingerprintInitialized()) { + if (fingerPrintCallback != null) { + fingerPrintCallback.onException(); + } + return; + } + // starts listening for fingerprints with the initialised crypto object + cancellationSignal = new CancellationSignal(); + fingerprintManager.authenticate( + cryptoObject, + cancellationSignal, + 0 /* flags */, + authenticationCallback, + null); + } + + @SuppressLint("NewApi") + public void stopListening() { + if (!isFingerprintInitialized()) { + return; + } + if (cancellationSignal != null) { + cancellationSignal.cancel(); + cancellationSignal = null; + } + } + + public void initForMode(final int mode) { + switch (mode) { + case Cipher.ENCRYPT_MODE: { + initEncryptData(); + break; + } + case Cipher.DECRYPT_MODE: { + initDecryptData(); + break; + } + } + } + + public interface FingerPrintCallback { + + void handleResult(String value); + + void onInvalidKeyException(); + + void onException(); + + } + + @TargetApi(Build.VERSION_CODES.M) + public FingerPrintHelper( + final Context context, + final FingerPrintCallback fingerPrintCallback) { + + if (!isFingerprintSupported()) { + // really not much to do when no fingerprint support found + setInitOk(false); + return; + } + this.context = context; + this.fingerprintManager = context.getSystemService(FingerprintManager.class); + this.keyguardManager = context.getSystemService(KeyguardManager.class); + this.fingerPrintCallback = fingerPrintCallback; + + if (hasEnrolledFingerprints()) { + try { + this.keyStore = KeyStore.getInstance("AndroidKeyStore"); + this.keyGenerator = KeyGenerator.getInstance( + KeyProperties.KEY_ALGORITHM_AES, + "AndroidKeyStore"); + this.cipher = Cipher.getInstance( + KeyProperties.KEY_ALGORITHM_AES + "/" + + KeyProperties.BLOCK_MODE_CBC + "/" + + KeyProperties.ENCRYPTION_PADDING_PKCS7); + this.cryptoObject = new FingerprintManager.CryptoObject(cipher); + setInitOk(true); + } catch (final Exception e) { + setInitOk(false); + fingerPrintCallback.onException(); + } + } + } + + public boolean isFingerprintInitialized() { + return hasEnrolledFingerprints() && initOk; + } + + @SuppressWarnings("NewApi") + public void initEncryptData() { + + if (!isFingerprintInitialized()) { + if (fingerPrintCallback != null) { + fingerPrintCallback.onException(); + } + return; + } + try { + createNewKeyIfNeeded(false); // no need to keep deleting existing keys + keyStore.load(null); + final SecretKey key = (SecretKey) keyStore.getKey(ALIAS_KEY, null); + cipher.init(Cipher.ENCRYPT_MODE, key); + + stopListening(); + startListening(); + + } catch (final KeyPermanentlyInvalidatedException invalidKeyException) { + fingerPrintCallback.onInvalidKeyException(); + } catch (final Exception e) { + fingerPrintCallback.onException(); + } + } + + @SuppressWarnings("NewApi") + public void encryptData(final String value) { + + if (!isFingerprintInitialized()) { + if (fingerPrintCallback != null) { + fingerPrintCallback.onException(); + } + return; + } + try { + // actual do encryption here + byte[] encrypted = cipher.doFinal(value.getBytes()); + final String encryptedValue = Base64.encodeToString(encrypted, 0 /* flags */); + + // create & store spec here since we need it to decrypt again later on (only done at this point to prevent failures on next attempts if + // we never encrypted anything new) + spec = cipher.getParameters().getParameterSpec(IvParameterSpec.class); + final FileOutputStream fileOutputStream = context.openFileOutput(IV_FILE, Context.MODE_PRIVATE); + fileOutputStream.write(spec.getIV()); + fileOutputStream.close(); + + fingerPrintCallback.handleResult(encryptedValue); + + } catch (final Exception e) { + fingerPrintCallback.onException(); + } + + } + + @SuppressWarnings("NewApi") + public void initDecryptData() { + + if (!isFingerprintInitialized()) { + if (fingerPrintCallback != null) { + fingerPrintCallback.onException(); + } + return; + } + + try { + createNewKeyIfNeeded(false); + keyStore.load(null); + final SecretKey key = (SecretKey) keyStore.getKey(ALIAS_KEY, null); + + // restore spec + final File file = new File(context.getFilesDir() + "/" + IV_FILE); + final int fileSize = (int) file.length(); + final byte[] iv = new byte[fileSize]; + + final FileInputStream fileInputStream = context.openFileInput(IV_FILE); + fileInputStream.read(iv, 0, fileSize); + fileInputStream.close(); + + spec = new IvParameterSpec(iv); + cipher.init(Cipher.DECRYPT_MODE, key, spec); + + stopListening(); + startListening(); + + } catch (final KeyPermanentlyInvalidatedException invalidKeyException) { + fingerPrintCallback.onInvalidKeyException(); + } catch (final Exception e) { + fingerPrintCallback.onException(); + } + } + + @SuppressWarnings("NewApi") + public void decryptData(final String encryptedValue) { + + if (!isFingerprintInitialized()) { + if (fingerPrintCallback != null) { + fingerPrintCallback.onException(); + } + return; + } + + try { + // actual decryption here + final byte[] encrypted = Base64.decode(encryptedValue, 0); + byte[] decrypted = cipher.doFinal(encrypted); + final String decryptedString = new String(decrypted); + //final String encryptedString = Base64.encodeToString(encrypted, 0 /* flags */); + fingerPrintCallback.handleResult(decryptedString); + + } catch (final Exception e) { + fingerPrintCallback.onException(); + } + } + + @SuppressLint("NewApi") + private void createNewKeyIfNeeded(final boolean allowDeleteExisting) { + if (!isFingerprintInitialized()) { + return; + } + try { + keyStore.load(null); + if (allowDeleteExisting + && keyStore.containsAlias(ALIAS_KEY)) { + + keyStore.deleteEntry(ALIAS_KEY); + } + + // Create new key if needed + if (!keyStore.containsAlias(ALIAS_KEY)) { + // Set the alias of the entry in Android KeyStore where the key will appear + // and the constrains (purposes) in the constructor of the Builder + keyGenerator.init( + new KeyGenParameterSpec.Builder( + ALIAS_KEY, + KeyProperties.PURPOSE_ENCRYPT | + KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_CBC) + // Require the user to authenticate with a fingerprint to authorize every use + // of the key + .setUserAuthenticationRequired(true) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) + .build()); + keyGenerator.generateKey(); + } + } catch (final Exception e) { + fingerPrintCallback.onException(); + } + } + + @SuppressLint("NewApi") + public boolean isHardwareDetected() { + return isFingerprintSupported() + && fingerprintManager != null + && fingerprintManager.isHardwareDetected(); + } + + @SuppressLint("NewApi") + public boolean hasEnrolledFingerprints() { + // fingerprint hardware supported and api level OK + return isHardwareDetected() + // fingerprints enrolled + && fingerprintManager != null + && fingerprintManager.hasEnrolledFingerprints() + // and lockscreen configured + && keyguardManager.isKeyguardSecure(); + } + + void setInitOk(final boolean initOk) { + this.initOk = initOk; + } + + public boolean isFingerprintSupported() { + return Build.VERSION.SDK_INT >= MINIMAL_REQUIRED_SDK_VERSION; + } + +} \ No newline at end of file diff --git a/app/src/main/res/drawable-hdpi/ic_fp_40px.png b/app/src/main/res/drawable-hdpi/ic_fp_40px.png new file mode 100644 index 000000000..48ebd8ad7 Binary files /dev/null and b/app/src/main/res/drawable-hdpi/ic_fp_40px.png differ diff --git a/app/src/main/res/drawable-xhdpi/ic_fp_40px.png b/app/src/main/res/drawable-xhdpi/ic_fp_40px.png new file mode 100644 index 000000000..e1c9590bb Binary files /dev/null and b/app/src/main/res/drawable-xhdpi/ic_fp_40px.png differ diff --git a/app/src/main/res/drawable-xxhdpi/ic_fp_40px.png b/app/src/main/res/drawable-xxhdpi/ic_fp_40px.png new file mode 100644 index 000000000..f7e87240e Binary files /dev/null and b/app/src/main/res/drawable-xxhdpi/ic_fp_40px.png differ diff --git a/app/src/main/res/layout/password.xml b/app/src/main/res/layout/password.xml index 990945936..f88201756 100644 --- a/app/src/main/res/layout/password.xml +++ b/app/src/main/res/layout/password.xml @@ -18,11 +18,12 @@ along with KeePassDroid. If not, see . --> - + - - + + + + + - -