0

I have following code:

let keyData = UUID().uuidString.data(using: .utf8)!

var attributes: [NSString: Any] = [
    kSecClass: kSecClassKey,
    kSecAttrApplicationTag: keyData,
]
let st1 = SecItemDelete(attributes as CFDictionary)
attributes[kSecValueData] = keyData
let st2 = SecItemAdd(attributes as CFDictionary, nil)

I am trying to add item to the keychain with type kSecClassKey. For some reason this code works perfectly in iOS and doesn't work in macOS. In macOS st1 is -25300 (which means The item cannot be found.) and st2 is -25299 (which means The item already exists.) What can I do to make this code work?

1 Answer 1

1

The error errSecDuplicateItem (-25299) might also be returned if you miss a mandatory attribute, e.g., if you try to add a kSecClassGenericPassword key without the kSecAttrService set.

In your case I wonder why you try to store the UUID as a cryptographic key (kSecClassKey). Storing it as a generic password (kSecClassGenericPassword) instead would suffice.

let keyData = UUID().uuidString.data(using: .utf8)!

var attributes: [NSString: Any] = [
    kSecClass: kSecClassGenericPassword,
    kSecAttrService: "YourApp-UUID", // Determines the purpose/context of the used password/value
    kSecAttrLabel: "YourApp (UUID)", // Name of the Keychain item
    kSecValueData: keyData, // Actual value, that will be stored securely
]
let status = SecItemAdd(attributes as CFDictionary, nil)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.