How to encrypt an SSH private key

If you are using SSH key-based authentication you should be encrypting your private key. This ensures that if someone breaks into your server and steals your keys, they won’t be able to utilize them to access other systems. If your private key isn’t encrypted you can use the ssh-keygen utilities “-p” option to do so:

$ ssh-keygen -p -f id_dsa
Enter old passphrase:
Key has comment ‘id_dsa’
Enter new passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved with the new passphrase.

This option can be used to change the password used to encrypt a private key, and to add a password to an existing private key. Viva la OpenSSH!

4 thoughts on “How to encrypt an SSH private key”

  1. “This ensures that if someone breaks into your server and steals your keys […]”

    Let me stop you right there. Why is your private key on a server in the first place?

    And, let’s just assume that they are on the server, why don’t you have a passphrase so that simple possession of the private key + 25 cents still won’t get you a call on a payphone?

  2. @magnus919 – you ask: “Why is your private key on a server in the first place”

    Really, the point is that you should protect your private key with a passphrase so that it’s protected if someone breaks into whatever machine it’s stored on and steals it. You are correct that the private key does not need to be on the ssh server in order to connect to it with ssh, however that “server” may be, for example, a development machine and the user might want to connect from there to other “servers”, using SSH. In that case, the user might want to have private keys stored there.

  3. Regarding keeping private keys on a “development server” so you can further connect to other machines… I recently discovered agent-forwarding which handles this problem nicely. You only need your private key on the box you are physically sitting at, and it lets you go many hops, passing your auth along with you.

Leave a Reply

Your email address will not be published. Required fields are marked *