Generate a key pair for SSH authentication

Identity key-based authentication lets you log in to the server without supplying a password.

To set up key-based SSH login authentication, you must generate the keys the two computers will use to establish and validate the identity of each other.

To authorize all users of the computer to have SSH access, you must generate keys for each user account. Run the following commands in Terminal for each user that needs to open key-based SSH sessions.

Important:  Key-based authentication has risks. If the private key you generate becomes compromised, unauthorized users can access your computers. You must determine whether the advantages of key-based authentication are worth the risks.

  1. Open Terminal (located in /Applications/Utilities/).

  2. Verify that an .ssh folder exists in your home folder by entering:

    ls -ld ~/.ssh

    If .ssh is listed in the output, continue to the next step. If .ssh isn’t listed in the output, enter the following and continue to the next step:

    mkdir -m 700 ~/.ssh
  3. Change directories in the shell to the hidden .ssh directory by entering:

    cd ~/.ssh
  4. Generate the public and private keys by entering:

    ssh-keygen -b 2048 -t rsa -f id_rsa -P ''

    The -b flag sets the length of the keys to 2048-bits, -t indicates to use the RSA hashing algorithm, -f sets the file name as id_rsa, and -P followed by two single-quotation marks sets the private key password to be null. The null private key password allows for automated SSH connections.

    Keys are equivalent to passwords, so keep them private and protected.

    This creates two files. Your identification or private key is saved in one file (id_rsa in our example), and your public key is saved in the other (id_rsa.pub in our example). The key fingerprint, which is derived cryptographically from the public key value, also appears. This secures the public key.

  5. Set the permissions on the private key so the file can only be changed by the owner by entering:

    chmod go-rwx ~/.ssh/id_rsa
  6. Copy the public key to the specified user’s home folder on the remote computer by entering:

    scp id_rsa.pub username@remotemachine:~
  7. Using ssh, copy the public key into the authorized_keys file on the remote computer by entering:

    ssh username@remotemachine "cat /Users/username/id_rsa.pub >> ~/.ssh/authorized_keys"
  8. Delete the id_rsa.pub file from the user’s home folder on the remote computer.

    ssh username@remotemachine "rm /Users/username/id_rsa.pub"

    The next time you log in to the remote computer from the local computer, you won’t need to enter a password. If you need to establish two-way communication between servers, repeat this process on the second computer. This process must be repeated for each user who needs to be able to open a key-based SSH session. This includes the root user, whose home folder on OS X Server is at /var/root/.