attestKey(_:clientDataHash:completionHandler:)
Asks Apple to attest to the validity of a generated cryptographic key.
Declaration
func attestKey(_ keyId: String, clientDataHash: Data, completionHandler: @escaping @Sendable (Data?, (any Error)?) -> Void)func attestKey(_ keyId: String, clientDataHash: Data) async throws -> DataParameters
- keyId:
The identifier you received when generating a cryptographic key by calling the Generatekey(completionhandler:) method.
- clientDataHash:
A SHA256 hash of a unique, single-use data block that embeds a challenge from your server. Should be at least 16 bytes in length.
- completionHandler:
A closure that the method calls upon completion with the following parameters:
attestationObject: A statement from Apple about the validity of the key associated withkeyId. Send this to your server for processing.error: A Dcerror Swift.struct instance that indicates the reason for failure, ornilon success.
Mentioned in
Discussion
This method asks Apple to attest to the validity of a key that you previously generated with a call to the generateKey(completionHandler:) method. Provide the method with both the key identifier and a computed hash of a data block that includes a one-time challenge from your server to prevent replay attacks. For example, you can use CryptoKit to create a SHA256 hash of challenge data:
import CryptoKit let hash = Data(SHA256.hash(data: challenge)) // A
challenge from your server.The attest method calls its completion handler to return an attestation object to you, which you must send to your server for verification. A compromised version of your app could falsify the verification result, thus circumventing App Attest.
If you successfully verify the attestation object on your server, as described in Validating apps that connect to your server, then you can associate the key identifier with the user on the device for future reference. You’ll need the identifier to generate assertions with calls to generateAssertion(_:clientDataHash:completionHandler:). If your server fails to verify the attestation object, discard the key identifier.
If the method’s completion handler returns the serverUnavailable error — typically due to network connectivity issues — it means that the framework failed to reach the App Attest service to complete the attestation. In this case, retry attestation again using the same key and client data hash later to avoid unnecessarily generating new keys. Retrying with the same inputs helps to preserve the risk metric for a given device.