Objective-c – Store and retrieve private key from Mac keychain programmatically

keychainmacosobjective cprivate-key

In a Mac application, I have a requirement to store the private key sent from the server for logged in user in a secure way and retrieve it back whenever needed programmatically. I know that keychain is the best place to store the private key. Is there any sample code available to achieve this?

I am able to add the private key to the keychain using "SecKeychainItemImport" method of "Security.framework" but having issues retrieving back the private key from the keychain. I have tried using "SecKeychainItemCopyAttributesAndData" and "SecKeychainItemCopyContent" methods for getting private key back from the keychain. But no luck so far.

I have also read in blogs mentioning private key storage inside ".ssh" hidden folder. But I feel that storing the private key inside the keychain provides one more level of security so that someone else can not have an easy access to the private key.

Best Answer

One purpose of the Keychain is to keep private keys protected by not exposing their data to the application. To prevent accidentally exposing a private key, these items are flagged CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_SENSITIVE by default; i.e., it is only possible to get their data using SecKeychainItemExport, and only in a passphrase-protected format.

There are APIs in the Security framework that encrypt/decrypt/sign/verify etc. data using a supplied key item without ever putting the raw key data in the application's address space. (These operations are normally done by a separate, privileged process.)

If for some reason you do need access to the private key's raw bits, you need to prepare for this at the time you import the private key to the keychain. You need to set keyAttributes to CSSM_KEYATTR_EXTRACTABLE (i.e., without the sensitive bit) in the keyParams parameter of SecKeychainItemImport.

Related Topic