Implemented finding fallback algorithms as PBKDF2WithHmacSHA256 is only supported on newer Androids

This commit is contained in:
dankito 2020-10-10 01:40:08 +02:00
parent 2f709ed0b6
commit 968543953a
2 changed files with 78 additions and 1 deletions

View File

@ -109,7 +109,7 @@ open class CryptographyManager {
protected open fun generatePbeSecretKey(userPassword: String, salt: ByteArray): SecretKey { protected open fun generatePbeSecretKey(userPassword: String, salt: ByteArray): SecretKey {
// Initialize PBE with password // Initialize PBE with password
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256") val factory = SecretKeyFactory.getInstance(findBestPbeAlgorithm()!!)
val spec = PBEKeySpec(userPassword.toCharArray(), salt, 65536, 256) val spec = PBEKeySpec(userPassword.toCharArray(), salt, 65536, 256)
val key = factory.generateSecret(spec) val key = factory.generateSecret(spec)
@ -126,4 +126,37 @@ open class CryptographyManager {
} }
} }
open fun findBestPbeAlgorithm(): String? {
return findBestMatchingAlgorithm(SecurityProviderServiceType.SecretKeyFactory, "PBKDF2","PBKDF2WithHmacSHA256")
?: findBestMatchingAlgorithm(SecurityProviderServiceType.SecretKeyFactory, "PBE")
}
open fun findBestMatchingAlgorithm(type: SecurityProviderServiceType, nameStartsWith: String, vararg preferredAlgorithms: String): String? {
val supportedAlgorithms = listServiceTypeAlgorithmsWithName(type, "PBKDF2")
val bestMatchingAlgorithm = preferredAlgorithms.firstOrNull { supportedAlgorithms.contains(it) }
?: supportedAlgorithms.maxBy { it.length }
return bestMatchingAlgorithm
}
open fun listServiceTypeAlgorithmsWithName(type: SecurityProviderServiceType, nameStartsWith: String): List<String> {
return listServiceTypeAlgorithms(type)
.filter { it.startsWith(nameStartsWith, true) }
}
open fun listServiceTypeAlgorithms(type: SecurityProviderServiceType): List<String> {
val algorithms = mutableListOf<String>()
Security.getProviders().forEach { provider ->
algorithms.addAll(provider.services
.filter { it.type == type.type }
.map { it.algorithm }
)
}
return algorithms
}
} }

View File

@ -0,0 +1,44 @@
package net.dankito.banking.ui.android.security
enum class SecurityProviderServiceType(val type: String) {
AlgorithmParameterGenerator("AlgorithmParameterGenerator"),
AlgorithmParameters("AlgorithmParameters"),
CertPathBuilder("CertPathBuilder"),
CertPathValidator("CertPathValidator"),
CertStore("CertStore"),
CertificateFactory("CertificateFactory"),
Cipher("Cipher"),
KeyAgreement("KeyAgreement"),
KeyFactory("KeyFactory"),
KeyGenerator("KeyGenerator"),
KeyManagerFactory("KeyManagerFactory"),
KeyPairGenerator("KeyPairGenerator"),
KeyStore("KeyStore"),
Mac("Mac"),
MessageDigest("MessageDigest"),
SSLContext("SSLContext"),
SecretKeyFactory("SecretKeyFactory"),
SecureRandom("SecureRandom"),
Signature("Signature"),
}