Skip to main content

Android How to Implement Fingerprint Authentication Kotlin

Fingerprint Authentication is essential authorization method for App. It does not mean that current method using pin and password is not good. Existing method is also very useful but the Fingerprint Authentication is unique and it's almost impossible to guess.

Fingerprint Authentication feature has been released from Android 6.(M) onward. In Following tutorial and example shows how to implement Fingerprint Authentication in your application.

The benefit of using the Fingerprint Scan Authentication


1. The main benefit of this is that your identity is never break even after your phone gets misplaced. It doesn't matter how?
2. It is very Fast, Convenient and Reliable way to Authenticate.
3. Fingerprints are always unique so its assure that your app will only get unlocked by you.
4. It will make the online transaction more secure and you can verify your app by just by scanning the Finger.

The final app will look as below after implementation.

Fingerprint Scanner Authorization demo Android

Create the Project


First of all, we have to create the project using Android Studio.

Fingerprint Authentication Auth Create Project

Select the API level as per your requirement. But you can support the fingerprints scan authentication from Android Version 6(M).

Fingerprint Authentication Auth Create Project2

Set required Permission and feature Into AndroidMainfest


We need to add USE_FINGERPRINT permission and android.hardware.fingerprint feature into the AndroidMainfest.xml file as given below.
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-feature android:name="android.hardware.fingerprint"
android:required="false"/>

Here, we set the feature android.hardware.fingerprint to false. Because we want to show our app on google play even if the user doesn't have the fingerprint on their device.  If we set it true then your app will not show the device which does not support the fingerprint scanner.

Complet AndroidManifest.xml files as given below.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.nplix.appauth">
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-feature android:name="android.hardware.fingerprint"
android:required="false"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>

Create Layout Files For The Fingerprint Scanner Authentication


We have to create the layout for the Fingerprint Scanner Authentication Screen in our application. Let's create the layout as given below.

Update the string.xml


We need to update the string.xml file as per our requirement in the layout.
<resources>
<string name="app_name">Fingerprint Authentication</string>
<string name="auth_title"> Authenticate </string>
<string name="auth_success">Congratulation ! You have Successfully Authorization has</string>
<string name="aut_fail">Authorization is not Success</string>
<string name="msg"> Sweep on your Fingerprint to Authorize</string>
<string name="btn_auth">Sweep</string>
</resources>

Create auth logo for Fingerprint Scanner


We need to create the Fingerprints Scanner logo using the ImageAsset tool in the android studio. So go to File->New->ImageAsset

fingerprint Scanner logo

create fingerprint scanner logo

 

Create Layout files


So, let's create or modify the main activity layout file as given below.
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
android:id="@+id/auth"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/auth_title"
android:textSize="32sp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:text="@string/btn_auth"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

<TextView
android:id="@+id/message"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="@+id/button"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/imageView" />

<ImageView
android:id="@+id/imageView"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/auth"
app:srcCompat="@drawable/ic_action_auth"
android:layout_marginLeft="16dp"
android:layout_marginRight="8dp" />

</android.support.constraint.ConstraintLayout>

 

Create Main Activity File


We now need to create the MainActivity.kt file as given below. It contains the below method as given below.

checkFinger() -> This method checks the basic requirement using the KeygurardManager.

generateKey() -> This method used to create the secure key.

generateCipher() - > Generate the cipher for auth.
package com.nplix.fingerprintauthentication

import android.app.KeyguardManager
import android.content.Context
import android.hardware.fingerprint.FingerprintManager
import android.os.Bundle
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Button
import android.widget.TextView
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey

