我丢失了我的公钥。我可以从私钥中恢复吗?

问题描述:

我为iOS / OSX开发创建了密钥对+签名证书。在某个地方,我丢失了与我的私钥一起使用的公钥。也许是因为Keychain Access没有将私钥和公钥组合在一起,就像它与证书和私钥一样(这太刺激了!为什么(不)那样做!)

I created a key pair + signed certificate for iOS/OSX development. Somewhere along the way, I lost the public key that goes with my private key. Maybe it's because Keychain Access doesn't group the private and public keys together, like it does with certificates and private keys (that is so irritating! why does it (not) do that!)

在Keychain Access中,我仍然可以右键单击私钥 - >申请证书;但没有公钥可用,我收到错误无法在钥匙串中找到指定的项目。我非常确保公钥是可恢复的,但是如何?显然,Keychain Access不够智能,无法自动完成。

In Keychain Access, I can still right-click the private key -> "Request a certificate"; but without the public key available I get the error "The specified item could not be found in the keychain". I am pretty sure that public keys are recoverable, but how? Obviously, Keychain Access isn't smart enough to do it automatically.

我最终想出来并在几天之后将我的答案标记为正确,除非有人添加新内容答案。

I eventually figured this out and will mark my answer correct after a few days, unless someone adds something new to the answer.

我记得模糊地能够通过.pem文件上的openssl做到这一点,所以这是我的方向。

I remembered vaguely being able to do this with openssl on .pem files, so that's the direction I headed.


  • 在Keychain Access中,导出私钥,例如 private.p12 。是否应用密码。

  • 将其转换为.pem: openssl pkcs12 -in private.p12 -out private.pem 。输入上一步的密码。您被迫将密码应用于.pem。

  • 提取公共部分: openssl rsa -in private.pem -poutout> public.pem 。输入上一步的密码。

  • 导入钥匙串访问:安全导入public.pem -k login.keychain 。如果您没有指定钥匙串,导入似乎已完成,但我无法找到该项目的放置位置。

  • 在钥匙串访问中,查看登录钥匙串中的导入的公共键。重命名并移动到所需位置。

  • 自行清理,特别是没有密码或密码不佳的.p12和.pem私钥。

  • In Keychain Access, export the private key as eg private.p12. Apply a password, or not.
  • Convert it to .pem: openssl pkcs12 -in private.p12 -out private.pem. Enter password from previous step. You're forced to apply a password to the .pem.
  • Extract the public portion: openssl rsa -in private.pem -pubout > public.pem. Enter password from previous step.
  • Import into Keychain Access: security import public.pem -k login.keychain. If you don't specify a keychain, the import appears to complete but I couldn't find where the item was put.
  • In Keychain Access, look in the login keychain for "Imported Public Key". Rename it and move to the desired location.
  • Clean up after yourself, especially those .p12 and .pem private keys with no or poor passwords.