· 7 years ago · Jan 14, 2019, 11:04 PM
1public class AutenticacionHuellaActivity extends AppCompatActivity {
2 @Override
3 protected void onCreate(Bundle savedInstanceState) {
4 super.onCreate(savedInstanceState);
5 setContentView(R.layout.activity_autenticacion_huella);
6 getSupportActionBar().setDisplayHomeAsUpEnabled(true);
7 Intent intentoRecuperado= getIntent();
8//Se instancian objetos FingerprintManager y KeyguardManager
9 KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
10 FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
11 packageManager=getPackageManager();
12 // Se verifica si el dispositivo posee sensor de huella
13...
14 //Se verfica si es que se tiene permiso del uso de huella dactilar.
15...
16 //Se verifica si se tienen huellas dactilares enroladas en teléfono.
17...
18 //Se verifican si la pantalla de seguridad esté habilitada.
19 //Generar clave
20 generateKey();
21 //Iniciar el cifrador.
22 if (cipherInit()) {
23 FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher);
24 ManejoDeHuellas manejadorHuellas = new ManejoDeHuellas(this);
25 //Se obtiene el id del empleado
26 Intent intent= getIntent();
27 int idEmpleado= intent.getExtras().getInt("idEmpleado");
28 //aqui se llama al metodo que inicia la autenticacion.
29 //Verificar si se va a registrar entrada o salida
30 if(opcionEntrada==true){
31 manejadorHuellas.opcionEntrada=true;
32 manejadorHuellas.opcionSalida=false;
33 }else {
34 manejadorHuellas.opcionEntrada=false;
35 manejadorHuellas.opcionSalida=true;
36 }
37 manejadorHuellas.idEmpleado=idEmpleado;
38 manejadorHuellas.empezarAutenticacionHuella(fingerprintManager, cryptoObject);
39 }
40 }
41 }
42 }
43 }
44
45
46 }//Fin onCreate
47
48 //Acceso al Keystore y Keygenerator de Android, para poder generar claves se debe primero tener acceso al keystore.
49 //El Keystore es un lugar en donde se guardan las claves de manera segura.
50 @TargetApi(Build.VERSION_CODES.M)
51 protected void generateKey() {
52 try {
53 keyStore = KeyStore.getInstance("AndroidKeyStore");
54 } catch (Exception e) {
55 e.printStackTrace();
56 }
57
58 KeyGenerator keyGenerator;
59 try {
60 keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");//Para obtener referencia al keystore se usa getInstance.
61 //Generar una clave usando el servicio KeyGenerator Service.
62 } catch (NoSuchAlgorithmException | NoSuchProviderException e) {
63 throw new RuntimeException("Fallo en obtener una instancia de KeyGenerator", e);
64 }
65
66 //Generar la clave que va a ser usado por el cifrador en el proceso de encripción.
67 try {
68 keyStore.load(null); //Se carga el contenedor de claves
69 //Se instancia KeyGenerator con los diferentes parámetros de seguridad.
70 //Se inicia la generación de clave.
71 //KeyGenParameterSpec.Builder sirve para especificar el tipo de clave a generar. en este caso, la clave es simétrica, para cifrar y decifrar ese l mismo.
72 //setBlockModes() para especificar el modo de bloque, en este caso es CBC: Cipher Block Chaining. a cada bloque se aplica XOR.
73 //setUserAuthenticationRequired para que el usuario tenga que autorizar la operación cada vez que se use la clave para la autenticacion de huellas.
74 //También se emplea rellenos para que la información quede especificamente en bloques para que sean cifrados por bloques.
75 keyGenerator.init(new
76 KeyGenParameterSpec.Builder(KEY_NAME,
77 KeyProperties.PURPOSE_ENCRYPT |
78 KeyProperties.PURPOSE_DECRYPT)
79 .setBlockModes(KeyProperties.BLOCK_MODE_CBC)
80 .setUserAuthenticationRequired(true)
81 .setEncryptionPaddings(
82 KeyProperties.ENCRYPTION_PADDING_PKCS7)
83 .build());
84 keyGenerator.generateKey();
85 } catch (NoSuchAlgorithmException |
86 InvalidAlgorithmParameterException
87 | CertificateException | IOException e) {
88 throw new RuntimeException(e);
89 }
90 }
91
92 //Para Iniciar el cifrador
93 //getInstance obtiene instancia del Cipher. luego le configuran con las propiedades requeridas por la autenticación por huella.
94 //La clave previamente generada es extraÃda del Keystore container y usada para inicializar la instancia del cipher.
95 //Se manejan errores acordemente.
96 //Retorna true si el cifrador inició satisfactoriamente.
97 //false en el caso que no.
98 @TargetApi(Build.VERSION_CODES.M)
99 public boolean cipherInit() {
100 try {
101 //Se obtiene una referencia al cifrador.
102 cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
103 } catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
104 throw new RuntimeException("Fallo en iniciar el Cifrador", e);
105 }
106 try {
107 keyStore.load(null); //Se carga el keystore container
108 //Se genera una clave secreta
109 SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
110 null);
111 //Se inicia el cifrador
112 cipher.init(Cipher.ENCRYPT_MODE, key);
113 //Si esque el cifrador inicia correctamente, retorna true.
114 return true;
115 } catch (KeyPermanentlyInvalidatedException e) {
116 return false;
117 } catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
118 throw new RuntimeException("Fallo en iniciar el Cifrador", e);
119 }
120 }
121/*
122 public static void mostrarEstadoAutenticacion(String mensaje){
123 txvwEstadoAutenticacion.setText(mensaje);
124
125 }*/
126 public static void mostrarEstadoRegistro(String mensaje){
127 txvwEstadoRegistro.setText(mensaje);
128 }
129
130}//Fin actividad