Android Core

Android fingerprint authentication tutorial

Android fingerprint authentication uses smartphone touch sensor to authenticate the user. Android Marshmallow has introduced a set of API that makes easy to use touch sensor. Before Android Marshmallow the method to access to touch sensor was not standard.

There are several benefits of using Android fingerprint authentication:

  • Fast and easy to use
  • Secure: fingerprint uniquely identifies you
  • Online transaction are safer

There are several steps you have to follow before using Android fingerprint authentication and at the beginning, it could seem really complex but this tutorial will guide you step by step.

The final results is an Android app that uses fingerprint authentication as shown below:

android_fingerprint_authentication-576x1024

Getting started with Android fingerprint authentication

As said before, there are several steps to follow to enable fingerprint authentication:

  • Verify that the lock screen is secure, or in other words, it is protected by PIN, password or pattern
  • Verify that at least one fingerprint is registered on the smartphone
  • Get access to Android keystore to store the key used to encrypt/decrypt an object
  • Generate an encryption key and the Cipher
  • Start the authentication process
  • Implement a callback class to handle authentication events

That’s all!!..We will implement these steps.

Before starting, it is important to request the permission to use the touch sensor and the fingerprint authentication. So in the Manifest.xml, we add:

<uses-permission android:name="android.permission.USE_FINGERPRINT" />

Now it is time to create our main activity class that handles all the authentication process.

Verify secure lock screen in Android

The first step is verifying the secure lock screen. This can be done KeyguardManager and FingerprintManager. We get an instance of these two managers using getSystemService:

// Keyguard Manager
KeyguardManager keyguardManager = (KeyguardManager)
                  getSystemService(KEYGUARD_SERVICE);

// Fingerprint Manager
fingerprintManager = (FingerprintManager) 
                 getSystemService(FINGERPRINT_SERVICE);

Now, our authentication app can check if all the secure conditions are satisfied:

private boolean checkFinger() {

  // Keyguard Manager
  KeyguardManager keyguardManager = (KeyguardManager)
           getSystemService(KEYGUARD_SERVICE);

  // Fingerprint Manager
  fingerprintManager = (FingerprintManager) 
         getSystemService(FINGERPRINT_SERVICE);

  try {
   // Check if the fingerprint sensor is present
   if (!fingerprintManager.isHardwareDetected()) {
     // Update the UI with a message
     message.setText("Fingerprint authentication not supported");
     return false;
   }

   if (!fingerprintManager.hasEnrolledFingerprints()) {
     message.setText("No fingerprint configured.");
     return false;
   }

   if (!keyguardManager.isKeyguardSecure()) {
     message.setText("Secure lock screen not enabled");
     return false;
   }
 }
 catch(SecurityException se) {
   se.printStackTrace();
 }
 return true;
}

Notice that, the authentication app verifies that, at least, one fingerprint is registered otherwise the authentication process can not start.

The image below shows a message error when the app does not find a fingerprint registered.

android_fingerprint_not_supported-576x1024

If everything is ok and all the conditions are satisfied, the authentication app generates the key and accesses to the Android store.

android_fingerprint_authentication-576x1024

Access to Android keystore and generate the key

The next step is accessing to the Android keystore and generate the key to encrypt the data. The app does it in a separate method called generateKey().

// Get the reference to the key store
keyStore = KeyStore.getInstance("AndroidKeyStore");

then it is necessary to get the reference to the key generator:

// Key generator to generate the key
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, 
                 "AndroidKeyStore");

and finally, we have to initialize the key generator:

keyGenerator.init( new
  KeyGenParameterSpec.Builder(KEY_NAME,
  KeyProperties.PURPOSE_ENCRYPT |
  KeyProperties.PURPOSE_DECRYPT)
  .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
  .setUserAuthenticationRequired(true)
  .setEncryptionPaddings(
    KeyProperties.ENCRYPTION_PADDING_PKCS7)
  .build());

 keyGenerator.generateKey();

Notice that we specify the usage of the key: encrypt and decrypt and that the authentication is required to use the key itself. At the end, the app generates the key (last line).

Below, the complete method:

private void generateKey() throws FingerprintException {
  try {
    // 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( new
       KeyGenParameterSpec.Builder(KEY_NAME,
      KeyProperties.PURPOSE_ENCRYPT |
      KeyProperties.PURPOSE_DECRYPT)
     .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
     .setUserAuthenticationRequired(true)
     .setEncryptionPaddings(
        KeyProperties.ENCRYPTION_PADDING_PKCS7)
    .build());

    keyGenerator.generateKey();
  }
  catch(KeyStoreException
   | NoSuchAlgorithmException
   | NoSuchProviderException
   | InvalidAlgorithmParameterException
   | CertificateException
   | IOException exc) {
    exc.printStackTrace();
    throw new FingerprintException(exc);
 }
}

