|
| 1 | +package com.example.identity.credentialmanager |
| 2 | + |
| 3 | +import android.annotation.SuppressLint |
| 4 | +import android.app.Activity |
| 5 | +import android.app.PendingIntent |
| 6 | +import android.content.Intent |
| 7 | +import android.os.Build.VERSION_CODES |
| 8 | +import android.os.Bundle |
| 9 | +import android.os.PersistableBundle |
| 10 | +import androidx.annotation.RequiresApi |
| 11 | +import androidx.biometric.BiometricManager |
| 12 | +import androidx.biometric.BiometricPrompt |
| 13 | +import androidx.biometric.BiometricPrompt.AuthenticationCallback |
| 14 | +import androidx.biometric.BiometricPrompt.AuthenticationResult |
| 15 | +import androidx.credentials.CreatePasswordRequest |
| 16 | +import androidx.credentials.CreatePasswordResponse |
| 17 | +import androidx.credentials.CreatePublicKeyCredentialRequest |
| 18 | +import androidx.credentials.CreatePublicKeyCredentialResponse |
| 19 | +import androidx.credentials.GetCredentialResponse |
| 20 | +import androidx.credentials.GetPasswordOption |
| 21 | +import androidx.credentials.GetPublicKeyCredentialOption |
| 22 | +import androidx.credentials.PasswordCredential |
| 23 | +import androidx.credentials.PublicKeyCredential |
| 24 | +import androidx.credentials.provider.BeginCreateCredentialRequest |
| 25 | +import androidx.credentials.provider.BeginCreateCredentialResponse |
| 26 | +import androidx.credentials.provider.BeginCreatePasswordCredentialRequest |
| 27 | +import androidx.credentials.provider.BeginCreatePublicKeyCredentialRequest |
| 28 | +import androidx.credentials.provider.CallingAppInfo |
| 29 | +import androidx.credentials.provider.CreateEntry |
| 30 | +import androidx.credentials.provider.PendingIntentHandler |
| 31 | +import androidx.credentials.webauthn.AuthenticatorAssertionResponse |
| 32 | +import androidx.credentials.webauthn.AuthenticatorAttestationResponse |
| 33 | +import androidx.credentials.webauthn.FidoPublicKeyCredential |
| 34 | +import androidx.credentials.webauthn.PublicKeyCredentialCreationOptions |
| 35 | +import androidx.credentials.webauthn.PublicKeyCredentialRequestOptions |
| 36 | +import androidx.fragment.app.FragmentActivity |
| 37 | +import java.math.BigInteger |
| 38 | +import java.security.KeyPair |
| 39 | +import java.security.KeyPairGenerator |
| 40 | +import java.security.MessageDigest |
| 41 | +import java.security.SecureRandom |
| 42 | +import java.security.Signature |
| 43 | +import java.security.interfaces.ECPrivateKey |
| 44 | +import java.security.spec.ECGenParameterSpec |
| 45 | +import java.security.spec.ECParameterSpec |
| 46 | +import java.security.spec.ECPoint |
| 47 | +import java.security.spec.EllipticCurve |
| 48 | + |
| 49 | +class CredentialProviderDummyActivity: FragmentActivity() { |
| 50 | + |
| 51 | + private val PERSONAL_ACCOUNT_ID: String = "" |
| 52 | + private val FAMILY_ACCOUNT_ID: String = "" |
| 53 | + private val CREATE_PASSWORD_INTENT: String = "" |
| 54 | + |
| 55 | + @RequiresApi(VERSION_CODES.M) |
| 56 | + // [START android_identity_credential_provider_handle_passkey] |
| 57 | + override fun onCreate(savedInstanceState: Bundle?, persistentState: PersistableBundle?) { |
| 58 | + super.onCreate(savedInstanceState, persistentState) |
| 59 | + // ... |
| 60 | + |
| 61 | + val request = |
| 62 | + PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent) |
| 63 | + |
| 64 | + val accountId = intent.getStringExtra(CredentialsRepo.EXTRA_KEY_ACCOUNT_ID) |
| 65 | + if (request != null && request.callingRequest is CreatePublicKeyCredentialRequest) { |
| 66 | + val publicKeyRequest: CreatePublicKeyCredentialRequest = |
| 67 | + request.callingRequest as CreatePublicKeyCredentialRequest |
| 68 | + createPasskey( |
| 69 | + publicKeyRequest.requestJson, |
| 70 | + request.callingAppInfo, |
| 71 | + publicKeyRequest.clientDataHash, |
| 72 | + accountId |
| 73 | + ) |
| 74 | + } |
| 75 | + } |
| 76 | + |
| 77 | + @SuppressLint("RestrictedApi") |
| 78 | + fun createPasskey( |
| 79 | + requestJson: String, |
| 80 | + callingAppInfo: CallingAppInfo?, |
| 81 | + clientDataHash: ByteArray?, |
| 82 | + accountId: String? |
| 83 | + ) { |
| 84 | + val request = PublicKeyCredentialCreationOptions(requestJson) |
| 85 | + |
| 86 | + val biometricPrompt = BiometricPrompt( |
| 87 | + this, |
| 88 | + { }, // Pass in your own executor |
| 89 | + object : AuthenticationCallback() { |
| 90 | + override fun onAuthenticationError(errorCode: Int, errString: CharSequence) { |
| 91 | + super.onAuthenticationError(errorCode, errString) |
| 92 | + finish() |
| 93 | + } |
| 94 | + |
| 95 | + override fun onAuthenticationFailed() { |
| 96 | + super.onAuthenticationFailed() |
| 97 | + finish() |
| 98 | + } |
| 99 | + |
| 100 | + @RequiresApi(VERSION_CODES.P) |
| 101 | + override fun onAuthenticationSucceeded( |
| 102 | + result: AuthenticationResult |
| 103 | + ) { |
| 104 | + super.onAuthenticationSucceeded(result) |
| 105 | + |
| 106 | + // Generate a credentialId |
| 107 | + val credentialId = ByteArray(32) |
| 108 | + SecureRandom().nextBytes(credentialId) |
| 109 | + |
| 110 | + // Generate a credential key pair |
| 111 | + val spec = ECGenParameterSpec("secp256r1") |
| 112 | + val keyPairGen = KeyPairGenerator.getInstance("EC"); |
| 113 | + keyPairGen.initialize(spec) |
| 114 | + val keyPair = keyPairGen.genKeyPair() |
| 115 | + |
| 116 | + // Save passkey in your database as per your own implementation |
| 117 | + |
| 118 | + // Create AuthenticatorAttestationResponse object to pass to |
| 119 | + // FidoPublicKeyCredential |
| 120 | + |
| 121 | + val response = AuthenticatorAttestationResponse( |
| 122 | + requestOptions = request, |
| 123 | + credentialId = credentialId, |
| 124 | + credentialPublicKey = getPublicKeyFromKeyPair(keyPair), |
| 125 | + origin = appInfoToOrigin(callingAppInfo!!), |
| 126 | + up = true, |
| 127 | + uv = true, |
| 128 | + be = true, |
| 129 | + bs = true, |
| 130 | + packageName = callingAppInfo.packageName |
| 131 | + ) |
| 132 | + |
| 133 | + val credential = FidoPublicKeyCredential( |
| 134 | + rawId = credentialId, |
| 135 | + response = response, |
| 136 | + authenticatorAttachment = "", // Add your authenticator attachment |
| 137 | + ) |
| 138 | + val result = Intent() |
| 139 | + |
| 140 | + val createPublicKeyCredResponse = |
| 141 | + CreatePublicKeyCredentialResponse(credential.json()) |
| 142 | + |
| 143 | + // Set the CreateCredentialResponse as the result of the Activity |
| 144 | + PendingIntentHandler.setCreateCredentialResponse( |
| 145 | + result, |
| 146 | + createPublicKeyCredResponse |
| 147 | + ) |
| 148 | + setResult(RESULT_OK, result) |
| 149 | + finish() |
| 150 | + } |
| 151 | + } |
| 152 | + ) |
| 153 | + |
| 154 | + val promptInfo = BiometricPrompt.PromptInfo.Builder() |
| 155 | + .setTitle("Use your screen lock") |
| 156 | + .setSubtitle("Create passkey for ${request.rp.name}") |
| 157 | + .setAllowedAuthenticators( |
| 158 | + BiometricManager.Authenticators.BIOMETRIC_STRONG |
| 159 | + /* or BiometricManager.Authenticators.DEVICE_CREDENTIAL */ |
| 160 | + ) |
| 161 | + .build() |
| 162 | + biometricPrompt.authenticate(promptInfo) |
| 163 | + } |
| 164 | + |
| 165 | + @RequiresApi(VERSION_CODES.P) |
| 166 | + fun appInfoToOrigin(info: CallingAppInfo): String { |
| 167 | + val cert = info.signingInfo.apkContentsSigners[0].toByteArray() |
| 168 | + val md = MessageDigest.getInstance("SHA-256"); |
| 169 | + val certHash = md.digest(cert) |
| 170 | + // This is the format for origin |
| 171 | + return "android:apk-key-hash:${b64Encode(certHash)}" |
| 172 | + } |
| 173 | + // [END android_identity_credential_provider_handle_passkey] |
| 174 | + |
| 175 | + @RequiresApi(VERSION_CODES.M) |
| 176 | + // [START android_identity_credential_provider_password_creation] |
| 177 | + fun processCreateCredentialRequest( |
| 178 | + request: BeginCreateCredentialRequest |
| 179 | + ): BeginCreateCredentialResponse? { |
| 180 | + when (request) { |
| 181 | + is BeginCreatePublicKeyCredentialRequest -> { |
| 182 | + // Request is passkey type |
| 183 | + return handleCreatePasskeyQuery(request) |
| 184 | + } |
| 185 | + |
| 186 | + is BeginCreatePasswordCredentialRequest -> { |
| 187 | + // Request is password type |
| 188 | + return handleCreatePasswordQuery(request) |
| 189 | + } |
| 190 | + } |
| 191 | + return null |
| 192 | + } |
| 193 | + |
| 194 | + @RequiresApi(VERSION_CODES.M) |
| 195 | + private fun handleCreatePasswordQuery( |
| 196 | + request: BeginCreatePasswordCredentialRequest |
| 197 | + ): BeginCreateCredentialResponse { |
| 198 | + val createEntries: MutableList<CreateEntry> = mutableListOf() |
| 199 | + |
| 200 | + // Adding two create entries - one for storing credentials to the 'Personal' |
| 201 | + // account, and one for storing them to the 'Family' account. These |
| 202 | + // accounts are local to this sample app only. |
| 203 | + createEntries.add( |
| 204 | + CreateEntry( |
| 205 | + PERSONAL_ACCOUNT_ID, |
| 206 | + createNewPendingIntent(PERSONAL_ACCOUNT_ID, CREATE_PASSWORD_INTENT) |
| 207 | + ) |
| 208 | + ) |
| 209 | + createEntries.add( |
| 210 | + CreateEntry( |
| 211 | + FAMILY_ACCOUNT_ID, |
| 212 | + createNewPendingIntent(FAMILY_ACCOUNT_ID, CREATE_PASSWORD_INTENT) |
| 213 | + ) |
| 214 | + ) |
| 215 | + |
| 216 | + return BeginCreateCredentialResponse(createEntries) |
| 217 | + } |
| 218 | + // [END android_identity_credential_provider_password_creation] |
| 219 | + |
| 220 | + @RequiresApi(VERSION_CODES.M) |
| 221 | + fun handleEntrySelectionForPasswordCreation( |
| 222 | + mDatabase: MyDatabase |
| 223 | + ) { |
| 224 | + // [START android_identity_credential_provider_entry_selection_password_creation] |
| 225 | + val createRequest = PendingIntentHandler.retrieveProviderCreateCredentialRequest(intent) |
| 226 | + val accountId = intent.getStringExtra(CredentialsRepo.EXTRA_KEY_ACCOUNT_ID) |
| 227 | + |
| 228 | + if (createRequest == null) { |
| 229 | + return |
| 230 | + } |
| 231 | + |
| 232 | + val request: CreatePasswordRequest = createRequest.callingRequest as CreatePasswordRequest |
| 233 | + |
| 234 | + // Fetch the ID and password from the request and save it in your database |
| 235 | + mDatabase.addNewPassword( |
| 236 | + PasswordInfo( |
| 237 | + request.id, |
| 238 | + request.password, |
| 239 | + createRequest.callingAppInfo.packageName |
| 240 | + ) |
| 241 | + ) |
| 242 | + |
| 243 | + //Set the final response back |
| 244 | + val result = Intent() |
| 245 | + val response = CreatePasswordResponse() |
| 246 | + PendingIntentHandler.setCreateCredentialResponse(result, response) |
| 247 | + setResult(Activity.RESULT_OK, result) |
| 248 | + finish() |
| 249 | + // [END android_identity_credential_provider_entry_selection_password_creation] |
| 250 | + } |
| 251 | + |
| 252 | + @RequiresApi(VERSION_CODES.P) |
| 253 | + private fun handleUserSelectionForPasskeys( |
| 254 | + mDatabase: MyDatabase |
| 255 | + ) { |
| 256 | + // [START android_identity_credential_provider_user_pk_selection] |
| 257 | + val getRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent) |
| 258 | + val publicKeyRequest = getRequest?.credentialOptions?.first() as GetPublicKeyCredentialOption |
| 259 | + |
| 260 | + val requestInfo = intent.getBundleExtra("CREDENTIAL_DATA") |
| 261 | + val credIdEnc = requestInfo?.getString("credId").orEmpty() |
| 262 | + |
| 263 | + // Get the saved passkey from your database based on the credential ID from the PublicKeyRequest |
| 264 | + val passkey = mDatabase.getPasskey(credIdEnc) |
| 265 | + |
| 266 | + // Decode the credential ID, private key and user ID |
| 267 | + val credId = b64Decode(credIdEnc) |
| 268 | + val privateKey = b64Decode(passkey.credPrivateKey) |
| 269 | + val uid = b64Decode(passkey.uid) |
| 270 | + |
| 271 | + val origin = appInfoToOrigin(getRequest.callingAppInfo) |
| 272 | + val packageName = getRequest.callingAppInfo.packageName |
| 273 | + |
| 274 | + validatePasskey( |
| 275 | + publicKeyRequest.requestJson, |
| 276 | + origin, |
| 277 | + packageName, |
| 278 | + uid, |
| 279 | + passkey.username, |
| 280 | + credId, |
| 281 | + privateKey |
| 282 | + ) |
| 283 | + // [END android_identity_credential_provider_user_pk_selection] |
| 284 | + } |
| 285 | + |
| 286 | + @SuppressLint("RestrictedApi") |
| 287 | + @RequiresApi(VERSION_CODES.M) |
| 288 | + private fun validatePasskey( |
| 289 | + requestJson: String, |
| 290 | + origin: String, |
| 291 | + packageName: String, |
| 292 | + uid: ByteArray, |
| 293 | + username: String, |
| 294 | + credId: ByteArray, |
| 295 | + privateKeyBytes: ByteArray, |
| 296 | + ) { |
| 297 | + // [START android_identity_credential_provider_user_validation_biometric] |
| 298 | + val request = PublicKeyCredentialRequestOptions(requestJson) |
| 299 | + val privateKey: ECPrivateKey = convertPrivateKey(privateKeyBytes) |
| 300 | + |
| 301 | + val biometricPrompt = BiometricPrompt( |
| 302 | + this, |
| 303 | + { }, // Pass in your own executor |
| 304 | + object : BiometricPrompt.AuthenticationCallback() { |
| 305 | + override fun onAuthenticationError( |
| 306 | + errorCode: Int, errString: CharSequence |
| 307 | + ) { |
| 308 | + super.onAuthenticationError(errorCode, errString) |
| 309 | + finish() |
| 310 | + } |
| 311 | + |
| 312 | + override fun onAuthenticationFailed() { |
| 313 | + super.onAuthenticationFailed() |
| 314 | + finish() |
| 315 | + } |
| 316 | + |
| 317 | + override fun onAuthenticationSucceeded( |
| 318 | + result: BiometricPrompt.AuthenticationResult |
| 319 | + ) { |
| 320 | + super.onAuthenticationSucceeded(result) |
| 321 | + val response = AuthenticatorAssertionResponse( |
| 322 | + requestOptions = request, |
| 323 | + credentialId = credId, |
| 324 | + origin = origin, |
| 325 | + up = true, |
| 326 | + uv = true, |
| 327 | + be = true, |
| 328 | + bs = true, |
| 329 | + userHandle = uid, |
| 330 | + packageName = packageName |
| 331 | + ) |
| 332 | + |
| 333 | + val sig = Signature.getInstance("SHA256withECDSA"); |
| 334 | + sig.initSign(privateKey) |
| 335 | + sig.update(response.dataToSign()) |
| 336 | + response.signature = sig.sign() |
| 337 | + |
| 338 | + val credential = FidoPublicKeyCredential( |
| 339 | + rawId = credId, |
| 340 | + response = response, |
| 341 | + authenticatorAttachment = "", // Add your authenticator attachment |
| 342 | + ) |
| 343 | + val result = Intent() |
| 344 | + val passkeyCredential = PublicKeyCredential(credential.json()) |
| 345 | + PendingIntentHandler.setGetCredentialResponse( |
| 346 | + result, GetCredentialResponse(passkeyCredential) |
| 347 | + ) |
| 348 | + setResult(RESULT_OK, result) |
| 349 | + finish() |
| 350 | + } |
| 351 | + } |
| 352 | + ) |
| 353 | + |
| 354 | + val promptInfo = BiometricPrompt.PromptInfo.Builder() |
| 355 | + .setTitle("Use your screen lock") |
| 356 | + .setSubtitle("Use passkey for ${request.rpId}") |
| 357 | + .setAllowedAuthenticators( |
| 358 | + BiometricManager.Authenticators.BIOMETRIC_STRONG |
| 359 | + /* or BiometricManager.Authenticators.DEVICE_CREDENTIAL */ |
| 360 | + ) |
| 361 | + .build() |
| 362 | + biometricPrompt.authenticate(promptInfo) |
| 363 | + // [END android_identity_credential_provider_user_validation_biometric] |
| 364 | + } |
| 365 | + |
| 366 | + @RequiresApi(VERSION_CODES.M) |
| 367 | + private fun handleUserSelectionForPasswordAuthentication( |
| 368 | + mDatabase: MyDatabase, |
| 369 | + callingAppInfo: CallingAppInfo, |
| 370 | + ) { |
| 371 | + // [START android_identity_credential_provider_user_selection_password] |
| 372 | + val getRequest = PendingIntentHandler.retrieveProviderGetCredentialRequest(intent) |
| 373 | + |
| 374 | + val passwordOption = getRequest?.credentialOptions?.first() as GetPasswordOption |
| 375 | + |
| 376 | + val username = passwordOption.allowedUserIds.first() |
| 377 | + // Fetch the credentials for the calling app package name |
| 378 | + val creds = mDatabase.getCredentials(callingAppInfo.packageName) |
| 379 | + val passwords = creds.passwords |
| 380 | + val it = passwords.iterator() |
| 381 | + var password = "" |
| 382 | + while (it.hasNext()) { |
| 383 | + val passwordItemCurrent = it.next() |
| 384 | + if (passwordItemCurrent.username == username) { |
| 385 | + password = passwordItemCurrent.password |
| 386 | + break |
| 387 | + } |
| 388 | + } |
| 389 | + // [END android_identity_credential_provider_user_selection_password] |
| 390 | + |
| 391 | + // [START android_identity_credential_provider_set_response] |
| 392 | + // Set the response back |
| 393 | + val result = Intent() |
| 394 | + val passwordCredential = PasswordCredential(username, password) |
| 395 | + PendingIntentHandler.setGetCredentialResponse( |
| 396 | + result, GetCredentialResponse(passwordCredential) |
| 397 | + ) |
| 398 | + setResult(Activity.RESULT_OK, result) |
| 399 | + finish() |
| 400 | + // [END android_identity_credential_provider_set_response] |
| 401 | + } |
| 402 | + |
| 403 | + // [START android_identity_credential_pending_intent] |
| 404 | + fun createSettingsPendingIntent(): PendingIntent |
| 405 | + // [END android_identity_credential_pending_intent] |
| 406 | + { |
| 407 | + return PendingIntent.getBroadcast(this, 0, Intent(), PendingIntent.FLAG_IMMUTABLE) |
| 408 | + } |
| 409 | + |
| 410 | + private fun getPublicKeyFromKeyPair(keyPair: KeyPair): ByteArray { |
| 411 | + return byteArrayOf() |
| 412 | + } |
| 413 | + |
| 414 | + private fun b64Encode(certHash: ByteArray) {} |
| 415 | + |
| 416 | + private fun handleCreatePasskeyQuery( |
| 417 | + request: BeginCreatePublicKeyCredentialRequest |
| 418 | + ): BeginCreateCredentialResponse { |
| 419 | + return BeginCreateCredentialResponse() |
| 420 | + } |
| 421 | + |
| 422 | + private fun createNewPendingIntent( |
| 423 | + accountId: String, |
| 424 | + intent: String |
| 425 | + ): PendingIntent { |
| 426 | + return PendingIntent.getBroadcast(this, 0, Intent(), PendingIntent.FLAG_IMMUTABLE) |
| 427 | + } |
| 428 | + |
| 429 | + private fun b64Decode(encodedString: String): ByteArray { |
| 430 | + return byteArrayOf() |
| 431 | + } |
| 432 | + |
| 433 | + private fun convertPrivateKey(privateKeyBytes: ByteArray): ECPrivateKey { |
| 434 | + return ECPrivateKeyImpl() |
| 435 | + } |
| 436 | +} |
| 437 | + |
| 438 | +object CredentialsRepo { |
| 439 | + const val EXTRA_KEY_ACCOUNT_ID: String = "" |
| 440 | +} |
| 441 | + |
| 442 | +class MyDatabase { |
| 443 | + fun addNewPassword(passwordInfo: PasswordInfo) {} |
| 444 | + |
| 445 | + fun getPasskey(credIdEnc: String): PasskeyInfo { |
| 446 | + return PasskeyInfo() |
| 447 | + } |
| 448 | + |
| 449 | + fun getCredentials(packageName: String): CredentialsInfo { |
| 450 | + return CredentialsInfo() |
| 451 | + } |
| 452 | +} |
| 453 | + |
| 454 | +data class PasswordInfo( |
| 455 | + val id: String = "", |
| 456 | + val password: String = "", |
| 457 | + val packageName: String = "", |
| 458 | + val username: String = "" |
| 459 | +) |
| 460 | + |
| 461 | +data class PasskeyInfo( |
| 462 | + val credPrivateKey: String = "", |
| 463 | + val uid: String = "", |
| 464 | + val username: String = "" |
| 465 | +) |
| 466 | + |
| 467 | +data class CredentialsInfo( |
| 468 | + val passwords: List<PasswordInfo> = listOf() |
| 469 | +) |
| 470 | + |
| 471 | +class ECPrivateKeyImpl: ECPrivateKey { |
| 472 | + override fun getAlgorithm(): String = "" |
| 473 | + override fun getFormat(): String = "" |
| 474 | + override fun getEncoded(): ByteArray = byteArrayOf() |
| 475 | + override fun getParams(): ECParameterSpec { |
| 476 | + return ECParameterSpec( |
| 477 | + EllipticCurve( |
| 478 | + { 0 }, |
| 479 | + BigInteger.ZERO, |
| 480 | + BigInteger.ZERO |
| 481 | + ), |
| 482 | + ECPoint( |
| 483 | + BigInteger.ZERO, |
| 484 | + BigInteger.ZERO |
| 485 | + ), |
| 486 | + BigInteger.ZERO, |
| 487 | + 0 |
| 488 | + ) |
| 489 | + } |
| 490 | + override fun getS(): BigInteger = BigInteger.ZERO |
| 491 | +} |
0 commit comments