Remove private key from Mac OS X keychain using Terminal

[亡魂溺海] 提交于 2019-12-02 20:21:06

There are several keychains on your system:

sudo security list-keychains
"/Users/JonDoe/Library/Keychains/login.keychain"
"/Library/Keychains/System.keychain"

I think you imported it into the System-Keychain: First make a backup of your System Root Certificates before making any changes (or any other keychain you choose):

cd /System/Library/Keychains/
sudo cp SystemRootCertificates.keychain SystemRootCertificates.keychain.old

List all keychains / all certificates in your keychain:

ls -l /System/Library/Keychains/
sudo security dump-keychain /System/Library/Keychains/SystemRootCertificates.keychain

With the second command each certificate of the keychain is shown. Identify the certificate you want to remove. Then remove the certificate with the following command:

sudo security delete-certificate -Z <SHA-1 hash of certificate> /System/Library/Keychains/SystemRootCertificates.keychain
**alternative:**
sudo security delete-certificate -c <common name of certificate> /System/Library/Keychains/SystemRootCertificates.keychain

That's all. Now you can import your certificate again. In case of an error, you can restore your keychain with the following command:

sudo security import certificate_files_backup -k /System/Library/Keychains/SystemRootCertificates.keychain -t cert

You can delete certificate and key by running a command in the terminal:

sudo security delete-identity -Z "SHA-1"

or

sudo security delete-identity -c "CommonName"

At the beginning I thought it removes only the key, but in fact it removes certificate too (you just need to close the keychain completely and open it again to see the changes - if you are verifying it with GUI).

From man security:

     delete-identity [-h] [-c name] [-Z hash] [-t] [keychain...]
        Delete a certificate and its private key from a keychain.  If no keychain arguments are provided, the default search list is used.

        -c name         Specify certificate to delete by its common name
        -Z hash         Specify certificate to delete by its SHA-1 hash
        -t              Also delete user trust settings for this identity certificate

You may need to unlock the keychain first (from man security):

 unlock-keychain [-hu] [-p password] [keychain]
        Unlock keychain, or the default keychain if none is specified.
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!