Tutorial

How To Create SSH Keys With PuTTY to Connect to a VPS

Published on July 19, 2013
author

Pablo Carranza

How To Create SSH Keys With PuTTY to Connect to a VPS

Benefits of Public & Private SSH Keys

If your headless, or remote, VPS is visible over the Internet, you should use public key authentication instead of passwords, if at all possible. This is because SSH keys provide a more secure way of logging in compared to using a password alone. While a password can eventually be cracked with a brute-force attack, SSH keys are nearly impossible to decipher by brute force alone. With public key authentication, every computer has (i) a public and (ii) a private "key" (two mathematically-linked algorithms that are effectively impossible to crack).

Today, OpenSSH is the default SSH implementation on Unix-like systems such as Linux and OS X. Key-based authentication is the most secure of several modes of authentication usable with OpenSSH, such as plain passwords and Kerberos tickets. Other authentication methods are only used in very specific situations. SSH can use either "RSA" (Rivest-Shamir-Adleman) or "DSA" ("Digital Signature Algorithm") keys. Both of these were considered state-of-the-art algorithms when SSH was invented, but DSA has come to be seen as less secure in recent years. RSA is the only recommended choice for new keys, so this tutorial uses "RSA key" and "SSH key" interchangeably.

When you log in to your DigitalOcean VPS, the SSH server uses the public key to "lock" messages in a way that can only be "unlocked" by your private key. This means that even the most resourceful attacker cannot snoop on, or interfere with, your session. As an extra security measure, some users and most SSH programs store the private key in a passphrase-protected format, to provide a window of time in which you can disable your compromised public key, should your computer be stolen or broken in to. For these reasons, public key authentication is a much better solution than passwords for most people. In fact, by not employing a passphrase on your private key, you will have the ability to automate parts of your configuration management with secure, automatic log-ins, such as incremental off-site backups, manage your DigitalOcean assets via the DigitalOcean API, and more.

Key-Based SSH Logins

You can save the same public key on as many cloud servers as you'd like, while your private key is saved on a client from which you log in to the server. Then, you can disable the normal username/password login procedure, which means that only people with a valid private/public key pair can log in; making your system more secure, because it will be impervious to brute-force attacks.

Automate the Creation of New Droplets

Another useful purpose that SSH keys can serve is in the creation of DigitalOcean droplets. As you know, when you spin up a droplet, you have to wait for an e-mail with your password. Although this email is very convenient, there is a more secure (and faster) way of gaining access to your new cloud server without the need for email. This can be done by saving your public key in the DigitalOcean Control Panel. To accomplish this:

Prerequisites

This tutorial assumes that you are familiar with DigitalOcean's guide on How to Log Into Your Droplet with PuTTY (for windows users).

PuTTY Key Generator (a.k.a. PuTTYgen)

While PuTTY is a client program for SSH (in addition to Telnet and Rlogin), it is not a port of or otherwise based on OpenSSH. Consequently, PuTTY does not have native support for reading OpenSSH's SSH-2 private key files. However, PuTTY does have a companion named PuTTYgen (an RSA and DSA key generation utility), that can convert OpenSSH private key files into PuTTY's format; allowing you to connect to your cloud server from a Windows machine, with the added security that SSH keys provide.

PuTTYgen is a (free) open-source utility and can be downloaded from the maintainer's website. PuTTYgen is what you will use to generate your SSH keys for use in PuTTY. To start, all you need to do is download the exectuable files (.exe) and save them on the computer that you'll use to connect to your VPS, e.g. on the desktop. You will not need to "install" PuTTYgen, because it is a standalone application.

Generating OpenSSH-compatible Keys for Use with PuTTY

To generate a set of RSA keys with PuTTYgen:

  1. Start the PuTTYgen utility, by double-clicking on its .exe file;
  2. For Type of key to generate, select RSA;
  3. In the Number of bits in a generated key field, specify either 2048 or 4096 (increasing the bits makes it harder to crack the key by brute-force methods);
  4. Click the Generate button;
  5. Move your mouse pointer around in the blank area of the Key section, below the progress bar (to generate some randomness) until the progress bar is full;
  6. A private/ public key pair has now been generated;
  7. In the Key comment field, enter any comment you'd like, to help you identify this key pair, later (e.g. your e-mail address; home; office; etc.) -- the key comment is particularly useful in the event you end up creating more than one key pair;
  8. Optional: Type a passphrase in the Key passphrase field & re-type the same passphrase in the Confirm passphrase field (if you would like to use your keys for automated processes, however, you should not create a passphrase);
  9. Click the Save public key button & choose whatever filename you'd like (some users create a folder in their computer named my_keys);
  10. Click the Save private key button & choose whatever filename you'd like (you can save it in the same location as the public key, but it should be a location that only you can access and that you will NOT lose! If you lose your keys and have disabled username/password logins, you will no longer be able log in!);
  11. Right-click in the text field labeled Public key for pasting into OpenSSH authorized_keys file and choose Select All;
  12. Right-click again in the same text field and choose Copy.

