Android How to Implement Fingerprint Authentication Kotlin

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.

Fingerprint Scanner Authorization demo Android
Click on AUTH TEST Button
Fingerprint Scanner Authorization demo Android
Input touch Event using the command given below.
Fingerprint Scanner Authorization demo Android
Auth Success

 

 

 

 

 

 

 

 

 

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.

Get Email Updates!

Signup now receive an email once I publish new content. I will never give away, trade or sell your email address. You can unsubscribe at any time.

Join 911 other subscribers

Leave a Reply

Close Menu