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).
- Go to your Emulator -> Settings -> Security -> FingerPrint -> Add -> Set your PIN (for example 1234) -> Next Find your Sensor.
- 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
- Add your frintprint by typing new cmd (adb -e emu finger touch 1234abc). In this example I am setting up fingerprint 1234abc.
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
- <?xml version="1.0" encoding="utf-8" ?>
- <resources>
- <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
- <item name="colorPrimary">#263237</item>
- <item name="colorPrimaryDark">#263237</item>
- <item name="colorAccent">#1e282d</item>
- </style>
- </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
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:layout_width="match_parent"
- android:layout_height="match_parent"
- android:background="#263237"
- android:padding="16dp">
- <ImageView
- android:id="@+id/fingerImage"
- android:src="@drawable/fingerprint"
- android:layout_centerInParent="true"
- android:layout_width="150dp"
- android:layout_height="150dp" />
- <TextView
- android:layout_below="@+id/fingerImage"
- android:textColor="#F5F5F5"
- android:textSize="20sp"
- android:text="Please place your fingertip on the scanner to verify your identity"
- android:layout_centerHorizontal="true"
- android:textAlignment="center"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </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
- <?xml version="1.0" encoding="utf-8"?>
- <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
- android:padding="16dp"
- android:layout_width="match_parent"
- android:layout_height="match_parent">
- <TextView
- android:textColor="#95aab4"
- android:textSize="20sp"
- android:text="You have successfully logged in with Fingerprint Authentication"
- android:layout_centerHorizontal="true"
- android:textAlignment="center"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content" />
- </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
- using Android.App;
- using Android.OS;
- using Android.Support.V7.App;
- namespace FingerAuth
- {
- [Activity(Label = "HomeActivity" , Theme ="@style/AppTheme")]
- public class HomeActivity : AppCompatActivity
- {
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
-
- SetContentView(Resource.Layout.Home);
- }
- }
- }
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
- using Android.App;
- using Android.Widget;
- using Android.OS;
- using Android.Support.V7.App;
- using Java.Security;
- using Javax.Crypto;
- using Android.Hardware.Fingerprints;
- using Android.Support.V4.App;
- using Android;
- using System;
- using Android.Security.Keystore;
- namespace FingerAuth
- {
- [Activity(Label = "FingerAuth", MainLauncher = true, Theme ="@style/AppTheme")]
- public class MainActivity : AppCompatActivity
- {
- private KeyStore keyStore;
- private Cipher cipher;
- private string KEY_NAME = "Ahsan";
- protected override void OnCreate(Bundle savedInstanceState)
- {
- base.OnCreate(savedInstanceState);
-
- SetContentView(Resource.Layout.Main);
- KeyguardManager keyguardManager = (KeyguardManager)GetSystemService(KeyguardService);
- FingerprintManager fingerprintManager = (FingerprintManager)GetSystemService(FingerprintService);
- if (ActivityCompat.CheckSelfPermission(this, Manifest.Permission.UseFingerprint)
- != (int)Android.Content.PM.Permission.Granted)
- return;
- if (!fingerprintManager.IsHardwareDetected)
- Toast.MakeText(this, "FingerPrint authentication permission not enable", ToastLength.Short).Show();
- else
- {
- if(!fingerprintManager.HasEnrolledFingerprints)
- Toast.MakeText(this, "Register at least one fingerprint in Settings", ToastLength.Short).Show();
- else
- {
- if (!keyguardManager.IsKeyguardSecure)
- Toast.MakeText(this, "Lock screen security not enable in Settings", ToastLength.Short).Show();
- else
- GenKey();
- if (CipherInit())
- {
- FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher);
- FingerprintHandler handler = new FingerprintHandler(this);
- handler.StartAuthentication(fingerprintManager, cryptoObject);
- }
- }
- }
- }
- private bool CipherInit()
- {
- try
- {
- cipher = Cipher.GetInstance(KeyProperties.KeyAlgorithmAes
- + "/"
- + KeyProperties.BlockModeCbc
- + "/"
- + KeyProperties.EncryptionPaddingPkcs7);
- keyStore.Load(null);
- IKey key = (IKey)keyStore.GetKey(KEY_NAME, null);
- cipher.Init(CipherMode.EncryptMode, key);
- return true;
- }
- catch(Exception ex) { return false; }
- }
- private void GenKey()
- {
- keyStore = KeyStore.GetInstance("AndroidKeyStore");
- KeyGenerator keyGenerator = null;
- keyGenerator = KeyGenerator.GetInstance(KeyProperties.KeyAlgorithmAes, "AndroidKeyStore");
- keyStore.Load(null);
- keyGenerator.Init(new KeyGenParameterSpec.Builder(KEY_NAME, KeyStorePurpose.Encrypt | KeyStorePurpose.Decrypt)
- .SetBlockModes(KeyProperties.BlockModeCbc)
- .SetUserAuthenticationRequired(true)
- .SetEncryptionPaddings(KeyProperties
- .EncryptionPaddingPkcs7).Build());
- keyGenerator.GenerateKey();
- }
- }
- }
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
- using System;
- using Android;
- using Android.Content;
- using Android.Hardware.Fingerprints;
- using Android.OS;
- using Android.Support.V4.App;
- using Android.Widget;
- namespace FingerAuth
- {
- internal class FingerprintHandler : FingerprintManager.AuthenticationCallback
- {
- private Context mainActivity;
- public FingerprintHandler(Context mainActivity)
- {
- this.mainActivity = mainActivity;
- }
- internal void StartAuthentication(FingerprintManager fingerprintManager, FingerprintManager.CryptoObject cryptoObject)
- {
- CancellationSignal cancellationSignal = new CancellationSignal();
- if (ActivityCompat.CheckSelfPermission(mainActivity, Manifest.Permission.UseFingerprint)
- != (int)Android.Content.PM.Permission.Granted)
- return;
- fingerprintManager.Authenticate(cryptoObject, cancellationSignal, 0, this, null);
- }
- public override void OnAuthenticationFailed()
- {
- Toast.MakeText(mainActivity, "Fingerprint Authentication failed!",ToastLength.Long).Show();
- }
- public override void OnAuthenticationSucceeded(FingerprintManager.AuthenticationResult result)
- {
- mainActivity.StartActivity(new Intent(mainActivity, typeof(HomeActivity)));
- }
- }
- }
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" />