Сохраните пароль в хранилище ключей Android с помощью биометрического API.Android

Форум для тех, кто программирует под Android
Ответить Пред. темаСлед. тема
Гость
 Сохраните пароль в хранилище ключей Android с помощью биометрического API.

Сообщение Гость »


Я хочу сохранить

Код: Выделить всё

password
in Android Key-store just confused where it stores actually the password is it in

Код: Выделить всё

Sharedpreference
or this is the code i tried so far

Код: Выделить всё

import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.biometric.BiometricPrompt
import androidx.core.content.ContextCompat
import java.security.KeyStore
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec

class MainActivity : AppCompatActivity() {

private val KEY_ALIAS = "my_secure_key"

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val keyStore = KeyStore.getInstance("AndroidKeyStore")
keyStore.load(null)

val secretKey = if (keyStore.containsAlias(KEY_ALIAS)) {
keyStore.getKey(KEY_ALIAS, null) as SecretKey
} else {
val keyGenerator = KeyGenerator.getInstance(
KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore"
)

val keyGenParameterSpec = KeyGenParameterSpec.Builder(
KEY_ALIAS,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setUserAuthenticationRequired(true) // Requires biometric authentication
.build()

keyGenerator.init(keyGenParameterSpec)
keyGenerator.generateKey()
}

val biometricPrompt = BiometricPrompt(
this,
ContextCompat.getMainExecutor(this),
object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
super.onAuthenticationSucceeded(result)
val cipher = result.cryptoObject?.cipher
if (cipher != null) {
val encryptedUsername = cipher.doFinal("my_username".toByteArray())
val encryptedPassword = cipher.doFinal("my_password".toByteArray())

// Store encryptedUsername and encryptedPassword as needed
}
}

override fun onAuthenticationError(
errorCode: Int, errString: CharSequence
) {
super.onAuthenticationError(errorCode, errString)
// Handle authentication errors
}

override fun onAuthenticationFailed() {
super.onAuthenticationFailed()
// Handle authentication failures
}
}
)

val cipher = Cipher.getInstance(
KeyProperties.KEY_ALGORITHM_AES + "/"
+ KeyProperties.BLOCK_MODE_GCM + "/"
+ KeyProperties.ENCRYPTION_PADDING_NONE
)

val secretKeyEntry = keyStore.getEntry(KEY_ALIAS, null) as KeyStore.SecretKeyEntry
val secretKey = secretKeyEntry.secretKey

val gcmSpec = GCMParameterSpec.Builder()
.setKeySize(256)
.setNonce(ByteArray(12)) // You need to generate a random nonce for each encryption
.build()

cipher.init(Cipher.ENCRYPT_MODE, secretKey, gcmSpec)

val promptInfo = BiometricPrompt.PromptInfo.Builder()
.setTitle("Authenticate to access credentials")
.setSubtitle("Using your biometric")
.setDescription("Authenticate using your fingerprint to access your credentials.")
.setNegativeButtonText("Cancel")
.build()

biometricPrompt.authenticate(promptInfo, BiometricPrompt.CryptoObject(cipher))
}
}


Источник: https://stackoverflow.com/questions/769 ... metric-api
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Android»