Android Fingerprint Authentication and android Fingerprint Authentication

Source: Internet
Author: User

Android Fingerprint Authentication and android Fingerprint Authentication

Android Fingerprint Authentication uses the smart phone touch sensor to authenticate the user's identity. Android candy mallow provides an API that makes it easy for users to use touch sensors. The method for accessing the touch sensor before Android reached Mallow is not standard.

For more information, see

Android Fingerprint Authentication has the following advantages:

1. faster and easier to use

2. Security: fingerprint can identify your unique identity

3. online transactions are easier

Before using android fingerprint recognition, you must follow some steps that may seem complicated, but this article will teach you how to implement it step by step.

The result is shown as follows:

Start Android Fingerprint Authentication

As mentioned above, the fingerprint authentication process involves the following steps:

  • Verify whether the lock screen is secure, or in other words, it is protected by a password or mode.
  • Make sure you have a fingerprint registered on your smartphone.
  • Access Android keystore to store keys that encrypt/decrypt objects
  • Generate an encryption key and password
  • Start the authentication process
  • Implements a callback class to handle identity authentication events

That's all. Next we will implement the above steps!

At the beginning, you must first enable the touch sensor and Identity Authentication permissions, and add the following in the Manifest. xml file:

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

Now it is time to create the main activity class to process all the authentication steps.

Verify Android security lock screen

The first step is to check whether the lock screen is secure. You can use KeyguardManager and FingerprintManager to solve this problem. We can get their instances by using the getSystemService class:

// Keyguard ManagerKeyguardManager keyguardManager = (KeyguardManager)                  getSystemService(KEYGUARD_SERVICE);// Fingerprint ManagerfingerprintManager = (FingerprintManager)                  getSystemService(FINGERPRINT_SERVICE);

Now, our certification application can check whether all security judgments are met:

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;}

Note that the application verifies that at least one fingerprint has been registered. Otherwise, the authentication process will not start. The following figure shows an error message if no fingerprint is found.

If everything is ready and the judgment conditions are met, authenticate the application to generate a key and access the Android store.

Access Android keystore and generate a key

The next step is to access the Android keystore and generate a key to encrypt the data. The application is completed separately in a method called generateKey.

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

Then you must obtain the reference of the key generator:

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

Finally, we must 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();

Note that the key must be used for encryption, decryption, and authentication. Finally, the application generates the key (the last line ).

The complete method of the above Code is as follows:

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 an Android Cipher

Once the key is ready, the last step is to use the previously generated key to create an Android Cipher. The code is 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 an Android Fingerprint Authentication app

It is time to combine the previous methods to create an Android fingerprint recognition app. This app is very simple and has only oneMainClassCall the method shown above to start authentication.

@Overrideprotected void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.activity_main);  message = (TextView) findViewById(;  Button btn = (Button) findViewById(;  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);   }  });}

Note: first, the Android app createsCryptoObjectObject To process the authentication process. Then, a button is added to the app. When the user clicks it, the authentication process starts. When the initialization conditions are not met, the button is hidden. The most important thing to note is the new class call.FingerprintHandler. This class is a callback class that receives authentication processing events. In addition, this class starts the doauth method of the authentication process.

Android Fingerprint Authentication callback

The last step is to create a callback class so that we can receive event messages and know when the authentication is successful or except for some problems. This class inherits from FingerprintManager. AuthenticationCallback.

public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {  private TextView tv;  public FingerprintHandler(TextView 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 note. First, doAuth enables authentication. This method contains the CryptoObject object, a cancellation signal and a callback listener. The following figure shows the app response:

In this case, the user completes the authentication using the android Fingerprint Authentication.

How can I test this app on a simulator?

To test this app, if it is possible to use a real machine with sensors, but you can also test the app on the simulator, before using the app, you must configure igure the fingerprint accessing to the Security menu. when the system requires your fingerprint, you must use the adb command to simulate fingerprint contact:

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

Finally, when your fingerprint is fixed, you will receive the following prompt:

Finally, I hope you have mastered the fingerprint recognition api of android and know how to develop a fingerprint recognition app. enjoy

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.