Create the Android Cipher

Once the key is ready, the last step is creating the Android Cipher that uses the key, we have generated before. The source code is very simple:

private Cipher generateCipher() throws FingerprintException {
  try {
    Cipher cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/"
     + KeyProperties.BLOCK_MODE_CBC + "/"
     + KeyProperties.ENCRYPTION_PADDING_PKCS7);
     SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
             null);
     cipher.init(Cipher.ENCRYPT_MODE, key);
     return cipher;
  }
  catch (NoSuchAlgorithmException
     | NoSuchPaddingException
     | InvalidKeyException
     | UnrecoverableKeyException
     | KeyStoreException exc) {
      exc.printStackTrace();
      throw new FingerprintException(exc);
  }
}

Build the Android fingerprint app

It is time to assemble all these methods and create the Android fingerprint authentication app. This app is very simple and it has a MainClass that calls the methods shown above and starts the authentication process.

@Override
protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  message = (TextView) findViewById(R.id.fingerStatus);
  Button btn = (Button) findViewById(R.id.authBtn);

  final FingerprintHandler fph = new FingerprintHandler(message);

  if (!checkFinger()) {
    btn.setEnabled(false);
  }
  else {
    // We are ready to set up the cipher and the key
   try {
     generateKey();
     Cipher cipher = generateCipher();
     cryptoObject =
      new FingerprintManager.CryptoObject(cipher);
  }
  catch(FingerprintException fpe) {
   // Handle exception
   btn.setEnabled(false);
  }
 }

 btn.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    message.setText("Swipe your finger");
    fph.doAuth(fingerprintManager, cryptoObject);
   }
  });
}

There are a few things to notice. First of all, the Android app creates  a CryptoObject that is used in the authentication process. Moreover, the app shows a button and when the user clicks on it the authentication process starts. The button is disabled if the initial conditions described above are not satisfied. The most important thing to notice is  new class called FingerprintHandler. This class is a callback class that receives the authentication process events. Moreover, this class starts the authentication process with doAuth method.

Android fingerprint authentication callback

The last step is creating the callback class so that we can receive event notification and we can know when the authentication succeeded or something went wrong. This class extends FingerprintManager.AuthenticationCallback.

public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
  private TextView tv;

  public FingerprintHandler(TextView tv) {
    this.tv = tv;
  }

  @Override
  public void onAuthenticationError(int errorCode, CharSequence errString) {
    super.onAuthenticationError(errorCode, errString);
    tv.setText("Auth error");
  }

  @Override
  public void onAuthenticationHelp(int helpCode, CharSequence helpString) {
    super.onAuthenticationHelp(helpCode, helpString);
  }

  @Override
  public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
    super.onAuthenticationSucceeded(result);
    tv.setText("auth ok");
    tv.setTextColor(tv.getContext().getResources().
                getColor(android.R.color.holo_green_light));
  }

  @Override
  public void onAuthenticationFailed() {
    super.onAuthenticationFailed();
  }

  public void doAuth(FingerprintManager manager, 
                     FingerprintManager.CryptoObject obj) {
   CancellationSignal signal = new CancellationSignal();

   try {
    manager.authenticate(obj, signal, 0, this, null);
   }
   catch(SecurityException sce) {}
 }
}

There are some important methods to notice. First of all, the doAuth that starts the authentication process. This method has the CryptoObject, a cancellation signal and the callback listener (this class). The image below shows the app in action:

android_authentication_with_finger-576x1024

In this case, the user is authenticated using Android fingerprint authentication.

How to test the app in Android emulator

To test the app, it is possible to use a real device that has a touch sensor. Anyway, it is possible to test the app in the emulator too. Before starting to use the app, you have to configure the fingerprint accessing to the Security menu. When the system asks for fingerprint you have to use the adb command to emulate the finger touch:

adb -e emu finger touch id(like 1,2, ecc.)

Finally, when the configuration is done, you get the message shown below:

android_fingerprint_config-1-576x1024

At the end of this post, hopefully, you gained the knowledge about Android fingerprint api and how to develop an Android fingerprint example app.

Reference: Android fingerprint authentication tutorial from our JCG partner Francesco Azzola at the Surviving w/ Android blog.

Francesco Azzola

He's a senior software engineer with more than 15 yrs old experience in JEE architecture. He's SCEA certified (Sun Certified Enterprise Architect), SCWCD, SCJP. He is an android enthusiast and he has worked for long time in the mobile development field.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button