Store and retrieve secret key from Mac keychain software

In the Mac application, I have a requirement to store the secret key sent from the server to log in to the system by the user in a safe way, and return it if necessary programmatically. I know that a keychain is the best place to store a private key. Is there any sample code for this?

I can add the private key to the keychain using the SecKeychainItemImport method for "Security.framework", but having problems returning the private key from the keychain. I tried using the SecKeychainItemCopyAttributesAndData and SecKeychainItemCopyContent methods to get the private key from the key fob. But so far no luck.

I also read on blogs that mention the secret keystore in the hidden ".ssh" folder. But I feel that storing the private key inside the keychain provides another level of security, so that someone else cannot have easy access to the private key.

+6
source share
2 answers

One of the goals of Keychain is to keep secret keys without exposing their data to the application. To prevent accidental disclosure of the private key, by default these elements are marked CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_SENSITIVE CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_SENSITIVE ; that is, their data can only be obtained using SecKeychainItemExport and only in a format protected by a passphrase.

The security structure has APIs that encrypt / decrypt / sign / verify, etc. data using the supplied key element, without putting the primary key data in the address space of the application. (These operations are usually performed by a separate, privileged process.)

If for some reason you need access to the raw bits of a private key, you need to prepare for this when you import the private key into the key chain. You need to set keyAttributes to CSSM_KEYATTR_EXTRACTABLE (i.e. Without a sensitive bit) in the keyParams SecKeychainItemImport parameter.

+4
source

Source: https://habr.com/ru/post/891637/


All Articles