-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathCryptoHelper.kt
80 lines (69 loc) · 2.47 KB
/
CryptoHelper.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package com.mikhaellopez.biometric
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import androidx.annotation.RequiresApi
import androidx.biometric.BiometricPrompt
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
/**
* Copyright (C) 2020 Mikhael LOPEZ
* CryptoHelper is an object to create a default [BiometricPrompt.CryptoObject]
* This class is also used to check if one biometric must be enrolled.
*/
class CryptoHelper {
companion object {
private const val DEFAULT_BIOMETRIC_KEY = "default_biometric_key"
}
/**
* Return true if one biometric must be enrolled else false
*
* @return [Boolean]
*/
@RequiresApi(Build.VERSION_CODES.M)
fun checkOneBiometricMustBeEnrolled(): Boolean =
try {
generateKey()
true
} catch (ex: Exception) {
false
}
/**
* Returns a default [BiometricPrompt.CryptoObject]
*
* @return [BiometricPrompt.CryptoObject]
*/
@RequiresApi(Build.VERSION_CODES.M)
fun cryptoObject(): BiometricPrompt.CryptoObject =
BiometricPrompt.CryptoObject(initCipher(generateKey()))
@RequiresApi(Build.VERSION_CODES.M)
private fun generateKey(): KeyStore {
val keyStore = KeyStore.getInstance("AndroidKeyStore")
val keyGenerator =
KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore")
keyStore.load(null)
keyGenerator.init(
KeyGenParameterSpec.Builder(
DEFAULT_BIOMETRIC_KEY,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build()
)
keyGenerator.generateKey()
return keyStore
}
@RequiresApi(Build.VERSION_CODES.M)
private fun initCipher(keyStore: KeyStore): Cipher {
val cipher =
Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7)
keyStore.load(null)
val key = keyStore.getKey(DEFAULT_BIOMETRIC_KEY, null) as SecretKey
cipher.init(Cipher.ENCRYPT_MODE, key)
return cipher
}
}