Show visual password strength indicator #631

This commit is contained in:
J-Jamet committed 2022-03-27 17:22:52 +02:00
1 parent 76319a56a2
commit 41c0aeedbe
10 files changed
+186 -5

No files matched your search

@@ -22,15 +22,19 @@ package com.kunzisoft.keepass.activities.dialogs
import android.app.Dialog
import android.content.Context
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.*
import androidx.appcompat.app.AlertDialog
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.google.android.material.textfield.TextInputLayout
import com.kunzisoft.keepass.R
import com.kunzisoft.keepass.database.element.Field
import com.kunzisoft.keepass.password.PasswordGenerator
import com.kunzisoft.keepass.settings.PreferencesUtil
import com.kunzisoft.keepass.timeout.ClipboardHelper
import com.kunzisoft.keepass.utils.PasswordEntropy
import com.kunzisoft.keepass.view.applyFontVisibility
class GeneratePasswordDialogFragment : DatabaseDialogFragment() {
@@ -38,11 +42,13 @@ class GeneratePasswordDialogFragment : DatabaseDialogFragment() {
private var mListener: GeneratePasswordListener? = null
private var root: View? = null
private var passwordStrengthProgress: LinearProgressIndicator? = null
private var lengthTextView: EditText? = null
private var passwordInputLayoutView: TextInputLayout? = null
private var passwordView: EditText? = null
private var mPasswordField: Field? = null
private var mPasswordEntropyCalculator: PasswordEntropy? = null
private var uppercaseBox: CompoundButton? = null
private var lowercaseBox: CompoundButton? = null
@@ -69,6 +75,29 @@ class GeneratePasswordDialogFragment : DatabaseDialogFragment() {
super.onDetach()
}
override fun onResume() {
super.onResume()
// To check checkboxes if a text is present
passwordView?.addTextChangedListener(passwordTextWatcher)
}
override fun onPause() {
super.onPause()
passwordView?.removeTextChangedListener(passwordTextWatcher)
}
private val passwordTextWatcher = object : TextWatcher {
override fun beforeTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun onTextChanged(charSequence: CharSequence, i: Int, i1: Int, i2: Int) {}
override fun afterTextChanged(editable: Editable) {
getEntropyStrength(editable.toString())
}
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
activity?.let { activity ->
val builder = AlertDialog.Builder(activity)
@@ -87,7 +116,7 @@ class GeneratePasswordDialogFragment : DatabaseDialogFragment() {
getString(R.string.copy_field,
getString(R.string.entry_password)))
}
passwordStrengthProgress = root?.findViewById(R.id.password_strength_progress)
lengthTextView = root?.findViewById(R.id.length)
uppercaseBox = root?.findViewById(R.id.cb_uppercase)
@@ -101,6 +130,11 @@ class GeneratePasswordDialogFragment : DatabaseDialogFragment() {
extendedBox = root?.findViewById(R.id.cb_extended)
mPasswordField = arguments?.getParcelable(KEY_PASSWORD_FIELD)
mPasswordEntropyCalculator = PasswordEntropy {
passwordView?.text?.toString()?.let { firstPassword ->
getEntropyStrength(firstPassword)
}
}
assignDefaultCharacters()
@@ -147,6 +181,17 @@ class GeneratePasswordDialogFragment : DatabaseDialogFragment() {
return super.onCreateDialog(savedInstanceState)
}
private fun getEntropyStrength(passwordText: String) {
mPasswordEntropyCalculator?.getEntropyStrength(passwordText) { entropyStrength ->
passwordStrengthProgress?.apply {
post {
setIndicatorColor(entropyStrength.strength.color)
setProgressCompat(entropyStrength.estimationPercent, true)
}
}
}
}
private fun assignDefaultCharacters() {
uppercaseBox?.isChecked = false
lowercaseBox?.isChecked = false
@@ -178,10 +223,12 @@ class GeneratePasswordDialogFragment : DatabaseDialogFragment() {
}
private fun fillPassword() {
root?.findViewById<EditText>(R.id.password)?.setText(generatePassword())
val passwordGenerated = generatePassword()
root?.findViewById<EditText>(R.id.password)?.setText(passwordGenerated)
getEntropyStrength(passwordGenerated)
}
fun generatePassword(): String {
private fun generatePassword(): String {
var password = ""
try {
val length = Integer.valueOf(root?.findViewById<EditText>(R.id.length)?.text.toString())
@@ -27,15 +27,18 @@ import android.os.Bundle
import android.text.Editable
import android.text.SpannableStringBuilder
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.CompoundButton
import android.widget.TextView
import androidx.appcompat.app.AlertDialog
import com.google.android.material.progressindicator.LinearProgressIndicator
import com.google.android.material.textfield.TextInputLayout
import com.kunzisoft.keepass.R
import com.kunzisoft.keepass.activities.helpers.ExternalFileHelper
import com.kunzisoft.keepass.activities.helpers.setOpenDocumentClickListener
import com.kunzisoft.keepass.model.MainCredential
import com.kunzisoft.keepass.utils.PasswordEntropy
import com.kunzisoft.keepass.utils.UriUtil
import com.kunzisoft.keepass.view.KeyFileSelectionView
@@ -50,6 +53,7 @@ class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
private var passwordTextInputLayout: TextInputLayout? = null
private var passwordView: TextView? = null
private var passwordStrengthView: LinearProgressIndicator? = null
private var passwordRepeatTextInputLayout: TextInputLayout? = null
private var passwordRepeatView: TextView? = null
@@ -59,6 +63,7 @@ class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
private var mListener: AssignMainCredentialDialogListener? = null
private var mExternalFileHelper: ExternalFileHelper? = null
private var mPasswordEntropyCalculator: PasswordEntropy? = null
private var mEmptyPasswordConfirmationDialog: AlertDialog? = null
private var mNoKeyConfirmationDialog: AlertDialog? = null
@@ -71,6 +76,15 @@ class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
override fun afterTextChanged(editable: Editable) {
passwordCheckBox?.isChecked = true
// Define password strength
mPasswordEntropyCalculator?.getEntropyStrength(editable.toString()) { entropyStrength ->
passwordStrengthView?.apply {
post {
setIndicatorColor(entropyStrength.strength.color)
setProgressCompat(entropyStrength.estimationPercent, true)
}
}
}
}
}
@@ -100,6 +114,13 @@ class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
super.onDetach()
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Create the password entropy object
mPasswordEntropyCalculator = PasswordEntropy()
}
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
activity?.let { activity ->
@@ -125,6 +146,12 @@ class SetMainCredentialDialogFragment : DatabaseDialogFragment() {
passwordCheckBox = rootView?.findViewById(R.id.password_checkbox)
passwordTextInputLayout = rootView?.findViewById(R.id.password_input_layout)
passwordView = rootView?.findViewById(R.id.pass_password)
passwordStrengthView = rootView?.findViewById(R.id.password_strength_progress)
passwordStrengthView?.apply {
setIndicatorColor(PasswordEntropy.Strength.RISKY.color)
progress = 0
max = 100
}
passwordRepeatTextInputLayout = rootView?.findViewById(R.id.password_repeat_input_layout)
passwordRepeatView = rootView?.findViewById(R.id.pass_conf_password)
@@ -26,7 +26,7 @@ import kotlinx.coroutines.*
*/
class IOActionTask<T>(
private val action: () -> T ,
private val afterActionDatabaseListener: ((T?) -> Unit)? = null) {
private val afterActionListener: ((T?) -> Unit)? = null) {
private val mainScope = CoroutineScope(Dispatchers.Main)
@@ -42,7 +42,7 @@ class IOActionTask<T>(
}
}
withContext(Dispatchers.Main) {
afterActionDatabaseListener?.invoke(asyncResult.await())
afterActionListener?.invoke(asyncResult.await())
}
}
}
@@ -0,0 +1,90 @@
/*
* Copyright 2022 Jeremy Jamet / Kunzisoft.
*
* This file is part of KeePassDX.
*
* KeePassDX is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* KeePassDX is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with KeePassDX. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.kunzisoft.keepass.utils
import android.graphics.Color
import com.kunzisoft.keepass.app.database.IOActionTask
import me.gosimple.nbvcxz.Nbvcxz
import me.gosimple.nbvcxz.resources.Configuration
import me.gosimple.nbvcxz.resources.ConfigurationBuilder
import java.util.*
import kotlin.math.ln
import kotlin.math.min
class PasswordEntropy(actionOnInitFinished: (() -> Unit)? = null) {
private var mPasswordEntropyCalculator: Nbvcxz? = null
init {
IOActionTask({
// Create the password generator object
val configuration: Configuration = ConfigurationBuilder()
.setLocale(Locale.getDefault())
.setMinimumEntropy(80.0)
.createConfiguration()
mPasswordEntropyCalculator = Nbvcxz(configuration)
}, {
actionOnInitFinished?.invoke()
}).execute()
}
enum class Strength(val color: Int) {
RISKY(Color.rgb(224, 56, 56)),
VERY_GUESSABLE(Color.rgb(196, 63, 49)),
SOMEWHAT_GUESSABLE(Color.rgb(219, 152, 55)),
SAFELY_UNGUESSABLE(Color.rgb(118, 168, 24)),
VERY_UNGUESSABLE(Color.rgb(37, 152, 41))
}
data class EntropyStrength(val strength: Strength,
val estimationPercent: Int) {
override fun toString(): String {
return "EntropyStrength(strength=$strength, estimationPercent=$estimationPercent)"
}
}
fun getEntropyStrength(passwordString: String,
entropyStrengthResult: (EntropyStrength) -> Unit) {
val basicScore = mPasswordEntropyCalculator?.estimate(passwordString)?.basicScore ?: 0
val percentScore = min(((ln((basicScore+2.0)) *passwordString.length)*100/60).toInt(), 100)
val strength =
if (basicScore == 0 || percentScore < 10) {
Strength.RISKY
} else if (basicScore == 1 || percentScore < 20) {
Strength.VERY_GUESSABLE
} else if (basicScore == 2 || percentScore < 33) {
Strength.SOMEWHAT_GUESSABLE
} else if (basicScore == 3 || percentScore < 52) {
Strength.SAFELY_UNGUESSABLE
} else if (basicScore == 4) {
Strength.VERY_UNGUESSABLE
} else {
Strength.RISKY
}
IOActionTask(
{
EntropyStrength(strength, percentScore)
},
{
it?.let { entropyStrength -> entropyStrengthResult.invoke(entropyStrength) }
}
).execute()
}
}