Fingerprint recognition in Android

Source: Internet
Author: User
Tags decrypt asymmetric encryption

Reprint Please specify source: http://blog.csdn.net/wl9739/article/details/52444671

Recent projects need to use the fingerprint recognition function, consulted the relevant information, organized into this article.

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. In addition, there are two main scenarios for using fingerprints in a real-world development scenario:

    • Pure local use. That is, after the user completes the fingerprint recognition locally, it is not necessary to send the fingerprint information to the background.
    • Interact with the background. After the user has completed the fingerprint recognition locally, the fingerprint-related information needs to be passed to the background.

Because a cryptographic object (Cryptoobject) is required to use the fingerprint recognition feature, the object is generally obtained by symmetric or asymmetric encryption. The implementation of the two development scenarios is similar, the main difference is the encryption process key creation and use, in general, pure local use of fingerprint recognition function, only need symmetric encryption , and background interaction requires the use of asymmetric encryption : Private key for local fingerprint identification , after the recognition is successful, the encrypted information is passed to the backstage, and the background developer decrypts it with the public key to obtain the user information.

The following is a brief introduction of symmetric encryption and asymmetric encryption of the relevant concepts, and then the two development methods to explain the implementation of each.

Symmetric encryption, asymmetric encryption, and signing

Before formally using the fingerprint recognition function, it is necessary to understand the symmetric encryption and asymmetric encryption related content.

    • Symmetric encryption: The so-called symmetry, is the use of this encryption method used by both parties to encrypt and decrypt the same key. A key is an instruction that controls the process of encrypting and decrypting. The algorithm is a set of rules that specify how to encrypt and decrypt. Therefore, the security of encryption not only depends on the encryption algorithm itself, but also the security of key management is more important. Because both encryption and decryption use the same key, how to safely pass the key to the decryption hand is a problem that must be solved.

    • Asymmetric encryption: An asymmetric encryption algorithm requires two keys: Public key (PublicKey) and private key (Privatekey). Public key and private key is a pair, if the data encrypted with public key, only with the corresponding private key to decrypt, if the private key to encrypt the data, 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 the asymmetric encryption algorithm to realize the secret information exchange is: Party A generates a pair of keys and exposes one of them as a public key to other parties; the party B who obtains the public key encrypts the secret information and sends it to party a, and then decrypts the encrypted information with another private key that it saves.

    • Signature: Add a piece of content to the back of the message to prove that the information has not been modified. The general is to do a hash of the information to get a hash value, note that the process is irreversible, that is, the hash value can not be derived from the original information content. When the message is sent out, the hash value is encrypted and sent out together as a signature and message.

As can be learned from the above, symmetric encryption and asymmetric encryption are characterized 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. The common symmetric encryption algorithms are DES, 3DES, AES, Blowfish, Idea, RC5, RC6.
    • Asymmetric encryption is more secure and suitable for encrypting data that needs to be transmitted over the network, and is less efficient than symmetric encryption. Asymmetric encryption applied to SSH, HTTPS, TLS, electronic certificates, electronic signatures, electronic IDs, etc.
Symmetric encryption implementation of fingerprint recognition

The main process for using fingerprint-aware symmetric encryption is as follows:

    1. Use keygenerator to create a symmetric key that is stored in the KeyStore.
    2. Set KeyGenParameterSpec.Builder.setUserAuthenticationRequired() to True,
    3. Initializes a cipher object with the created symmetric key, and uses the object invocation method to FingerprintManager.authenticate() start the fingerprint sensor and start listening.
    4. Override FingerprintManager.AuthenticationCallback Several callback methods to handle fingerprint recognition success ( onAuthenticationSucceeded() ), failure ( onAuthenticationFailed() and), and onAuthenticationError() so on.
Create key

There are two classes involved in creating a key: KeyStore and Keygenerator.

KeyStore is a container for storing and retrieving keys (key), and the method to get KeyStore is as follows:

