Android 6.0 fingerprint app development case

In Android 6.0, Google finally added fingerprint recognition support to the Android system. This function has been implemented on the iPhone for a long time, and it has been implemented internally in the customized ROM of many manufacturers. This function came a little late. The nexus 5x and nexus 6p newly released by Google carry a fingerprint identification chip on the back of the device, as shown in the following figure (the picture comes from the network):

The equipment in the author's hand is the black nexus 5x in the picture. It is said that this machine is very beautiful! It feels great! No more nonsense. Next, I'll give a demo app for fingerprint recognition and explain in detail how to develop a fingerprint recognition app based on Google API. The source code of demo is on my GitHub: https://github.com/CreateChance/AndroidFingerPrintDemo

Fingerprint identification interface in Android M

This is the first thing to pay attention to. Before we actually start writing apps, we need to know what fingerprint identification interfaces the latest platform provides for us. All fingerprint identification interfaces are on Android hardware. There are not many classes in the fingerprint package, as follows:

API doc link address: https://developer.android.com/reference/android/hardware/fingerprint/package-summary.html You'd better FQ yourself. In the above figure, we can see that there are four classes in this package. Let's briefly introduce them: 1 Fingerprint Manager: mainly used to coordinate the management and access of fingerprint identification hardware devices 2 FingerprintManager. Authenticationcallback is a callback interface. After fingerprint authentication, the system will call back this interface to inform the app of the authentication result. 3 FingerprintManager. Authenticationresult this is a class representing the authentication result, which will be given as a parameter in the callback interface. 4 FingerprintManager. Cryptoobject is an encrypted object class used to ensure the security of authentication. This is a key point. We will analyze it below. Well, here we briefly know that there are not many fingerprint identification interfaces given by Android 6.0, which can be said to be short and capable.

Start developing a fingerprint identification app

Now, we're going to write a fingerprint identification app using the above interface. The app interface is very simple, just an activity. Fingerprint identification will be activated on this activity, and then the user will be prompted to press the fingerprint, and the authentication results will be displayed.

start

Before we start, we need to know the basic steps of using fingerprint recognition hardware: 1 At androidmanifest The following permissions are declared in XML:

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

2. Get the object reference of fingerprint manager 3 During operation, check the compatibility of the fingerprint identification device, such as whether there is a fingerprint identification device. Let's talk about the above steps in detail:

Claim authority

This step is relatively simple, just in the Android manifest Just add the permissions mentioned above to the XML.

Get the fingerprint manager object reference

This is a common way to obtain system service objects in app development, as follows:

The above two methods are given. The first is to obtain compatible object references through the V4 support package, which is the practice implemented by Google; There is also the direct use of interfaces in the API 23 framework to obtain object references.

Check operating conditions

To make our fingerprint recognition app work normally, there are some conditions that must be met.

1). API level 23 fingerprint identification API is added to API level 23, that is, Android 6.0, so our app must run on this system version. Therefore, Google recommends using the Android support library V4 package to obtain the fingerprint managercompact object, because this package will check the version of the current system platform when obtaining it.

2). Hardware fingerprint identification definitely requires fingerprint identification hardware on your device, so you need to check whether there is fingerprint identification hardware in the system during operation:

Call the above interface to know whether there is such hardware in the system. If not, you need to do some appropriate things, such as reminding the user that there is no fingerprint recognition hardware in the current system.

3). The current device must be in security protection. This condition means that your device must be protected with a screen lock. The screen lock can be password, pin or pattern. Why? Because Google's native logic is that if you want to use fingerprint identification, you must first enable the screen lock. This is the same as the smart lock logic in Android 5.0. This is because Google believes that the current fingerprint identification technology still has shortcomings and the security can not be compared with the traditional way. We can use the following code to check whether the current device is in security protection:

We can know by using the iskeyguardsecure interface of keyguardmanager.

4). Is there a registered fingerprint in the system? In Android 6.0, if an ordinary app wants to use the fingerprint identification function, the user must first register at least one fingerprint in setting, otherwise it cannot be used. Therefore, we need to check whether there is registered fingerprint information in the current system:

If the user has not registered a fingerprint, our app can prompt the user: if you want to use the fingerprint function, please register your fingerprint in setting. If Bluetooth or other devices are developed here, you know that you can start the interface opened by Bluetooth by sending an intent, as long as the Bluetooth management permission is declared. However, up to now, Google still does not have the permission to allow ordinary apps to start the fingerprint registration interface. We can see this from the androidmanifest of setting:

Most of the fingerprint setting interfaces do not have an export, only setupfingerprint enrollintroduction, but this interface requires Android permission. MANAGE_ The permission of finderprint can only be used by system apps, which directly prevents third-party apps from starting this interface. (I wonder if Google will open this permission in the future...)

A good app should check the above conditions at runtime to prevent unexpected errors in the app.

Scan user pressed fingerprint

To start scanning the fingerprint pressed by the user is very simple. Just call the authenticate method of fingerprint manager. Now let's take a look at this interface:

