问题描述
在Mac应用程序中,我要求以安全的方式存储从服务器发送的用于登录用户的私钥,并在需要时以编程方式将其取回.我知道钥匙串是存储私钥的最佳位置.有没有可用的示例代码来实现这一目标?
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?
我可以使用"Security.framework"的"SecKeychainItemImport"方法将私钥添加到钥匙串中,但是在从钥匙串取回私钥时遇到了问题.我尝试使用"SecKeychainItemCopyAttributesAndData"和"SecKeychainItemCopyContent"方法从钥匙串中获取私钥.但到目前为止没有运气.
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.
我还读过博客,提到".ssh"隐藏文件夹内的私钥存储.但是我觉得将私钥存储在钥匙串中可以提供更高级别的安全性,从而使其他人无法轻松访问私钥.
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.
推荐答案
钥匙串的一个目的是通过不将私有数据公开给应用程序来保护私钥.为防止意外暴露私钥,默认情况下,这些项目标记为CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_SENSITIVE
;否则,将其标记为CSSM_KEYATTR_EXTRACTABLE | CSSM_KEYATTR_SENSITIVE
.即只能使用SecKeychainItemExport
并以受密码保护的格式获取其数据.
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.
安全性框架中有一些API,可以使用提供的密钥项对数据进行加密/解密/签名/验证等,而无需将原始密钥数据放在应用程序的地址空间中. (这些操作通常是由一个单独的特权进程完成的.)
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.)
如果由于某些原因您确实需要访问私钥的原始位,则需要在将私钥导入到钥匙串时为此做准备.您需要在SecKeychainItemImport
的keyParams
参数中将keyAttributes
设置为CSSM_KEYATTR_EXTRACTABLE
(即不使用敏感位).
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
.
这篇关于以编程方式从Mac钥匙串存储和检索私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!