Android fingerprint recognition, read this one is enough


In Android 6.0 (Api23), the Android system added the fingerprint identification API interface, that is FingerprintManager, defined the most basic fingerprint identification interface. However, in AndroidP (Api28), the official no longer recommends the use of @Deprecated.

 

Later, in support v4 library added to FingerprintManagerCompatthe class, I saw his source, in fact, to FingerprintManagerdo a certain amount of packaging, such as making a judgment on the version of the SDK for encryption processing section, etc., in its essence, is used FingerprintManagerto Realize the fingerprint recognition function.

When it comes to AndroidP, FingerprintManagerit is officially retired, and the system has added an BiometricPromptinterface. It can also be seen from the name of the interface 'biometrics'. The future security verification function will not be limited to fingerprints, and facial recognition should also be added.

The following is a demo I wrote to expand to introduce FingerprintManageras well BiometricPrompt.

1. Public part:

1. In general, we write a Manager class. The internal judgment of the Api version is used to implement the adaptation of Api23 and Api28, respectively.

 

Instantiate the two classes according to the Api version

2. Among them, the way to judge the version number is:

 

Determine the version number

3. Secondly, we declared an interface IBiometricPromptImpl, instances of Api28 and Api23 should inherit him

 

interface

3. To judge whether the system supports fingerprint recognition:

 

Four judgments together to make the final judgment

 

Performance in demo

Explain the details of the judgment separately:

isAboveApi23(): I have already mentioned above;
isHardwareDetected(): This is used to judge whether the system hardware supports fingerprint recognition. Here is also a case-by-case judgment, but AndroidP does not yet know what exact method to judge, so temporarily use the same method as AndroidM. The specific implementation of Api23 is in the implementation class, you will see later

isHardwareDetected()

 

hasEnrolledFingerprints(): This method is used to determine whether your device has a fingerprint set in the system settings.
If the user has not set it, you can guide him to set it at this time. However, I checked, and the activity names of the fingerprint setting pages of various manufacturers are not uniform, so one by one adaptation can be a dog. So if you want to boot, you can boot to the security settings page. The security settings page system has a unified Intent, which is [ Settings.ACTION_SECURITY_SETTINGS].

hasEnrolledFingerprints()

 

isKeyguardSecure(): This method is to determine whether the system has a lock screen.
I think this method is tasteless, because now if you set a fingerprint, you must first set a password (PIN / Password / Pattern), then the lock screen must be set accordingly, do n’t understand why Judge this. . .

isKeyguardSecure ()

 

2. BiometricPromptApi23: Api23 ~ Api27

1、authenticate()

Looking at BiometricPromptApi23.javabefore the contents inside, we first need to look at the key method of fingerprint identification: authenticate().

authenticate method


The above picture is the description in Google's api document. Now let's explain each of these parameters one by one:
cryptoThis is an object of encryption type, and the fingerprint scanner will use this object to judge the validity of the authentication result. This object can be null, but in this case, it means the result of the app's unconditional trust authentication. Although in theory this process may be attacked and data can be tampered with, this is the risk the app must bear in this case. Therefore, it is recommended not to set this parameter to null. The instantiation of this class is a bit troublesome. It is mainly implemented using the security interface of javax. Later in my demo program, a helper class ( CryptoObjectHelper.java) will be given . This class encapsulates the internal implementation logic. Developers can use my class to simplify instantiation the process of.
②. cancelThis is CancellationSignalan object of the class. This object is used to cancel the current scanning operation when the fingerprint reader scans the user's fingerprint. If it is not canceled, the fingerprint scanner will transplant the scan until it times out (generally 30s, depending on Specific manufacturers to achieve), this will consume more power. It is recommended not to set this parameter to null.
③. flagsIdentification bit, according to the document description above, this bit should be 0 temporarily, this flag bit should be reserved for future use.
④. callbackThis is FingerprintManager.AuthenticationCallbackthe object of the class . This is the most important parameter except the first parameter in this interface. We will introduce it in detail later. This parameter cannot be NULL.
⑤. handlerThis is an object of class Handler. If this parameter is not null, then FingerprintManagerthe looper in this handler will be used to process messages from the fingerprint recognition hardware. Generally speaking, development does not need to provide this parameter, you can directly set to null, because FingerprintManagerthe main looper of the app will be used by default.

 

2. Callback method after fingerprint authentication

What I will introduce here is the above mentioned FingerprintManager.AuthenticationCallback, because the process of scanning fingerprints and authentication are completed in another process, so we need to adopt an asynchronous method, after the operation is completed, let the system callback to us, callback method Is AuthenticationCallbackthe 4 methods in the class

Four callback methods