The above figure is the description in Google's API document. Now let's explain what these parameters are one by one: 1 Crypto is an object of encryption class. The fingerprint scanner will use this object to judge the legitimacy of the authentication result. This object can be null, but in this case, it means that this is the result of APP unconditional trust authentication. Although theoretically, this process may be attacked and the data can be tampered with, which is the risk that app must bear in this case. Therefore, it is recommended that this parameter not be set to null. The instantiation of this class is a little troublesome. It is mainly implemented using the security interface of javax. A helper class will be given in my demo program later. This class encapsulates the logic of the internal implementation. Developers can directly use my class to simplify the instantiation process. 2. Cancel is an object of cancelationsignal class. This object is used to cancel the current scanning operation when the fingerprint recognizer scans the user's fingerprint. If not, the fingerprint scanner will transplant the scanning until it times out (generally 30s, depending on the specific manufacturer's implementation). In this way, it will consume more power. It is recommended that this parameter not be set to null. 3. Flags identification bit. According to the document description above, this bit should be 0 temporarily, and this flag bit should be reserved for future use. 4. Callback this is fingerprint manager The object of the authenticationcallback class, which is the most important parameter in the interface except the first parameter. After the system completes the fingerprint authentication process (failure or success), it will call back the interface in this object to notify the app of the authentication result. This parameter cannot be null. 5. Handler this is the object of the handler class. If this parameter is not null, the fingerprint manager will use the looper in this handler to process messages from the fingerprint identification hardware. Generally speaking, this parameter is not required for development, but can be set to null directly, because the fingerprint manager will use the app's main looper by default.

Cancel fingerprint scanning

We mentioned the operation of canceling fingerprint scanning, which is very common. At this time, you can use the cancel method of cancelationsignal class to implement:

This method is specifically used to send a cancel command to a specific listener to cancel the current operation. Therefore, the app can call the cancel method when necessary to cancel the fingerprint scanning operation.

Create cryptoobject class object

When we analyze the authenticate method of fingerprint manager, we see that the first parameter of this method is the object of cryptoobject class. Now let's see how to instantiate this object. We know that the reliability of fingerprint identification results is very important. We certainly don't want the authentication process to be attacked by a third party in some form, because the purpose of introducing fingerprint authentication is to improve security. However, from a theoretical point of view, the process of fingerprint authentication may be maliciously attacked by third-party middleware. The common attack means is to intercept and tamper with the results provided by fingerprint recognizer. Here, we can provide cryptoobject object to the authenticate method to avoid this form of attack. FingerprintManager. Cryptoobject is a wrapper class based on java encryption API and is used by fingerprint manager to ensure the integrity of authentication results. Generally speaking, the mechanism used to encrypt fingerprint scanning results is a javax Crypto. Cipher object. The cipher object itself will use a key generated by the application calling the API of Android keystore to realize the protection function mentioned above. In order to understand how these classes work together, here I give a wrapper class code for instantiating cryptoobject objects. Let's first see how this code is implemented, and then explain why.