class MainActivity : AppCompatActivity() {
private val KEY_NAME:String="mykey"
private val TAG:String="FigurePrintAuth"

private var keyStore: KeyStore? = null
private var keyGenerator: KeyGenerator? = null
private val textView: TextView? = null
private var cryptoObject: FingerprintManager.CryptoObject? = null
private var fingerprintManager: FingerprintManager? = null


var message: TextView?=null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

message = findViewById<TextView>(R.id.message)
val btn = findViewById<Button>(R.id.button)
val fph = FingerprintHandler(message!!)
if (!checkFinger()) {
Log.d(TAG,"checkFinger return"+!checkFinger())
btn.isEnabled = false
} else {
// We are ready to set up the cipher and the key
Log.d(TAG,"checkFinger return else"+!checkFinger())
generateKey()
val cipher = generateCipher()
cryptoObject = FingerprintManager.CryptoObject(cipher)
message?.text=getString(R.string.msg);

}
btn.setOnClickListener{
message!!.text="Touch the fingerprint scanner to authorize"
fph.doAuth(this.fingerprintManager!!, this!!.cryptoObject!!)

}
}


private fun checkFinger(): Boolean {
// Keyguard Manager
val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
// Fingerprint Manager
fingerprintManager = getSystemService(Context.FINGERPRINT_SERVICE) as FingerprintManager
try {
// Check if the fingerprint sensor is present
if (!fingerprintManager!!.isHardwareDetected) {
// Update the UI with a message
message?.text = getString(R.string.fingerprint_not_supported)
return false
}
if (!fingerprintManager!!.hasEnrolledFingerprints()) {
message?.text = getString(R.string.no_fingerprint_configured)
return false
}
if (!keyguardManager.isKeyguardSecure) {
message?.text = getString(R.string.secure_lock_not_enabled)
return false
}
} catch (se: SecurityException) {
se.printStackTrace()
}

return true
}

private fun generateKey() {

// Get the reference to the key store
keyStore = KeyStore.getInstance("AndroidKeyStore")
// Key generator to generate the key
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,
"AndroidKeyStore")
keyStore?.load(null)
keyGenerator?.init(KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(
KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build())
keyGenerator?.generateKey()


}


private fun generateCipher(): Cipher {

val cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_CBC + "/"
+ KeyProperties.ENCRYPTION_PADDING_PKCS7)
val key = keyStore?.getKey(KEY_NAME,
null) as SecretKey
cipher.init(Cipher.ENCRYPT_MODE, key)
return cipher
}
}

Create Fingerprint Authentication helper Class


Create a class and name it FingerprintHandler.kt. The Handler class and extends FingerprintManager.AuthenticationCallback and implements the all required package.
package com.nplix.fingerprintauthentication

import android.hardware.fingerprint.FingerprintManager
import android.os.CancellationSignal
import android.provider.Settings.Secure.getString
import android.widget.TextView

class FingerprintHandler(private val tv: TextView) : FingerprintManager.AuthenticationCallback() {
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
super.onAuthenticationError(errorCode, errString)
tv.text = tv.context.getString(R.string.aut_fail)
}

override fun onAuthenticationHelp(helpCode: Int, helpString: CharSequence) {
super.onAuthenticationHelp(helpCode, helpString)
}

override fun onAuthenticationSucceeded(result: FingerprintManager.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
tv.text = tv.context.getString(R.string.auth_success)
tv.setTextColor(tv.context.resources.getColor(android.R.color.holo_green_light))
}

override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
}

fun doAuth(manager: FingerprintManager,
obj: FingerprintManager.CryptoObject) {
val signal = CancellationSignal()
try {
manager.authenticate(obj, signal, 0, this, null)
} catch (sce: SecurityException) {
}

}
}

Test your FingerPrint Scanner App


There is two way to test fingerprint scanner authorization. If you have a physical device there is nothing need to be done just install the app and test the same.

But, if you want to test this on emulator then we have to register the dummy fingerprint using the ADB commands.

The requirement of the Fingerprint Authentication



  • You must set up the pin or any other auth method

  • register the fingerprint on the emulator


Set up the fingerprint authentication on the emulator



  1. Open the setting on the emulator

  2. Go to Security

  3. Setup the Lock Screen Authentication by tabbing on fingerprint


Setup Fingerprint android

Choose your Fingerprint backup screen lock

fingerprint backup screen lock

Follow the further notification and enter the required. You have to use the password, pattern or PIN depending on the method you have selected.  After that, you will get the below screen.

