Моя задача, сделать андроид приложение с авторизацией по лицу. Предварительно я сделал обычную авторизацию по логину и паролю с помощью Firebase? чтобы в дальнейшем в профиле можно было добавить биометрию лица. Вопрос заключается в том, возможно ли сделать авторизацию по лицу через различные сервисы Firebase или же использовать сторонние сервисы, если сторонние то какие? В приоритете нейронные сети, но какие есть варианты, которые можно прикрутить как распознавалку и с помощью которого будет возможен вход в приложение?
1 ответ
Насколько я знаю, в системе Android это встроенный функционал. Никаких сервисов использовать не нужно. У вас в системе есть хранилище ваших данных. Оно защищено довольно хорошо так как там хранятся ваши отпечатки например и данные сканера лица. Для того чтобы использовать данное хранилище нужно:
Добавить зависимость:
implementation 'androidx.biometric:biometric:1.0.1'
Добавить в манифест разрешение:
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
Будем использовать для вызова диалога например кнопку:
<?xml version="1.0" encoding="utf-8"?> <layout xmlns:android="http://schemas.android.com/apk/res/android"> <RelativeLayout android:id="@+id/parent_layout" android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="30dp"> <Button android:id="@+id/touch_button" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="@color/river_blue" android:stateListAnimator="@null" android:text="Biometric Login" android:textAllCaps="false" android:textColor="@color/white" android:textSize="16sp" /> </RelativeLayout> </layout>
Добавляем необходимые переменные в класс активности:
private static final String KEY_NAME = "KeyName"; private static final String ANDROID_KEY_STORE = "AndroidKeyStore"; private static final String FORWARD_SLASH = "/";
В функции
onCreate()
добавляем эти строки:touchButton = findViewById(R.id.touch_button); touchButton.setOnClickListener((view) -> onTouchIdClick()); displayBiometricButton();
Обрабатываем клик на кнопку:
private void onTouchIdClick() { getBiometricPromptHandler().authenticate(getBiometricPrompt(), new BiometricPrompt.CryptoObject(getCipher())); // Please see the below mentioned note section. // getBiometricPromptHandler().authenticate(getBiometricPrompt()); }
Проверяем доступно ли на устройстве хоть какие-то способы биометрической защиты:
private boolean isBiometricCompatibleDevice() { if (getBiometricManager().canAuthenticate() == BiometricManager.BIOMETRIC_SUCCESS) { return true; } else { return false; } }
Отображаем кнопку логина если есть какие-то средства биометрии:
private void displayBiometricButton() { if (isBiometricCompatibleDevice()) { touchButton.setEnabled(false); } else { touchButton.setEnabled(true); generateSecretKey(); } }
Получаем менеджер биометрического хранилища и генерируем ключ:
private BiometricManager getBiometricManager() { return BiometricManager.from(this); } private void generateSecretKey() { KeyGenerator keyGenerator = null; KeyGenParameterSpec keyGenParameterSpec = new KeyGenParameterSpec.Builder( KEY_NAME, KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT) .setBlockModes(KeyProperties.BLOCK_MODE_CBC) .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7) .setUserAuthenticationRequired(true) .setInvalidatedByBiometricEnrollment(false) .build(); try { keyGenerator = KeyGenerator.getInstance( KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEY_STORE); } catch (NoSuchAlgorithmException | NoSuchProviderException e) { e.printStackTrace(); } if (keyGenerator != null) { try { keyGenerator.init(keyGenParameterSpec); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } keyGenerator.generateKey(); } } private SecretKey getSecretKey() { KeyStore keyStore = null; Key secretKey = null; try { keyStore = KeyStore.getInstance(ANDROID_KEY_STORE); } catch (KeyStoreException e) { e.printStackTrace(); } if (keyStore != null) { try { keyStore.load(null); } catch (CertificateException | IOException | NoSuchAlgorithmException e) { e.printStackTrace(); } try { secretKey = keyStore.getKey(KEY_NAME, null); } catch (KeyStoreException | NoSuchAlgorithmException | UnrecoverableKeyException e) { e.printStackTrace(); } } return (SecretKey) secretKey; }
Подключаем шифровальщик и обрабатываем данные с считывателей:
private Cipher getCipher() { Cipher cipher = null; try { cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + FORWARD_SLASH + KeyProperties.BLOCK_MODE_CBC + FORWARD_SLASH + KeyProperties.ENCRYPTION_PADDING_PKCS7); try { cipher.init(Cipher.ENCRYPT_MODE, getSecretKey()); } catch (InvalidKeyException e) { e.printStackTrace(); } } catch (NoSuchAlgorithmException | NoSuchPaddingException e) { e.printStackTrace(); } return cipher; } private BiometricPrompt.PromptInfo getBiometricPrompt() { return new BiometricPrompt.PromptInfo.Builder() .setTitle("Biometric login for my app") .setSubtitle("Login with your biometric credential") .setNegativeButtonText("cancel") .setConfirmationRequired(false) .build(); } private void onBiometricSuccess() { //Call the respective API on biometric success callLoginApi("userName", "password"); } private BiometricPrompt getBiometricPromptHandler() { return new BiometricPrompt(this, ContextCompat.getMainExecutor(this), new BiometricPrompt.AuthenticationCallback() { @Override public void onAuthenticationError(int errorCode, @NonNull CharSequence errString) { super.onAuthenticationError(errorCode, errString); } @Override public void onAuthenticationSucceeded(@NonNull BiometricPrompt.AuthenticationResult result) { super.onAuthenticationSucceeded(result); onBiometricSuccess(); } @Override public void onAuthenticationFailed() { super.onAuthenticationFailed(); } } ); }
Вот документ где описано сенсоры для доступа к хранилищу. Подобный вопрос и обсуждение. Документация_1, документация_2 и документация_3. Туториал по использованию распознавания по лицу.