Last active
June 28, 2025 11:59
-
-
Save algrid/b78f755a9b4cea07ddfecff7fd9a2619 to your computer and use it in GitHub Desktop.
Creating a cryptographic key stored in Secure Enclave
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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