Xamarin.Android - Finger Print Authentication

Introduction

In this article, I’m going to show you exactly how to implement fingerprint authentication in your own apps, by walking you through the process of creating a sample app that registers when the user places their fingertip against their device’s touch sensor, processes their input, and then displays a range of toasts depending on whether the fingerprint authentication has succeeded or failed. We’ll also be looking at how to test fingerprint authentication on Android Virtual Devices (AVDs) that don’t feature a physical touch sensor.

The prerequisites
  • Android Support Library v7 AppCompat
  • Fingerprint Image
The steps given below are required to be followed in order to create a Fingerprint Authentication app in Xamarin.Android, using Visual Studio.
 
Step 1 - Creating Fingerprint Authentication Project
 
Let's create your Android solution in Visual Studio or Xamarin Studio. Select Android and from list choose Android Blank App give it a name like, FingerAuth.
 
Step 2 - Add Fingerprint to Emulator
 
First we will add our fingerprint to AVD - (I suggest you use Android Studio's Emulator for this example).
  1. Go to your Emulator -> Settings -> Security -> FingerPrint -> Add -> Set your PIN (for example 1234) -> Next Find your Sensor.

  2. Now go to Start and open Cmd as Administrator then change directory (cd) so it’s pointing at your Android SDK download; specifically, the Android/sdk/platform-tools folder.

    My command looks like this,

    cd C:\Program Files (x86)\Android\android-sdk\platform-tools

  3. Add your frintprint by typing new cmd (adb -e emu finger touch 1234abc). In this example I am setting up fingerprint 1234abc.

Step 3 - Add Android Support v7 AppCompat Library
 
First of all, in References add a reference Android.Support.v7. AppCompat using NuGet Package Manager, as shown below.
 
 
 
Step 4 - Add Finger Print Image
 
Open Solution Explorer -> Project Name -> Resources-> Drawable. Fingerprint image paste into drawable folder.
 
 
Step 5 - Add XML File
 
After successful installation of AppCompat, add a new XML file. For that, go to Solution Explorer-> Project Name-> Resources-> Values-> Right-click to add a new item, select XML, and give it a name, such as Styles.xml. Open this XML file and add the following code.
 
(Folder Name: values, File Name: Styles.xml)
 
XML Code
  1. <?xml version="1.0" encoding="utf-8" ?>   
  2. <resources>  
  3. <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">  
  4.   <item name="colorPrimary">#263237</item>  
  5.   <item name="colorPrimaryDark">#263237</item>  
  6.   <item name="colorAccent">#1e282d</item>  
  7. </style>    
  8. </resources>  
Step 6 - Main Layout
 
Open Solution Explorer-> Project Name-> Resources-> Layout-> Main.axml. Open this main layout file and add the following code.
 
(File Name: Main.axml , Folder Name: Layout)
 
XML Code
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:background="#263237"  
  6.     android:padding="16dp">  
  7.     <ImageView  
  8.         android:id="@+id/fingerImage"  
  9.         android:src="@drawable/fingerprint"  
  10.         android:layout_centerInParent="true"  
  11.         android:layout_width="150dp"  
  12.         android:layout_height="150dp" />  
  13.     <TextView  
  14.         android:layout_below="@+id/fingerImage"  
  15.         android:textColor="#F5F5F5"  
  16.         android:textSize="20sp"  
  17.         android:text="Please place your fingertip on the scanner to verify your identity"  
  18.         android:layout_centerHorizontal="true"  
  19.         android:textAlignment="center"  
  20.         android:layout_width="wrap_content"  
  21.         android:layout_height="wrap_content" />  
  22. </RelativeLayout>  
Step 7 - Add Home Layout
 
Next, add a new layout by going to Solution Explorer-> Project Name-> Resources-> Layout. Right-click to add a new item, select Layout, and give it a name, such as Home.axml. Open this layout file and add the following code.
 
(Folder Name: Layout , File Name: Home.axml)
 
XML Code
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     android:padding="16dp"  
  4.     android:layout_width="match_parent"  
  5.     android:layout_height="match_parent">  
  6.     <TextView  
  7.         android:textColor="#95aab4"  
  8.         android:textSize="20sp"  
  9.         android:text="You have successfully logged in with Fingerprint Authentication"  
  10.         android:layout_centerHorizontal="true"  
  11.         android:textAlignment="center"  
  12.         android:layout_width="wrap_content"  
  13.         android:layout_height="wrap_content" />  
  14. </RelativeLayout>  
Step 8 - Create Home Activity
 
Add a new Activity. For this, open Solution Explorer-> Project Name-> right click to add a new item and select Activity. Give it a name like Home and add the following code putting appropriate namespaces.
 
(FileName: Home)
 
C# Code
  1. using Android.App;  
  2. using Android.OS;  
  3. using Android.Support.V7.App;  
  4. namespace FingerAuth  
  5. {  
  6.     [Activity(Label = "HomeActivity" , Theme ="@style/AppTheme")]  
  7.     public class HomeActivity : AppCompatActivity  
  8.     {  
  9.         protected override void OnCreate(Bundle savedInstanceState)  
  10.         {  
  11.             base.OnCreate(savedInstanceState);  
  12.             // Create your application here  
  13.             SetContentView(Resource.Layout.Home);  
  14.         }  
  15.     }  
  16. }  
Step 9 - Main Activity Class
 
Now, go to Solution Explorer-> Project Name-> MainActivity and add the following code with appropriate namespaces.
 
(FileName: MainActivity)
 
C# Code
  1. using Android.App;  
  2. using Android.Widget;  
  3. using Android.OS;  
  4. using Android.Support.V7.App;  
  5. using Java.Security;  
  6. using Javax.Crypto;  
  7. using Android.Hardware.Fingerprints;  
  8. using Android.Support.V4.App;  
  9. using Android;  
  10. using System;  
  11. using Android.Security.Keystore;  
  12. namespace FingerAuth  
  13. {  
  14.     [Activity(Label = "FingerAuth", MainLauncher = true, Theme ="@style/AppTheme")]  
  15.     public class MainActivity : AppCompatActivity  
  16.     {  
  17.         private KeyStore keyStore;  
  18.         private Cipher cipher;  
  19.         private string KEY_NAME = "Ahsan";  
  20.         protected override void OnCreate(Bundle savedInstanceState)  
  21.         {  
  22.             base.OnCreate(savedInstanceState);  
  23.             // Set our view from the "main" layout resource  
  24.             SetContentView(Resource.Layout.Main);  
  25.             KeyguardManager keyguardManager = (KeyguardManager)GetSystemService(KeyguardService);  
  26.             FingerprintManager fingerprintManager = (FingerprintManager)GetSystemService(FingerprintService);  
  27.             if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.UseFingerprint)  
  28.                 != (int)Android.Content.PM.Permission.Granted)  
  29.                 return;  
  30.             if (!fingerprintManager.IsHardwareDetected)  
  31.                 Toast.MakeText(this"FingerPrint authentication permission not enable", ToastLength.Short).Show();  
  32.             else  
  33.             {  
  34.                 if(!fingerprintManager.HasEnrolledFingerprints)  
  35.                     Toast.MakeText(this"Register at least one fingerprint in Settings", ToastLength.Short).Show();  
  36.                 else  
  37.                 {  
  38.                     if (!keyguardManager.IsKeyguardSecure)  
  39.                         Toast.MakeText(this"Lock screen security not enable in Settings", ToastLength.Short).Show();  
  40.                     else  
  41.                         GenKey();  
  42.                     if (CipherInit())  
  43.                     {  
  44.                         FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher);  
  45.                         FingerprintHandler handler = new FingerprintHandler(this);  
  46.                         handler.StartAuthentication(fingerprintManager, cryptoObject);  
  47.                     }  
  48.                 }  
  49.             }  
  50.         }  
  51.         private bool CipherInit()  
  52.         {  
  53.             try  
  54.             {  
  55.                 cipher = Cipher.GetInstance(KeyProperties.KeyAlgorithmAes  
  56.                     + "/"  
  57.                     + KeyProperties.BlockModeCbc  
  58.                     + "/"  
  59.                     + KeyProperties.EncryptionPaddingPkcs7);  
  60.                 keyStore.Load(null);  
  61.                 IKey key = (IKey)keyStore.GetKey(KEY_NAME, null);  
  62.                 cipher.Init(CipherMode.EncryptMode, key);  
  63.                 return true;  
  64.             }  
  65.             catch(Exception ex) { return false; }  
  66.         }  
  67.         private void GenKey()  
  68.         {  
  69.             keyStore = KeyStore.GetInstance("AndroidKeyStore");  
  70.             KeyGenerator keyGenerator = null;  
  71.             keyGenerator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, "AndroidKeyStore");  
  72.             keyStore.Load(null);  
  73.             keyGenerator.Init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)  
  74.                 .SetBlockModes(KeyProperties.BlockModeCbc)  
  75.                 .SetUserAuthenticationRequired(true)  
  76.                 .SetEncryptionPaddings(KeyProperties  
  77.                 .EncryptionPaddingPkcs7).Build());  
  78.             keyGenerator.GenerateKey();  
  79.         }  
  80.     }  
  81. }  
Step 10 - Writing FingerprintHandler Class
 
Go to Solution Explorer-> Project Name and right-click. Select Add -> New Item-> Class. Give it a name like FingerprintHandler.cs and write the following code with appropriate namespaces.
 
(File Name: FingerprintHandler.cs)
 
C# Code
  1. using System;  
  2. using Android;  
  3. using Android.Content;  
  4. using Android.Hardware.Fingerprints;  
  5. using Android.OS;  
  6. using Android.Support.V4.App;  
  7. using Android.Widget;  
  8. namespace FingerAuth  
  9. {  
  10.     internal class FingerprintHandler : FingerprintManager.AuthenticationCallback  
  11.     {  
  12.         private Context mainActivity;  
  13.         public FingerprintHandler(Context mainActivity)  
  14.         {  
  15.             this.mainActivity = mainActivity;  
  16.         }  
  17.         internal void StartAuthentication(FingerprintManager fingerprintManager, FingerprintManager.CryptoObject cryptoObject)  
  18.         {  
  19.             CancellationSignal cancellationSignal = new CancellationSignal();  
  20.             if (ActivityCompat.CheckSelfPermission(mainActivity, Manifest.Permission.UseFingerprint)  
  21.                 != (int)Android.Content.PM.Permission.Granted)  
  22.                 return;  
  23.             fingerprintManager.Authenticate(cryptoObject, cancellationSignal, 0, thisnull);  
  24.         }  
  25.         public override void OnAuthenticationFailed()  
  26.         {  
  27.             Toast.MakeText(mainActivity, "Fingerprint Authentication failed!",ToastLength.Long).Show();  
  28.         }  
  29.         public override void OnAuthenticationSucceeded(FingerprintManager.AuthenticationResult result)  
  30.         {  
  31.             mainActivity.StartActivity(new Intent(mainActivity, typeof(HomeActivity)));  
  32.         }  
  33.     }  
  34. }  
Step 10 - Permission From Device
 
We need a permission from the device because we shall be using the device’s finger print. Please add Fingerprint permission to your AndroidManifest.xml.Let's open Solution Explorer-> Properties-> AndroidManifest and let's add the code inside application tags.

<uses-permission android:name="android.permission.USE_FINGERPRINT" /> 
 
Output 
 
 
 
Summary
 
This was the process of creating a Fingerprint Auth app in Xamarin.Android, using Visual Studio. Please share your comments and feedback.

Up Next
    Ebook Download
    View all
    Learn
    View all