Fingerprint Auth setting

To go next from this screen we need to provide the input using our fingerprint sensor. But, we know physical fingerprint scanner is not available on the emulator. So we need to provide the input using the ADB command.

List all connected device using the command below.

Windows
cd C:\Users\Username\AppData\Local\Android\sdk\platform-tools
C:\Users\PK\AppData\Local\Android\sdk\platform-tools>adb.exe devices
List of devices attached
emulator-5554 device

Linux
Go to SDK location on your device and then  
# ./adb devices
List of devices attached
emulator-5554 device

Then enter the below command to pass the dummy fingerprint scan key event to the emulator.
Pass the touch key input to emulator
adb.exe -s emulator-5554 emu finger touch 1

After this emulator will ask your fingerprint input for setting so input the same again.

fingerprint touch input to emulator

Your scan will get completed and will change as below after each Input.

Fingerprint Touch 1

Fingerprint Touch 2Fingerprint Touch 3

 

 

 

 

 

 

 

 

Test Our Fingerprint Scanner Demo App


Now, Time to test the demo application created into this tutorial.

[caption id="attachment_1285" align="alignleft" width="169"]Fingerprint Scanner Authorization demo Android Click on AUTH TEST Button[/caption]

[caption id="attachment_1286" align="alignleft" width="169"]Fingerprint Scanner Authorization demo Android Input touch Event using the command given below.[/caption]

[caption id="attachment_1287" align="alignleft" width="169"]Fingerprint Scanner Authorization demo Android Auth Success[/caption]

 

 

 

 

 

 

 

 

 
adb.exe -s emulator-5554 emu finger touch 1

Conclusion


If you follow the all the above steps as described it is not too diffcult to implement the Fingerprint Scanner Autrization.

Comments

Popular posts from this blog

Flutter Theme Creation, Programmatic Way

Flutter and Dart is an excellent combination for creating the mobile app with material design with nice GUI. Its lots of widget which help the developer for creating the app UI very fast with respect to the other language. You may face some problem in starting due to comm, curly brace and semicolon but after some time you will find the way how to work with these all stuff and it becomes very easy for you. But in this article, we are not going to discuss all these. In this article, we will handle a very interesting topic on how to create a custom theme or multiple themes and let's user decide which theme to use.



Create a flutter project



So let's create a flutter project by selecting the appropriate option from the File menu in android studio or Visual Code. If you are new to Flutter and Dart you can check out our recent post to get started Creating Cross-platform app using flutter.



Once your project is created you will get the default counter app and you try running the app in the…

Flutter How to Start Android Activity from Flutter View

Flutter and Dart is an excellent combination for creating the UI, but for accessing the platform-specific service we need to open platform-specific activity. So lets in this article we will explore how to start an android activity and access the service from Flutter View.

Create a Project for this Android Activity Flutter View Demo Create a Project From File menu select the New Flutter Project Enter the project name Select the AndroidX support and click on next After the above, we step click on Finish We will have the following project structure created. Create the Second Activity in Android
Just go to the android folder and open it in separate windows. We will have the following project structure.









Create the Activity Just right click on the Kotlin folder and create a blank activity from the menu. If you create the activity then you may be required to upgrade the Gradle and do some import. So Just click on update and wait for the project sync completed.
Update the project build config …

Flutter State Management With Provider and ChangeNotifier

Flutter state management with provider library and why it's so important? There are lots of topics in flutter which are very important but out of those state management of your flutter application is the most important and little bit complicated as well. So in this article, I will try to explain how to use the provider package for managing the state of flutter and dart application and how to access the data down the hierarchy of the widget tree without recreating the whole UI.



Basic knowledge of the state management and data flow in the Flutter



Before starting the coding I would like to explain some basics about the Flutter application so that you can understand, why it's important to manage the state of your application in the correct way.



In Flutter, everything is a widget and whenever the state of your application changes the UI is recreated the UI with the new data. Let's list out the topic or problem that we are going to explore about state management.



Challenge of St…