Intermittent failure accessing generated private keys

I'm using SecKeyCreateRandomKey to generate a private key, encrypting some data with that key (with the public key from the generated private key), and then saving that encrypted data in the keychain. I'm seeing some odd behavior where I'm occasionally unable to access the encryption key (SecItemCopyMatching returns errSecItemNotFound) even though I can access the encrypted data (returned status is errSecSuccess and the result value is populated correctly). Both items are using the same accessibility attributes, so I'm left thinking that either there's some data-loss happening (the worst-case scenario), or that there's something slightly wrong with my query that causes it to fail in some circumstances. I've been beating my head against this for way too long at this point without being able to make much progress forward, so any help here would be much appreciated.

Key generation:

let attributes: NSDictionary = [
  kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
  kSecAttrKeySizeInBits: 256,
  kSecAttrTokenID: kSecAttrTokenIDSecureEnclave,
  kSecPrivateKeyAttrs: [
    kSecClass: kSecClassKey,
    kSecAttrApplicationTag: "some_valid_tag".data(using: .utf8)!,
    kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
    kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
    kSecAttrAccessGroup: "SomeValidGroupIdentifier",
    kSecAttrIsPermanent: true,
  ],
]

var error: Unmanaged<CFError>?
guard let privateKey = SecKeyCreateRandomKey(attributes, &error) else {
  throw SomeError()
}

Key read operation:

let query: NSDictionary = [
  kSecClass: kSecClassKey,
  kSecAttrApplicationTag: "some_valid_tag".data(using: .utf8)!,
  kSecAttrKeyType: kSecAttrKeyTypeECSECPrimeRandom,
  kSecReturnRef: true,
]
var result: AnyObject?
let status = SecItemCopyMatching(query, &result)

For reference, the read/write queries I'm using for the encrypted data look like:

let readQuery = [
  kSecClass: kSecClassKey,
  kSecAttrApplicationTag: "some_valid_tag_data".data(using: .utf8)!,
  kSecReturnData: true,
]

let writeQuery = [
  kSecClass: kSecClassKey,
  kSecAttrApplicationTag: "some_valid_tag_data".data(using: .utf8)!,
  kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
  kSecAttrAccessGroup: "SomeValidGroupIdentifier,
]

Is there something I'm missing here? Is there a way for me to get more insight into why the query is failing?

Replies

Intermittent failure accessing generated private keys

What platform is this on?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

  • Ah, sorry. This is on iOS.

Add a Comment