Skip to content

Instantly share code, notes, and snippets.

@algrid
Last active June 28, 2025 11:59
Show Gist options
  • Select an option

  • Save algrid/b78f755a9b4cea07ddfecff7fd9a2619 to your computer and use it in GitHub Desktop.

Select an option

Save algrid/b78f755a9b4cea07ddfecff7fd9a2619 to your computer and use it in GitHub Desktop.
Creating a cryptographic key stored in Secure Enclave
static func makeAndStoreKey(name: String,
requiresBiometry: Bool = false) throws -> SecKey {
let flags: SecAccessControlCreateFlags
if #available(iOS 11.3, *) {
flags = requiresBiometry ?
[.privateKeyUsage, .biometryCurrentSet] : .privateKeyUsage
} else {
flags = requiresBiometry ?
[.privateKeyUsage, .touchIDCurrentSet] : .privateKeyUsage
}
let access =
SecAccessControlCreateWithFlags(kCFAllocatorDefault,
kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
flags,
nil)!
let tag = name.data(using: .utf8)!
let attributes: [String: Any] = [
kSecAttrKeyType as String : kSecAttrKeyTypeEC,
kSecAttrKeySizeInBits as String : 256,
kSecAttrTokenID as String : kSecAttrTokenIDSecureEnclave,
kSecPrivateKeyAttrs as String : [
kSecAttrIsPermanent as String : true,
kSecAttrApplicationTag as String : tag,
kSecAttrAccessControl as String : access
]
]
var error: Unmanaged<CFError>?
guard let privateKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else {
throw error!.takeRetainedValue() as Error
}
return privateKey
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment