Post

Replies

Boosts

Views

Activity

Reply to SecItemCopyMatching not saving permanent key
Thanks for the response Quinn! I've made some adjustments to my code based on your response, but still have the same problem. I am still using SecCreateRandomKey but instead of saving to the keychain from this call, I get a reference and use this to save the key with SecItemAdd. I also tried this code first converting the new key into Data, then passing it to SecItemAdd as kSecValueData but that made no difference. You can see I query for a count of all keys before and after saving. On working systems, the count goes up by one, but on the failing systems the count does not go up but I get no error from SecItemAdd. The countAllKeys is making a call to the secCall function mentioned in the linked forum post. It simply asks for all entries of type kSecClassKey and no limit (i.e. kSecMatchLimitAll), then returns the count of the result. This is an attempt to eliminate the variable of “is the SecItemCopyMatching query correct for finding this specific key”. This is basically my code, with a few cosmetic edits to simplify. var error: Unmanaged<CFError>? guard let access = SecAccessControlCreateWithFlags(kCFAllocatorDefault, kSecAttrAccessibleWhenUnlocked, .biometryAny, &error) else { throw error!.takeRetainedValue() as Error } let attributes: [String: Any] = [ kSecAttrKeyType as String: KeyManager.KEY_TYPE, kSecAttrKeySizeInBits as String: 3072, ] guard let newKey = SecKeyCreateRandomKey(attributes as CFDictionary, &error) else { throw error!.takeRetainedValue() as Error } let query: [String: Any] = [ kSecClass as String: kSecClassKey, kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeyClass as String: kSecAttrKeyClassPrivate, kSecAttrApplicationTag as String: "com.example.key".data(using: .utf8)!, kSecAttrLabel as String: "com.example.key", kSecAttrAccessControl as String: access, kSecValueRef as String: newKey, kSecAttrIsPermanent as String: true, kSecUseDataProtectionKeychain as String: true, ] print("... Tagged key count: " + String(describing: try countAllKeys())) // see note below let status = SecItemAdd(query as CFDictionary, nil) print("... Added key with code: " + String(status)) print("... Tagged key count: " + String(describing: try countAllKeys())) guard status == errSecSuccess else { print(SecCopyErrorMessageString(status, nil)) }
Topic: Privacy & Security SubTopic: General Tags:
Feb ’25