Importing a PKCS8 key

My app allows the user to import a PKCS8 private key to use in the application which I will store in the keychain. The problem I am running into is how to handle the senario where the private key they want to use is already in the keychain. When I run this code


OSStatus err = SecItemImport((__bridge CFDataRef)keyData, NULL, &inputFormat, &itemType, kSecItemPemArmour, &importParameters, keychain, &items);


It is returning to me errSecDuplicateItem which is correct.


I need a way to reference that key in my application so how would I go about finding that duplicate?

Replies

This speaks to the question of keychain item uniqueness. I’ve discussed this before in the context of the iOS-style keychain. I don’t actually know how it works for the traditional Mac keychain but my guess is that it’s in a very similar way. To that end, when you import the key for the first time, what do you get back for

kSecAttrApplicationLabel
and
kSecAttrApplicationTag
?

ps If you’re not familiar with the iOS-style vs traditional Mac keychain dichotomy, check out this post, which explains some background to this.

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

I think this may have been a dumb question on my part. I am trying to figure out what to do with my app if the user trys to import a key for my application to use that is already in the keychain and is unknown to my application. When I am testing this senario I am generating the key using SecKeyGeneratePair in my app (and not setting

kSecAttrApplicationLabel
or
kSecAttrApplicationTag)
and then exporting it. So when I try to import that key it is already in the keychain. I think this senario may be an edge case so I will ignore this senario for now.