NOTE: PuTTY and OpenSSH use different formats for public SSH keys. If the SSH Key you copied starts with "---- BEGIN SSH2 PUBLIC KEY ...", it is in the wrong format. Be sure to follow the instructions carefully. Your key should start with "ssh-rsa AAAA ...."

Save The Public Key On The Server

Now, you need to paste the copied public key in the file ~/.ssh/authorized_keys on your server.

  1. Log in to your destination server; see How to Log Into Your Droplet with PuTTY (for windows users)
  2. If your SSH folder does not yet exist, create it manually:
  3. mkdir ~/.ssh
    chmod 0700 ~/.ssh
    touch ~/.ssh/authorized_keys
    chmod 0644 ~/.ssh/authorized_keys
  4. Paste the SSH public key into your ~/.ssh/authorized_keys file (see Installing and Using the Vim Text Editor on an Cloud Server):
  5. sudo vim ~/.ssh/authorized_keys
  6. Tap the i key on your keyboard & right-click your mouse to paste.
  7. To save, tap the following keys on your keyboard (in this order): Esc, :, w, q, Enter.

Create a PuTTY Profile to Save Your Server's Settings

In PuTTY, you can create (and save) profiles for connections to your various SSH servers, so you don't have to remember, and continually re-type, redundant information.

  1. Start PuTTY by double-clicking its executable file;
  2. PuTTY's initial window is the Session Category (navigate PuTTY's various categories, along the left-hand side of the window);
  3. In the Host Name field, enter the IP address of your VPS or its fully qualified domain name (FQDN); see How to Set Up a Host Name with DigitalOcean
  4. Enter the port number in the Port field (for added security, consider changing your server's SSH port to a non-standard port. See Step Five of Initial Server Setup with Ubuntu 12.04
  5. Select SSH under Protocol;
  6. Along the left-hand side of the window, select the Data sub-category, under Connection;
  7. Specify the username that you plan on using, when logging in to the SSH server, and whose profile you're saving, in the Auto-login username field;
  8. Expand the SSH sub-category, under Connection;
  9. Highlight the Auth sub-category and click the Browse button, on the right-hand side of the PuTTY window;
  10. Browse your file system and select your previously-created private key;
  11. Return to the Session Category and enter a name for this profile in the Saved Sessions field, e.g. user@123.456.78.9 or user@host.yourdomain.tld;
  12. Click the Save button for the Load, Save or Delete a stored session area.

Now you can go ahead and log in to user@1.2.3.4 and you will not be prompted for a password. However, if you had set a passphrase on your public key, you will be asked to enter the passphrase at that time (and every time you log in, in the future).

Disable Username/Password Logins

Once you have verified that your key-based logins are working, you may elect to disable username/password logins to achieve better security. To do this, you need to edit your SSH server's configuration file. On Debian/ Ubuntu systems, this file is located at /etc/ssh/sshd_config.

sudo vim /etc/ssh/sshd_config

Tap the i key on your keyboard and edit the lines, referenced below:

[...]
PasswordAuthentication no
[...]
UsePAM no
[...]

To save, tap the following keys on your keyboard (in this order): Esc, :, w, q, Enter. Now, reload the SSH server's configuration:

sudo reload ssh

Additional Resources

As always, if you need help with the steps in this HowTo, look to the DigitalOcean Community for assistance by posing your question(s), below.

Article Submitted by: Pablo Carranza

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the authors
Default avatar
Pablo Carranza

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
53 Comments
Leave a comment...

This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

For a fresh install of CentOS 6.4 64-bit, I had to use “vim” wherever “vi” appears to edit files and I used this comment to restart sshd:

sudo service sshd restart

Otherwise, very helpful. Thanks!

I got a server ‘server refused our key’ message in PuTTY…

I got this message due to me creating the keys as “root” for a user. This appends the owner of “root” to the created folder/file. I had to add this command to succeed:

Note: this “user” was created beforehand without password.

mkdir /home/user/.ssh
chmod 0700 /home/user/.ssh
touch /home/user/.ssh/authorized_keys
chmod 0644 /home/user/.ssh/authorized_keys
chown user:user /home/rsadmin/.ssh/ -R
Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
October 18, 2013

@Nicholas: Have you uploaded the public to your droplet?

@Kamal,

You mean by means of sudo nano ~/.ssh/authorized_keys? Yes, I did that.

Strangely, it’s accepting my ‘user’ but not my key. I don’t have to type my username but still have to type my password to logon.

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
October 20, 2013

@Nicholas: Hmm. Can you please pastebin the contents of ~/.ssh/authorized_keys?

question. do i sudo nano ~/.ssh/authorized_keys in the root directory or do i do that in /home/user/?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
October 23, 2013

@Nicholas: /home/user/. Also, what’s the output of <code>wc -l /home/user/.ssh/authorized_keys</code>?

@Nicholas: I was having the same issue as you (“server refused our key” in PuTTY). I followed the steps of this article as a user with root access in CentOS 6. To be able to log in, I had to set the permissions of ~/.ssh to 755 instead of 700. In other words: sudo chmod 755 ~/.ssh sudo chmod 644 ~/.ssh/authorized_keys

@Kamal: Is the above acceptable? Or does it pose a risk, compared to setting the permissions of ~/.ssh to 700?

The CentOS wiki mentions that the following “permissions are required if StrictModes is set to yes in /etc/ssh/sshd_config (the default).” 700 ~/.ssh 600 ~/.ssh/authorized_keys

If I understand correctly… 700 means the owner can read/write/execute 600 means the owner can read/write

I assume the owner is root. But even as root, if I set the above permissions (or the ones mentioned in the guide), I receive “server refused our key”.

755 means owner can read/write/execute, group can read/execute, and public can read/execute. 644 means owner can read/write, group can read, and public can read.

Which is I’m not too comfortable setting permissions to… 755 ~/.ssh 644 ~/.ssh/authorized_keys

Then again, if I understand correctly, the above is still safer than logging in with username/password. Is that right?

Another thing: I followed another DigitalOcean guide by Etel Sverdlov (https://www.digitalocean.com/community/articles/initial-server-setup-with-centos-6) to create a user and change PermitRootLogin to no in order to prevent root log in. Could this be one of the reasons why I cannot enter the server through keys under permissions 700/644 above?

Thanks for your help.

@Kamal,

It works now. Thanks for pointing out my mistake. Had ‘sudo nano ~/.ssh/authorized_keys?’ in root. did that in /home/user and it is working

Hi, does anyone know how can I automate the passphrase entering ? in unix I just accept the passphrase for the first time and it will never ask me again, on windows I accept the first time, but it will ask me again and again

a better solution is not to do pasphrase but I had to (for other computers)

any idea ? any configuration in Putty ?

thanks

Hi, I would like to disable password login. This is what I have done:

[…] PasswordAuthentication no […] UsePAM no […]

To confirm that password has been disabled, I removed private key from Pageant and reconnected to putty. This is what I see in Putty:

login as: random random@123.123.123.12’s password:

I was prompted for the password. Can i safely assume that all passwords will not work since I have disabled passwords?

Fyi, when i created my droplet, i used SSH Key thus no email (containing the password) was sent by Digital Ocean.

Can I again assume that there is no password set for this droplet?

Sorry if i seem to sound like i don’t know what is going on as I am totally new to all this. Thanks in advance!

how do i get this software to sends bulk emails for marketing

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
December 4, 2013

@hopefloatt: <blockquote>I was prompted for the password. Can i safely assume that all passwords will not work since I have disabled passwords? </blockquote> Yes, as long as you restarted SSH, it will reject all passwords.

<blockquote>Fyi, when i created my droplet, i used SSH Key thus no email (containing the password) was sent by Digital Ocean.

Can I again assume that there is no password set for this droplet? </blockquote> It does have a random password set however it wasn’t sent to you. You can always change it by running the <code>passwd</code> command.

Thanks very much Kamal!! :D

<b>“It does have a random password set however it wasn’t sent to you. You can always change it by running the <code>passwd</code> command.”</b>

Is it possible to remove the password altogether?

Kamal Nasser
DigitalOcean Employee
DigitalOcean Employee badge
December 6, 2013

@Pablo: I think you can remove the password (<code>sudo passwd -d user</code>) and then lock the user:

<a href=“http://www.cyberciti.biz/faq/linux-locking-an-account/”>http://www.cyberciti.biz/faq/linux-locking-an-account/</a>

Hey DO, great tutorial as usual, FYI the link to installing vim is broken

I guess it is better to use sudo /etc/init.d/ssh restart to restart SSH

That command in the tut doesn’t work on my setup so I had to use the one I wrote in my first comment line.

Good luck, and Thanks by the way for the nice tut!

This comment has been deleted

    everytime some accesses my website, server asks for username and password, how to fix this ?

    Kamal Nasser
    DigitalOcean Employee
    DigitalOcean Employee badge
    April 9, 2014

    @lalitvohra2000: Can you create <a href=“https://www.digitalocean.com/community/questions”>a new question</a> with your virtualhost config?

    as @camdenl noted, the link to the tutorial “Installing and Using the Vim Text Editor on an Cloud Server” is broken.
    The correct link is: https://www.digitalocean.com/community/articles/installing-and-using-the-vim-text-editor-on-a-cloud-server

    Andrew SB
    DigitalOcean Employee
    DigitalOcean Employee badge
    April 16, 2014

    @ashley: Fixed. Thanks for catching that!

    Hey I got the same problem,

    PUTTY: Using username “userX”. Server refused our key userX@IP.xxx.xxx.xxx’s password:


    Running: wc -l /home/userX/.ssh/authorized_keys Show: —> 7 /home/userX/.ssh/authorized_keys

    This is not a SSH Droplets, it has user and password and I do the initial server configuration, etc.

    Can you help me?

    Andrew SB
    DigitalOcean Employee
    DigitalOcean Employee badge
    May 2, 2014

    @evhernandez23: On the server, running “tail -f /var/log/auth.log” should give you more information about the actual error. Often the case is that the files have the wrong permissions set. To make sure they’re right, run:

    <pre> chmod 700 ~/.ssh chmod 600 ~/.ssh/authorized_keys </pre>

    Excellent work on the tutorial! Thank you very much!

    I have the following in <code>auth.log</code>:

    <code>Jun 21 09:46:55 localhost sshd[1292]: Connection closed by XXX.MY.IP.XXX [preauth]</code>

    good stuff

    Hi, I have followed tutorial and works, when I login (I have followed tutorial as root user) I have:

    Using username “root”. Authenticating with public key “xxxxxx” Passphrase for key “xxxxx”:

    And all works if I’m root user.

    I have added a sudo user, and when I login with that user I have “Server refused our key” and it asks me normal password for sudo user.

    I would to like: Public and Private SSH Keys for root and sudo users; disable root login and Authentications. The problem is that I don’t know how can add public and private SSH keys to sudo users…

    What I wrong?

    Thank you very much in advance

    Hi, I had to change /etc/ssh/sshd_config back to

    [...]
    #PasswordAuthentication no (I commented it)
    [...]
    UsePAM yes
    [...]
    
    

    Because it blocks me from accessing sftp (based off this tutorial). When I typed sh username@remote_hostname_or_IP I get Permission denied (publickey). I get exact same answer when I typed sftp username@remote_hostname_or_IP. I also couldn’t use Filezilla (using this tutorial) to access the server due to PasswordAuthentication yes and UsePAM yes setting.

    So I had to revert PasswordAuthentication and UsePAM back to their original settings to make SFTP and Filezilla work.

    So is it possible to disable username/password logins for better security (hence changing PasswordAuthentication and UsePAM to yes) while allowing sftp access at the same time? Best for both worlds? Thanks in advance!

    This comment has been deleted

      hi i run this tutorial like this…

      1. login with user with root priviliged.
      2. su, and begin root.
      3. follow all the instructions above.

      this is the problem, i setup the username on putty > data with “root”, but when i login, it said Server refused public-key signature despite accepting key! and also ask for password.

      is anything wrong?

      2 hours later (about 7 attempts) I got this to work!

      Thanks for this FOOL Proof Guide

      This comment has been deleted

        This comment has been deleted

          Hi,

          Make as much as easy, a non developer cannot make a successful secured server. We face problem at every step.

          I just setup everything well, but I cannot find option PasswordAuthentication no in SSH config. This option is not available.

          UsePAM no :- Completed

          PasswordAuthentication no :- Cannot find this option.

          Solved

          The line was hidden in blue colour with # I removed # and changed to no. Try to access root with password - connection refused.

          Hi,

          What I will do if I loose my private key ?

          Hi, i got a server ‘server refused our key’ message in PuTTY, and it’s asking for a password from me. What should i do?

          Kamal Nasser
          DigitalOcean Employee
          DigitalOcean Employee badge
          July 31, 2015

          Hi @mmmdribling, have you added the public key to authorized_keys on the server? Make sure that it’s in the following format:

          ssh-rsa AAAAB..... optional-comment
          

          @kamaln7 Yes. It’s in the ~/.ssh/ directory.

          Hello, Can any 1 teach me how to use Putty with Command . I have etho root and PM ready. Pls Contact me at ( paul.enterprises@yahoo.com ) I will be expecting you.

          OK guys, I am not doing so well on the “Set up a cloud server in 55 seconds”. I don’t have a server here, I’m on a Windows notebook, I don’t know the difference between Composer, Git, Sudo, and Artisan, don’t know anything about Linux command line, but you got to start somewhere, right? Once I have LAMP running, I plan to use WinSCP to manage it. But I’m struggling to get there.

          I really don’t want to use Putty, it looks like it is from the '70’s. I installed it once and deleted it, even Edlin is better. C’mon guys, isn’t there a better way that you could explain above that doesn’t need a server (I can’t run any of the server command lines in this tutorial), and that doesn’t use a program from the '70’s. Are you saying this is the only way to do this? Did I miss a tutorial? Thanks guys.

          "Step One—Create the RSA Key Pair The first step is to create the key pair on the client machine (there is a good chance that this will just be your computer):

          ssh-keygen -t rsa
          

          Wrong. I know you Linux guys love your Putty, and I’m probably annoying most readers, but c’mon now, aren’t there any better tools yet? Ok, vent is now over, thanks again guys.

          NOTE: PuTTY and OpenSSH use different formats for public SSH keys. If the SSH Key you copied starts with “---- BEGIN SSH2 PUBLIC KEY …”, it is in the wrong format. Be sure to follow the instructions carefully. Your key should start with “ssh-rsa AAAA …”

          I would update this part. My issue was that, I have been saved the public key, and copy paste that content. I have seen that, it is in a wrong format, but I never would thought that inside the puttygen in the textbox there is a different format. Took me 30 mins, to realize… In this case you can also use the import key in puttygen, so you doesnt have to regenerate everything.:) But thx for the tut!

          Mine works only with 400 rights for ~/.ssh/authorized_keys

          OpenSSH_6.6p1, OpenSSL 1.0.1e-fips on CentOS

          If i want additional users to have SSH key how do i do it?

          is it possible to add the key generated by PUTTY to my ubuntu computer? or i need to generate a new one using the ubuntu machine and add it to the server?

          Still having the alert “Server refused our key” even when i carefully followed all steps above. I’ve uploaded my key to Droplet and yet still having the same error. Can someone kindly guide me?

          Great article. Each step nicely written.

          Unfortunately, I am stuck after step “Save The Public Key On The Server”.

          1. I did “Save The Public Key On The Server” step at /root/.ssh which I understand is ~/.ssh because when I tried mkdir ~/.ssh it says that .ssh folder is already available at /root/.ssh

          2. I reset all the permissions at /root/.ssh as said

          3. I was initially login to root using Putty with ip/password/port saved. I tried login that way after “Save The Public Key On The Server” step. I am surprised that it is not asking for any SSH private key!

          Please advise.

          I need to grant access to a technical support but the only way is to give them the private key to connect through FTP on the server

          I’ve read countless of post, SSH here and there, but how I can grant access to a adduser that I’ve created, .ssh/ authorized.keys that I’ve copied in /home/user to grant the access through my server on FTP without asking for private key

          doubt, also…

          do I need to add another SSH on my droplet, create also another SSH for a user, or I can use just one key (that’s what I’m doing, copying the .ssh/ and pasting to users.

          This tutorial’s method of generating keys with PuTTy always generates a PuTTy-format key, which doesn’t work on DigitalOcean.

          These instructions seem to be WAY out of date, and no longer work. I’ve tried 2 different keys with Puttygen, and was unable to add them. Error msg said that the key type wasn’t supported - then listed the key type I’d just created as one of the valid ones.

          droplet yesterday is working well but today give me this error No support authentication methods available (server sent :publickey) when try to access putty or to connect on it by cyperduck or mysql

          mkdir ~/.ssh chmod 0700 ~/.ssh touch ~/.ssh/authorized_keys chmod 0644 ~/.ssh/authorized_keys This should be a 4-line command, but the new version of the website is all displayed on one line, please check.

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Become a contributor for community

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          DigitalOcean Documentation

          Full documentation for every DigitalOcean product.

          Resources for startups and SMBs

          The Wave has everything you need to know about building a business, from raising funding to marketing your product.

          Get our newsletter

          Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

          New accounts only. By submitting your email you agree to our Privacy Policy

          The developer cloud

          Scale up as you grow — whether you're running one virtual machine or ten thousand.

          Get started for free

          Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

          *This promotional offer applies to new accounts only.