Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store and retrieve private key from Mac keychain programmatically

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.

like image 706
Subhash Avatar asked Jun 29 '11 13:06

Subhash


People also ask

Where is the private key on Mac keychain?

Where Is the Private Key? To locate the private key in Keychain, search the CSR common name in All Items in the Login keychain. There should be a public key (the CSR) and a private key matching the common name you entered when generating the CSR.

What is Privatekey in keychain Mac?

With this type of encryption, the private keys are a form of a secret password, and one that only you can and should know. The public key is another password, but one that you can tell everybody about.) Rather than barging into Keychain without notice, Mail is asking permission.


1 Answers

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.

like image 164
Karoy Lorentey Avatar answered Oct 09 '22 12:10

Karoy Lorentey