Below we briefly introduce the meaning of these interfaces:
①. OnAuthenticationError(int errorCode, ICharSequence errString)This interface will be called only when there is an unrecoverable error in the system fingerprint authentication, and the parameter errorCode gives the error code, which identifies the cause of the error.
Before AndroidP, after this method is called back, the fingerprint recognition sensor will be turned off, that is, if you put your finger on the fingerprint hardware, there will be no response. At this time, you need to prompt the user to close the fingerprint identification pop-up window, or use a password to pay, etc.
Under what circumstances will the error be called back? For example, fingerprint recognition error 5 times in succession, fingerprint hardware is not available, etc.
②. OnAuthenticationFailed()This interface will be called back only when the system fingerprint authentication fails. Note that the authentication failure here is not the same as the authentication error above, although the results cannot be authenticated. Authentication failure means that all the information is collected completely and there is no abnormality, but this fingerprint does not match the previously registered fingerprint; but authentication error means that an error occurred during the collection or authentication process, such as abnormal operation of the fingerprint sensor Wait. That is to say, authentication failure is a normal situation that can be expected, and authentication error is an unexpected situation.
③. The OnAuthenticationHelp(int helpMsgId, ICharSequence helpString)above authentication failure is an abnormal situation in the authentication process. We said that the situation is due to an unrecoverable error, and our OnAuthenticationHelp method is called only when there is an exception that can be responded to. What are the recoverable exceptions? A common example is: the finger moves too fast. When we put the finger on the sensor, if we remove the finger quickly, the fingerprint sensor may only collect part of the information, so the authentication will fail. But this error can be recovered, so as long as the user is prompted to press the fingerprint again, and do not remove it too quickly, it can be solved.
④.OnAuthenticationSucceeded(FingerprintManagerCompati.AuthenticationResult result)This interface will be called back after successful authentication. We can prompt user authentication success in this method. It needs to be explained here. If we call CryptoObject above when we call authenticate, then we can get the Cypher object through AuthenticationResult in this method and then call its doFinal method. The doFinal method checks whether the result will be intercepted or tampered with, and if so, throws an exception. When we find these exceptions, we should treat the authentication as a failure. It is recommended that everyone do this for security.

 

 

Ok, let's take a look at the implementation in my demo

 

 

This authenticate method rewrites the method in the IBiometricPromptImpl interface. I have added a comment to the important part. The rest should be understood. If you do n’t understand it, you can ask in the comment ~~ 【Manual smile face☺】

 

A callback class that implements fingerprint recognition

 

Open the dialog and wait for recognition

 

Recognition error

 

Recognize successfully, then close the dialog automatically

The following are the realization of two judgment methods

 

Determine if hardware support and fingerprint are set

3. BiometricPromptApi28: for Api28 and later platforms

In AndroidP, the original fingerprintManagerwill be BiometricPromptreplaced by the class. Google aims to unify the way of biometrics (although there is no iris, facial recognition, etc. in the api), including the UI, the UI does not allow customization, and must be used BiometricPrompt.Builderto create Dialog box, in which you can customize title, subtitle, description and a NegativeButton (that is, cancel button).

The performance of the system dialog in AndroidP

 

Create dialog

There is only one NegativeButton, which is awkward, which means that only buttons can exist on the interface. If I want to add a UsePassword button, I can only change this cancel button. . . (However, you can rest assured that although the source of AndroidP has not been released yet, I asked my old colleague to help me find the source code of BiometricPrompt. There is still a PositiveButton in it, but the api should not be released yet)

Let's take a look at the implementation code: the
construction method, creating the signature object (for encryption that is not well understood, which great god can be popularized)

 

Construction method

 

Much like Api23, implement authenticate method

 

authenticate method


Callback

Callback method

Attach the source code: If you have any questions, you can explore: https://github.com/gaoyangcr7/BiometricPromptDemo

common problem:

1,报错 java.io.IOException: Failed to find byte code for android/hardware/biometrics/BiometricPrompt$AuthenticationCallback

Just go to the settings and turn off InstantRun.

2,报错 java.lang.RuntimeException: java.security.InvalidAlgorithmParameterException: java.lang.IllegalStateException: At least one fingerprint must be enrolled to create keys requiring user authentication for every use at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2913)

  1. This exception does not appear on the emulator, the real machine will also have nothing to do with the device, it is suspected to be a pit of Google API
  2. My approach is to catch the exception, friendly remind the user does not support fingerprints, and guide users to use other verification methods
  3. The alternative method is to directly use keyless authentication, but there are certain security risks. At present, we are observing the frequency of online users, and then consider whether to use an alternative solution.

1. When you click "Turn On Identification" on Xiaomi 6, 6X mobile phone, you will go through onAuthenticationHelp first, helpCode = 1021, helpString is empty

It should be that MIUI modified the underlying time on its own. You can try to call the authenticate method later (not tested, there is no Mi phone on hand)



Author: UP7CR
link: https: //www.jianshu.com/p/1eae12582a31
Source: Jane books
are copyrighted by the author. For commercial reproduction, please contact the author for authorization, and for non-commercial reproduction, please indicate the source.

Published 31 original articles · Likes6 · Visitors 10,000+

Guess you like

Origin blog.csdn.net/u012824529/article/details/103744308