The above class will create a cipher object for each cryptoobject object and use the key generated by the application. The name of the key is key_ The name is defined by the name variable. The name should be unique. It is recommended to use the domain name difference. The getKey method will try to use the API of Android keystore to resolve a key (the name is defined above). If the key does not exist, call the createkey method to create a new key. The cipher variable is instantiated by calling cipher Obtained by getInstance method. This method accepts a transformation parameter, which specifies how to encrypt and decrypt data. Then call Cipher.. The init method will use the applied key to instantiate the cipher object. It should be emphasized here that Android will consider the current key invalid in the following cases: 1 A new fingerprint image has been registered in the system 2 The previously registered fingerprints in the current device no longer exist. They may have been deleted 3 The user turned off the screen lock function 4 The user changed the screen lock mode. When the above happens, cipher The init method will throw an exception of keypermanentyinvalidatedexception. I caught this exception in my code above, deleted the currently invalid key, and then tried to create it again according to the parameters. The above code uses Android's keygenerator to create a key and store it in the device. The keygenerator class will create a key, but some original data is required to create the key. These original information is provided through the object of the keygenparameterspec class. The instantiation of keygenerator class object is carried out using its factory method getInstance. From the above code, we can see the AES (Advanced Encryption Standard) encryption algorithm used here. AES will divide the data into several groups and then encrypt them for several groups. Next, the instantiation of keygenparameterspec uses its builder method, keygenparameterspec Builder encapsulates the following important information: 1 Key's name 2 The key must be valid during encryption and decryption. 3 Block in the above code_ Mode is set to cipher block chaining, that is, keyproperties BLOCK_ MODE_ CBC, which means that each data block segmented by AES has XOR operation with the previous data block. This purpose is to establish the dependency between each data block. 4. The cryptoobjecthelper class uses pksc7 (Public Key Cryptography Standard #7) to generate bytes used to fill AES data blocks, so as to ensure that the size of each data block is the same (because XOR calculation and aspect algorithm are required for data processing, please check the principle of AES algorithm for details). 5. The setuserauthenticationrequired (true) call means that the user's identity needs to be authenticated before using the key. Every time keygenparameterspec is created, it is used to initialize keygenerator, which will generate keys stored on the device.

How do I use cryptoobjecthelper?

Let's take a look at how to use the cryptoobjecthelper class. We can see it directly from the code:

The use is relatively simple. First, new a CryptoObjectHelper object, and then call the buildCryptoObject method to get the CryptoObject object.

Process the user's fingerprint authentication results

When we analyzed the authenticate interface earlier, we said that the fingerprint manager must be provided when calling this interface The object of authenticationcallback class, which will be called back by the system after the fingerprint authentication is completed to notify the app of the authentication result. In Android 6.0, fingerprint scanning and authentication are completed in another process (fingerprint system service), so we can't assume when the bottom layer can complete authentication. Therefore, we can only adopt asynchronous operation mode, that is, actively notify us when the bottom layer of the system is completed. The notification mode is to call back our own fingerprint manager Authenticationcallback class, which defines some callback methods for necessary processing:

Let's briefly introduce the meaning of these interfaces: 1 Onauthenticationerror (int errorcode, icharsequence errstring) is called only when an unrecoverable error occurs in the system fingerprint authentication, and the parameter errorcode gives the error code and identifies the cause of the error. At this time, all the app can do is prompt the user to try again. 2. Onauthenticationfailed() this interface will only call back when the system fingerprint authentication fails. Note that the authentication failure here is different from the authentication error above, although the results are unable to authenticate. Authentication failure means that all information is collected completely without any abnormality, but this fingerprint is inconsistent with the previously registered fingerprint; However, authentication errors refer to errors in the process of acquisition or authentication, such as abnormal operation of fingerprint sensor. In other words, authentication failure is a normal situation that can be expected, and authentication error is an unexpected exception. 3. The authentication failure on onauthenticationhelp (int helpmsgid, icharsequence helpstring) is an exception in the authentication process. We say that it is because of an unrecoverable error, and our onauthenticationhelp method is called only when there is an exception that can be answered. What are recoverable exceptions? A common example is that the finger moves too fast. When we put the finger on the sensor, if we move the finger quickly, the fingerprint sensor may only collect part of the information, so the authentication will fail. However, this error can be recovered, so just prompt the user to press the fingerprint again and don't remove it too soon. 4. Onauthenticationsucceeded (fingerprintmanagercompati. Authenticationresult result) this interface will call back after successful authentication. In this method, we can prompt that the user authentication is successful. It needs to be explained here that if we call authenticate above, our CryptoObject is not null, then we can get Cypher object through AuthenticationResult in this method and then call its doFinal method. The dofinal method will check whether the result has been intercepted or tampered with. If so, an exception will be thrown. When we find these exceptions, we should treat the authentication as a failure. For security, we recommend that you do so.

There are two more points to add about the above interface: 1 As mentioned above, there will be errors or help codes in onauthenticationerror and onauthenticationhelp methods to prompt why authentication is not successful. The Android system defines several errors and help codes in the fingerprintmanager class, as follows:

When implementing our callback class, it is best to deal with these errors and help codes.

2. When the fingerprint scanner is working, if we cancel this operation, the system will also call back the onauthenticationerror method, but the error code at this time is fingerprintmanager FINGERPRINT_ ERROR_ Canceled (value is 5), so apps need to be treated differently. The callback subclass implemented in my code is given below:

The implementation of this subclass is very simple. The main implementation method is to throw the message to the handler of the main interface for processing:

Here, the four callbacks are processed respectively, and the handleerrorcode method is called for error code processing:

It is very simple to set different display text on the interface for different error codes to prompt the user. Here you can modify the logic according to your own needs. Call the handlehelpcode method for help code processing:

The processing here is the same as handleerrorcode.

summary

Here we summarize the key points of fingerprint identification development on Android 6.0: 1 It is recommended to use the Android support library V4 compatibility API instead of the API directly in the framework. 2. Before using fingerprint hardware, be sure to check the above inspection conditions 3 According to Google's suggestions, it is best to use the fingerprint provided by Google to mark your fingerprint identification interface:

The purpose of this is to clearly remind the user that this is a fingerprint identification operation, just as people know it is a Bluetooth operation when they see the small logo of Bluetooth. Of course, this is just a practical suggestion from Google, not mandatory. 4. The app needs to inform the user of the current operation and the operation results in time. For example, it needs to clearly tell the user that the fingerprint is currently being scanned, please put your fingerprint on the sensor, etc. 5. Finally, it should be noted that the name of the fingerprint manager class in Android support library V4 is fingerprint managercompat, and the order of their authenticate method parameters is different, and the positions of flags and cancel are different in the two classes. This should be noted (personally, do you think this is a mistake of Google??? Hehe...)

Screenshot of demo running effect (running on nexus 5x)

Initial state

Scan status

Scanning failed (there is a recoverable error. Here, the finger moves too fast)

Authentication failed

Authentication successful

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support programming tips.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>