try {    mKeyStore = KeyStore.getInstance("AndroidKeyStore"catch (KeyStoreException e) {    thrownew RuntimeException("Failed to get an instance of KeyStore", e);}

To generate a Key, if it is symmetric encryption, you need the Keygenerator class. Getting a Keygenerator object is simple, as follows:

// 对称加密, 创建 KeyGenerator 对象try {    mKeyGenerator = KeyGenerator            "AndroidKeyStore"catch (NoSuchAlgorithmException | NoSuchProviderException e) {    thrownew RuntimeException("Failed to get an instance of KeyGenerator", e);}

Once 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). setuserauthenticationre quired (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 ();} 

Introduction to Keystrore and Keygenerator, recommended reading: Android KeyStore + fingerprintmanager storage password

Create and initialize a Cipher object

The Cipher object is an object that encrypts data according to a certain encryption rule. Calling the fingerprint recognition feature requires the use of this object. Creating a Cipher object is as simple as the following code:

Cipher defaultCipher;try {    "/"            "/"catch (NoSuchAlgorithmException | NoSuchPaddingException e) {    thrownew RuntimeException("创建Cipher对象失败", e);}

Then initialize the Cipher object with the key you just created:

try {    keyStore.load(null);    null);    cipher.init(Cipher.ENCRYPT_MODE, key);    returntruecatch (IOException | NoSuchAlgorithmException | CertificateException | UnrecoverableKeyException | KeyStoreException | InvalidKeyException e) {    thrownew RuntimeException("初始化 cipher 失败", e);}
Using the fingerprint recognition feature

When it comes to using the fingerprint recognition function, you will find that it is very simple, just call the method of the Fingerprintmanager class authenticate () , then the system will have the corresponding callback feedback to us, The method is as follows:

publicvoidauthenticateint

Several parameters of the method are explained as follows:

    • The first parameter is an encrypted object. Remember the cipher object that we Zhou Zhangdi to create and initialize before? 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's also easy to create the object, so new CancellationSignal() you can use it.
    • The third parameter is a flag that defaults to 0.
    • The fourth parameter is the authenticationcallback object, which itself is an abstract class within the Fingerprintmanager class. This class provides several callback methods for fingerprint recognition, including the 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.

After you finish the fingerprint identification, remember to close the authenticationcallback :

publicvoidstopListening() {    ifnull) {        true;        cancellationSignal.cancel();        null;    }}
Overriding callback Methods

When the authenticate() method is called, the fingerprint sensor is started and the scan starts. Depending on the scan results, several callback methods are returned through the Fingerprintmanager.authenticationcallback class:

// 成功onAuthenticationSucceeded()// 失败onAuthenticationFaile()// 错误onAuthenticationError()

In general we need to rewrite these methods to achieve our functionality. onAuthenticationFaile() onAuthenticationError() The difference between and will be mentioned later.

Implementation of asymmetric encryption for fingerprint recognition

In fact, the process and the above process is similar:

    1. Use keypairgenerator to create an asymmetric key.
    2. Use the created private key to sign, create an encrypted object with the signature, and use that object as FingerprintManager.authenticate() a parameter to the method, start the fingerprint sensor, and start listening.
    3. Override FingerprintManager.AuthenticationCallback Several callback methods of the class to handle the success ( onAuthenticationSucceeded() ), failure ( onAuthenticationFailed() and), and so on, of the fingerprint recognition onAuthenticationError() .

It can be seen that the asymmetric encryption method of fingerprint recognition 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 to get the keypairgenerator object:

// 非对称加密,创建 KeyPairGenerator 对象try {    mKeyPairGenerator =  "AndroidKeyStore"catch (NoSuchAlgorithmException | NoSuchProviderException e) {    thrownew RuntimeException("Failed to get an instance of KeyPairGenerator", e);}

Once you have the Keypairgenerator object, you can create a 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 BuilderMkeypairgenerator.initialize (NewKeygenparameterspec.builder (Key_name, keyproperties.purpose_sign). Setdigests (Keypro Perties. digest_sha256). Setalgorithmparameterspec (NewEcgenparameterspec ("SECP256R1"))//Require the user to authenticate with a fingerprint to authorize                    //Every use of the private key. setuserauthenticationrequired (true). Build ()); Mkeypairgenerator.generatekeypair ();}Catch(Invalidalgorithmparameterexception e) {Throw NewRuntimeException (e);}
Signature

The symmetric encryption implementation of fingerprint recognition uses the Cipher object to create the Cryptoobject object, and here we will use the private key to sign and create the Cryptoobject object with the Signature object:

//signed with private key  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 method is called to new FingerprintManager.CryptoObject(mSignature) create a Cryptoobject object.

Call the fingerprint recognition method

The method used here is the same as the calling method in the preceding "symmetric encryption implementation of fingerprint recognition", which is called FingerprintManager.authenticate() method. This is no longer described here.

Listener Callbacks

The listener callback is similar to the previous one, except that we need to interact with the background after the recognition is successful, that is, the onAuthenticationSucceeded() logic in processing is different.

Considerations in practical applications determine if a user can use the Fingerprint recognition feature

In general, for added security, the user is asked to turn on the Passcode lock screen in the "Settings" of the phone. Of course, using a fingerprint to unlock the premise is to enter at least one fingerprint.

// 如果没有设置密码锁屏,则不能使用指纹识别if (!keyguardManager.isKeyguardSecure()) {    Toast.makeText(this"请在设置界面开启密码锁屏功能",            Toast.LENGTH_LONG).show();}// 如果没有录入指纹,则不能使用指纹识别if (!fingerprintManager.hasEnrolledFingerprints()) {    Toast.makeText(this"您还没有录入指纹, 请在设置界面录入至少一个指纹",            Toast.LENGTH_LONG).show();}

There are two classes used here:Keyguardmanager and Fingerprintmanager, the first of which is screen-protected related classes. The latter is the core class of fingerprint recognition.

About the fingerprint recognition callback method

In front of the Authenticationcallback class, there are several callback methods, of which three are needed in our development:

onAuthenticationError()onAuthenticationSucceeded()onAuthenticationFailed()

There are a few things to note about these three callback methods:

    1. When the fingerprint fails, the method is called, and the onAuthenticationFailed() fingerprint sensor is not turned off, and the system gives us 5 retry attempts, that is, the onAuthenticationFailed() method is called after 5 successive calls to the method onAuthenticationError() .

    2. When the system is called onAuthenticationError() and onAuthenticationSucceeded() then the sensor shuts down and we re-authorize the authenticate() method before we can continue using the fingerprint recognition feature.

    3. When the system callback onAuthenticationError() method to close the sensor, in this case re authenticate() -call will have a period of time to disable, that is, the time is not able to use the fingerprint recognition again. Of course, the specific disabling time by the handset manufacturer's system differs slightly, some 1 minutes, some 30 seconds and so on. Moreover, due to the system differences of handset manufacturers, some systems have been called onAuthenticationError() , in the time of disabling, the fingerprint recognition function in other apps can not be used, even the system's fingerprint unlocking function can not be used. On some systems, it is possible to immediately reset the fingerprint recognition function by invoking the fingerprint unlocking function of other apps or the system's fingerprint unlocking function during the disabling time.

Sample code

Finally, the sample code for fingerprints in Android sample has the following address:

Symmetric encryption Method: Android-fingerprintdialog.

Asymmetric Encryption Method: Android-asymmetricfingerprintdialog

Reference link: New in Android samples:authenticating to remote servers using the fingerprint API

Fingerprint recognition in Android

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: info-contact@alibabacloud.com 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.