· 6 years ago · Dec 18, 2019, 10:46 PM
1package com.example.fingerprint
2import android.Manifest
3import android.content.Context
4import android.content.Intent
5import android.content.pm.PackageManager
6import android.hardware.fingerprint.FingerprintManager
7import android.os.CancellationSignal
8import android.widget.Toast
9import androidx.core.app.ActivityCompat
10
11class FingerprintHandler (private val appContext: Context) : FingerprintManager.AuthenticationCallback(){
12 private var cancellationSignal : CancellationSignal? = null
13
14 fun startAuth(manager : FingerprintManager, cryptoObject: FingerprintManager.CryptoObject) {
15 cancellationSignal = CancellationSignal()
16
17 if (ActivityCompat.checkSelfPermission(appContext, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
18 return
19 }
20 manager.authenticate(cryptoObject, cancellationSignal, 0, this,null)
21 }
22
23 override fun onAuthenticationError(signal: Int, errString: CharSequence) {
24 Toast.makeText(appContext, "Authentication error\n" + errString, Toast.LENGTH_LONG).show()
25 }
26
27 override fun onAuthenticationHelp(signal : Int, helpString: CharSequence) {
28 Toast.makeText(appContext, "Authentication help\n"+ helpString, Toast.LENGTH_LONG).show()
29 }
30
31 override fun onAuthenticationFailed() {
32 Toast.makeText(appContext, "Authentication failed", Toast.LENGTH_LONG).show()
33 }
34
35 override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult) {
36 Toast.makeText(appContext, "Authentication succeeded.", Toast.LENGTH_LONG).show()
37 val intent = Intent(appContext,Note::class.java)
38 appContext.startActivity(intent)
39
40 }
41}
42// main actrivity
43package com.example.fingerprint
44
45import android.Manifest
46import android.app.KeyguardManager
47import android.content.Context
48import android.content.pm.PackageManager
49import android.hardware.fingerprint.FingerprintManager
50import androidx.appcompat.app.AppCompatActivity
51import android.os.Bundle
52import android.security.keystore.KeyGenParameterSpec
53import android.security.keystore.KeyPermanentlyInvalidatedException
54import android.security.keystore.KeyProperties
55import android.widget.Button
56import android.widget.Toast
57import androidx.core.app.ActivityCompat
58import java.io.IOException
59import java.security.*
60import javax.crypto.Cipher
61import javax.crypto.KeyGenerator
62import javax.crypto.NoSuchPaddingException
63import javax.crypto.SecretKey
64import javax.security.cert.CertificateException
65
66class MainActivity : AppCompatActivity() {
67
68 private var fingerprintManager: FingerprintManager? = null
69 private var keyguardManager: KeyguardManager? = null
70 private var keyStore: KeyStore? = null
71 private var keyGenerator: KeyGenerator? = null
72 private val KEY_NAME = "key_note"
73 private var cipher: Cipher? = null
74 private var cryptoObject: FingerprintManager.CryptoObject? = null
75
76 private var disableBack : Boolean = false
77
78 override fun onBackPressed() {
79 // super.onBackPressed(); commented this line in order to disable back press
80 //Write your code here
81 if (!disableBack) {
82 super.onBackPressed()
83 }
84 else {
85 Toast.makeText(applicationContext, "Back press disabled!", Toast.LENGTH_SHORT).show()
86 }
87 }
88
89 override fun onCreate(savedInstanceState: Bundle?) {
90 super.onCreate(savedInstanceState)
91 setContentView(R.layout.activity_main)
92
93 val button = findViewById<Button>(R.id.button)
94 disableBack = intent.getBooleanExtra("back", false)
95 button.setOnClickListener {
96 Toast.makeText(this,"It works", Toast.LENGTH_LONG).show()
97 }
98
99 if (getManagers()) {
100 generateKey()
101
102 if (cipherInit()) {
103 cipher?.let {
104 cryptoObject = FingerprintManager.CryptoObject(it)
105 }
106
107 val helper = FingerprintHandler(this)
108
109 if (fingerprintManager != null && cryptoObject != null) {
110 helper.startAuth(fingerprintManager!!, cryptoObject!!)
111 }
112 }
113 }
114 }
115
116 private fun getManagers() : Boolean {
117 keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
118 fingerprintManager = getSystemService(Context.FINGERPRINT_SERVICE) as FingerprintManager
119
120 if (keyguardManager?.isKeyguardSecure == false) {
121
122 Toast.makeText(this,
123 "Lock screen security not enabled in Settings",
124 Toast.LENGTH_LONG).show()
125 return false
126 }
127
128 if (ActivityCompat.checkSelfPermission(this,
129 Manifest.permission.USE_FINGERPRINT) !=
130 PackageManager.PERMISSION_GRANTED) {
131 Toast.makeText(this,
132 "Fingerprint authentication permission not enabled",
133 Toast.LENGTH_LONG).show()
134
135 return false
136 }
137
138 if (fingerprintManager?.hasEnrolledFingerprints() == false) {
139 Toast.makeText(this,
140 "Register at least one fingerprint in Settings",
141 Toast.LENGTH_LONG).show()
142 return false
143 }
144 return true
145 }
146
147 private fun generateKey() {
148 try {
149 keyStore = KeyStore.getInstance("AndroidKeyStore")
150 } catch (e: Exception) {
151 e.printStackTrace()
152 }
153 try {
154 keyGenerator = KeyGenerator.getInstance(
155 KeyProperties.KEY_ALGORITHM_AES,
156 "AndroidKeyStore")
157 } catch (e: NoSuchAlgorithmException) {
158 throw RuntimeException(
159 "Failed to get KeyGenerator instance", e)
160 } catch (e: NoSuchProviderException) {
161 throw RuntimeException("Failed to get KeyGenerator instance", e)
162 }
163 try {
164 keyStore?.load(null)
165 keyGenerator?.init(
166 KeyGenParameterSpec.Builder(KEY_NAME,
167 KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
168 .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
169 .setUserAuthenticationRequired(true)
170 .setEncryptionPaddings(
171 KeyProperties.ENCRYPTION_PADDING_PKCS7)
172 .build())
173 keyGenerator?.generateKey()
174 } catch (e: NoSuchAlgorithmException) {
175 throw RuntimeException(e)
176 } catch (e: InvalidAlgorithmParameterException) {
177 throw RuntimeException(e)
178 } catch (e: CertificateException) {
179 throw RuntimeException(e)
180 } catch (e: IOException) {
181 throw RuntimeException(e)
182 }
183 }
184
185 private fun cipherInit(): Boolean {
186 try {
187 cipher = Cipher.getInstance(
188 KeyProperties.KEY_ALGORITHM_AES + "/"
189 + KeyProperties.BLOCK_MODE_CBC + "/"
190 + KeyProperties.ENCRYPTION_PADDING_PKCS7)
191 } catch (e: NoSuchAlgorithmException) {
192 throw RuntimeException("Failed to get Cipher", e)
193 } catch (e: NoSuchPaddingException) {
194 throw RuntimeException("Failed to get Cipher", e)
195 }
196
197 try {
198 keyStore?.load(null)
199 val key = keyStore?.getKey(KEY_NAME, null) as SecretKey
200 cipher?.init(Cipher.ENCRYPT_MODE, key)
201 return true
202 } catch (e: KeyPermanentlyInvalidatedException) {
203 return false
204 } catch (e: KeyStoreException) {
205 throw RuntimeException("Failed to init Cipher", e)
206 } catch (e: CertificateException) {
207 throw RuntimeException("Failed to init Cipher", e)
208 } catch (e: UnrecoverableKeyException) {
209 throw RuntimeException("Failed to init Cipher", e)
210 } catch (e: IOException) {
211 throw RuntimeException("Failed to init Cipher", e)
212 } catch (e: NoSuchAlgorithmException) {
213 throw RuntimeException("Failed to init Cipher", e)
214 } catch (e: InvalidKeyException) {
215 throw RuntimeException("Failed to init Cipher", e)
216 }
217 }
218}