Fingerprint recognition is a new feature after Android 6.0, so it is necessary to determine whether the system version of the user's phone supports fingerprint recognition when it is used. In addition, in the actual development scenario, there are two main scenarios for using fingerprints:
Pure local use. That is, after the user completes the fingerprint recognition locally, does not need the fingerprint correlation information to the backstage.
interacts with the background. After the user completes the fingerprint recognition locally, needs to pass the fingerprint related information to the backstage.
Because of the need for a cryptographic object (Cryptoobject) to use the fingerprint recognition feature, this object is generally obtained by symmetric or asymmetric encryption. These two development scenarios are implemented in a similar way, the main difference is the encryption process in the creation and use of the key, in general, pure local use of fingerprint recognition, only need symmetric encryption can be, but with the background interaction requires the use of asymmetric encryption: The private key for local fingerprint recognition, after the successful recognition of the encrypted information to the background, The background developer decrypts with the public key to obtain user information.
The following is a brief introduction to symmetric encryption and asymmetric encryption concepts, and then the implementation of the two development methods are explained separately.
Symmetric encryption, asymmetric encryption, and signing
Before you can formally use fingerprint recognition, it is important to understand the content of symmetric and asymmetric encryption.
Symmetric encryption: The so-called symmetry, is the use of this encryption method of the two sides using the same key for encryption and decryption. A key is an instruction that controls the process of encryption and decryption. An algorithm is a set of rules that specify how to encrypt and decrypt. Therefore, the security of encryption depends not only on the encryption algorithm itself, but also on the security of Key management. Since both encryption and decryption use the same key, how to safely pass the key to the decryption person's hand becomes a problem that must be solved.
Asymmetric encryption: An asymmetric encryption algorithm requires two keys: Public key (PublicKey) and private key (Privatekey). Public key is a pair of private key, if the data is encrypted with public key, only the corresponding private key can be decrypted, if the data is encrypted with private key, then only the corresponding public key can be decrypted. Because encryption and decryption use two different keys, this algorithm is called an asymmetric encryption algorithm. The basic process of realizing secret information exchange of Asymmetric encryption algorithm is: Party A generates a pair of keys and exposes one of them as public key to other parties; the party B who obtains the public key will use the key to encrypt the confidential information and send it to party A, and party A will then decrypt the encrypted information with another private key that he has saved.
Signature: After the information is added a section of content, can prove that the information has not been modified. General is to do a hash of information to get a hash value, note that this process is irreversible, that is, can not be derived from the hash value of the original information content. When the message is sent out, encrypt the hash value and send it together as a signature and message.
As you can see from the above, the characteristics of symmetric and asymmetric encryption are as follows:
The advantage of symmetric encryption is that it is fast, suitable for local data and local database encryption, and less secure than asymmetric encryption. Common symmetric encryption algorithms are DES, 3DES, AES, Blowfish, Idea, RC5, RC6.
The security of asymmetric encryption is relatively high, which is suitable for encrypting the data that needs to be transmitted by the network, and the speed is inferior to symmetric encryption. Asymmetric encryption applied to SSH, HTTPS, TLS, electronic certificates, electronic signatures, electronic IDs, etc.
The realization of symmetric encryption for fingerprint identification
The main process for using fingerprint-aware symmetric encryption is as follows:
Use Keygenerator to create a symmetric key that is stored in the KeyStore.
Set KeyGenParameterSpec.Builder.setUserAuthenticationRequired () to True,
Initializes a cipher object using the created symmetric key and invokes the Fingerprintmanager.authenticate () method to start the fingerprint sensor and start listening.
Rewrite several callback methods for Fingerprintmanager.authenticationcallback to handle the success of fingerprint recognition (onauthenticationsucceeded ()), Failure (onauthenticationfailed () and Onauthenticationerror ()).
Create key
Creating a key involves two classes: KeyStore and Keygenerator.
KeyStore is a container for storing and acquiring key (key), and the method for obtaining KeyStore is as follows:
try {
Mkeystore = keystore.getinstance ("Androidkeystore");
} catch (Keystoreexception e) {
throw new RuntimeException ("Failed to get a instance of KeyStore", e);
}
and generate Key, if it is symmetric encryption, you need to Keygenerator class. Getting a Keygenerator object is easier, as follows:
Symmetric encryption, create Keygenerator object
try {
mkeygenerator = Keygenerator
. getinstance (keyproperties.key_algorithm_ AES, "Androidkeystore");
} catch (NoSuchAlgorithmException | Nosuchproviderexception e) {
throw new RuntimeException ("Failed to get a instance of Keygenerator", e);
}
After you get the Keygenerator object, you can generate a Key:
try {
keystore.load (null);
Keygenparameterspec.builder Builder = new Keygenparameterspec.builder (defaultkeyname,
keyproperties.purpose_ ENCRYPT | Keyproperties.purpose_decrypt)
. Setblockmodes (KEYPROPERTIES.BLOCK_MODE_CBC)
. Setuserauthenticationrequired (True)
. Setencryptionpaddings (KEYPROPERTIES.ENCRYPTION_PADDING_PKCS7);
if (Build.VERSION.SDK_INT >= build.version_codes. N) {
builder.setinvalidatedbybiometricenrollment (true);
}
Keygenerator.init (Builder.build ());
Keygenerator.generatekey ();
} catch (Certificateexception | nosuchalgorithmexception | IOException | Invalidalgorithmparameterexception e) {
e.printstacktrace ();
}
About Keystrore and Keygenerator, recommended reading: Android KeyStore + fingerprintmanager Store password
Create and initialize Cipher objects
A Cipher object is an object that encrypts data after it has been encrypted according to a certain encryption rule. This object is required to invoke the fingerprint recognition feature. Creating a Cipher object is simple, as in the following code:
Cipher Defaultcipher;
try {
defaultcipher = cipher.getinstance (Keyproperties.key_algorithm_aes + "/"
+ Keyproperties.block_mode_ CBC + "/" + KEYPROPERTIES.ENCRYPTION_PADDING_PKCS7);
} catch (NoSuchAlgorithmException | Nosuchpaddingexception e) {
throw new RuntimeException ("Create cipher object Failed", e);
}
Then initialize the Cipher object with the key that you just created:
try {
keystore.load (null);
Secretkey key = (Secretkey) keystore.getkey (KeyName, null);
Cipher.init (Cipher.encrypt_mode, key);
return true;
} catch (IOException | nosuchalgorithmexception | certificateexception | unrecoverablekeyexception | keystoreexception | InvalidKeyException e) {
throw new RuntimeException ("Initialization cipher failed", e);
}
Use fingerprint recognition function
When it comes to using fingerprint recognition, you'll find that it's very simple, just call the Fingerprintmanager class's method Authenticate (), and then the system will have the corresponding callback feedback to us, the method is as follows:
public void Authenticate (Cryptoobject crypto, cancellationsignal cancel, int flags, Authenticationcallback callback, Handler Handler)
Several parameters of the method are explained as follows:
The first parameter is an encrypted object. Do you remember the cipher object we created and initialized before we had a big fee Zhou Zhangdi? The Cryptoobject object here is created using the Cipher object creation: New Fingerprintmanager.cryptoobject (Cipher).
The second parameter is a Cancellationsignal object that provides the ability to cancel the operation. It is also easy to create this object, using the new Cancellationsignal ().
The third parameter is a flag, and the default is 0.
The fourth parameter is the Authenticationcallback object, which itself is an abstract class inside the Fingerprintmanager class. This class provides several callback methods for fingerprint identification, including success and failure of fingerprint recognition. Need us to rewrite.
The last Handler, which can be used to handle callback events, can be passed null.
When you finish fingerprint identification, remember to turn off the Authenticationcallback:
public void stoplistening () {
if (cancellationsignal!= null) {
selfcancelled = true;
Cancellationsignal.cancel ();
cancellationsignal = null;
}
}
Overriding callback Methods
After the authenticate () method is invoked, the system starts the fingerprint sensor and begins the scan. Depending on the result of the scan, several callback methods are returned via the Fingerprintmanager.authenticationcallback class:
Success
onauthenticationsucceeded ()/
/Failure
onauthenticationfaile ()
//Error
Onauthenticationerror ()
Generally we need to rewrite these methods to achieve our function. The difference between onauthenticationfaile () and Onauthenticationerror () will be mentioned later.
Implementation of asymmetric encryption for fingerprint identification
In fact, the process and the above process is similar:
Use Keypairgenerator to create an asymmetric key.
Sign with the created private key, create an encrypted object using the signature, and use the object as a parameter of the Fingerprintmanager.authenticate () method to start the fingerprint sensor and start listening.
Rewrite several callback methods for the Fingerprintmanager.authenticationcallback class to handle the success of fingerprint recognition (onauthenticationsucceeded ()), Failure (onauthenticationfailed () and Onauthenticationerror ()).
It can be seen that the asymmetric encryption method of fingerprint identification and the implementation process of symmetric encryption are similar, the most obvious difference between them is the generation and use of the key.
Create key
Here you use Keypairgenerator to create a set of asymmetric keys, first getting the Keypairgenerator objects:
Asymmetric encryption, create Keypairgenerator object
try {
mkeypairgenerator = keypairgenerator.getinstance (keyproperties.key_ Algorithm_ec, "Androidkeystore");
} catch (NoSuchAlgorithmException | Nosuchproviderexception e) {
throw new RuntimeException ("Failed to get a instance of Keypairgenerator", e);
}
After you get the Keypairgenerator object, you can create the KeyPair (key pair):
try {
//Set The alias of the entry in Android KeyStore where the key would appear
//and the constrains (purposes)
in the constructor of the Builder mkeypairgenerator.initialize (
new Keygenparameterspec.builder (Key_name,
keyproperties.purpose_sign)
. Setdigests (keyproperties.digest_sha256)
. Setalgorithmparameterspec (New Ecgenparameterspec ("SECP256R1"))
//Require the user to authenticate with a fingerprint to authorize
//every use of the private key
. SetUser Authenticationrequired (True)
. Build ());
Mkeypairgenerator.generatekeypair ();
} catch (Invalidalgorithmparameterexception e) {
throw new RuntimeException (e);
}
Signature
The symmetric encryption implementation of fingerprint identification uses the Cipher object to create the Cryptoobject object, where we will sign with the private key and use the Signature object to create the Cryptoobject object:
Use the private key to sign
try {
mkeystore.load (null);
Privatekey key = (Privatekey) mkeystore.getkey (key_name, null);
Msignature.initsign (key);
return true;
} catch (Keypermanentlyinvalidatedexception e) {return
false;
} catch (Keystoreexception | certificateexception | unrecoverablekeyexception | IOException
| nosuchalgorithmexception | InvalidKeyException e) {
throw new RuntimeException ("Failed to init Cipher", e);
}
Similarly, the new Fingerprintmanager.cryptoobject (Msignature) method is invoked to create a Cryptoobject object.
Call Fingerprint Identification method
The use method here is the same as the calling method in the previous "symmetric encryption implementation of fingerprint identification", which is called the Fingerprintmanager.authenticate () method. This is no longer described here.
Listening for callbacks
The listener callback is similar to the previous one, and the only difference is that we need to interact with the background when we recognize success, that is, the logic in onauthenticationsucceeded () is different.
Matters needing attention in the practical application
Determine if the user can use fingerprint recognition function
In general, in order to increase security, users in the mobile phone "settings" opened the Password lock screen function. Of course, the premise of using fingerprint to unlock is to have at least one fingerprint entered.
If you do not set a password lock screen, you cannot use the fingerprint identification if
(!keyguardmanager.iskeyguardsecure ()) {
Toast.maketext (this, "Please open the Password lock screen in the Settings interface").
Toast.length_long). Show ();
If you do not enter a fingerprint, you cannot use the fingerprint identification if
(!fingerprintmanager.hasenrolledfingerprints ()) {
Toast.maketext (this, "You have not entered a fingerprint, Please enter at least one fingerprint in the Setup interface ",
Toast.length_long". Show ();
Here are two classes: Keyguardmanager and Fingerprintmanager, which are related classes for screen protection. The latter is the core category of fingerprint identification.
About fingerprint recognition callback method
There are several callback methods in the Authenticationcallback class, three of which are needed in our development:
Onauthenticationerror ()
onauthenticationsucceeded ()
onauthenticationfailed ()
There are a few things to note about these three callback methods:
When the fingerprint recognition fails, the onauthenticationfailed () method is invoked, and the fingerprint sensor is not closed, and the system gives us a 5 chance to retry, that is, after 5 consecutive onauthenticationfailed () methods are invoked, The Onauthenticationerror () method is invoked.
When the system calls Onauthenticationerror () and onauthenticationsucceeded (), the sensor shuts down, and only if we re authorize the authenticate () method to continue using the fingerprint recognition function.
When the system recalls the Onauthenticationerror () method to turn off the sensor, the authenticate () is invoked again for a period of time, meaning that it is not possible to use fingerprint identification again during this period. Of course, the specific disabling time is different from the handset manufacturer's system and has a slight difference, some 1 minutes, some 30 seconds and so on. Moreover, because the handset manufacturer's system difference, some system calls the Onauthenticationerror (), in the disabling time, other app inside fingerprint recognition function also cannot use, even the system fingerprint unlock function also cannot use. And some systems, in the disabling time to call other app's fingerprint unlock function, or the system's fingerprint unlock function, you can immediately reset fingerprint recognition function.
The above is a small set to introduce the Android fingerprint Identification Demo Development example, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!