πŸ” How to Use SSH Keys

Using SSH keys is a secure way to authenticate with remote servers and services (like GitHub, remote servers via SSH, etc.) without needing to type your password each time. Here's a complete guide on how to generate, configure, and use SSH keys across typical use cases.

πŸ” What Are SSH Keys?

SSH keys are a pair of cryptographic keys used for secure authentication:

πŸ› οΈ 1. Generate SSH Key Pair

On Linux / macOS / WSL:

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

You’ll see:

Generating public/private rsa key pair.
Enter file in which to save the key (/home/youruser/.ssh/id_rsa):

Press Enter to accept the default path.

Enter passphrase (empty for no passphrase):

You can optionally set a passphrase (adds extra security). Your keys are now saved in ~/.ssh/id_rsa and ~/.ssh/id_rsa.pub.

πŸ“¬ 2. Copy Public Key to Remote Server

Option 1: ssh-copy-id (easiest)

ssh-copy-id user@remote_host

This appends your public key to ~/.ssh/authorized_keys on the server.

Option 2: Manual method

cat ~/.ssh/id_rsa.pub

Copy the output, then on the remote server:

mkdir -p ~/.ssh
echo "your_copied_public_key" >> ~/.ssh/authorized_keys
chmod 600 ~/.ssh/authorized_keys
chmod 700 ~/.ssh

πŸ§ͺ 3. Test the SSH Connection

ssh user@remote_host

If everything's set up, it will log you in without a password.

πŸ™ 4. Use SSH Key with GitHub/GitLab

Step 1: Copy your public key

cat ~/.ssh/id_rsa.pub

Step 2: Add it to GitHub

Step 3: Test

ssh -T git@github.com

You should see:

Hi username! You've successfully authenticated.

🧠 5. Use Custom Key File or Multiple Keys

Specify key file manually:

ssh -i ~/.ssh/your_custom_key user@remote_host

Or configure per-host in ~/.ssh/config:

Host myserver
    HostName 192.168.0.10
    User myuser
    IdentityFile ~/.ssh/my_custom_key

Then just run:

ssh myserver

πŸ” 6. Forward SSH Key (for nested connections)

ssh -A user@jump_host

This allows your SSH agent and keys to be used on the remote host, useful for SSHing from a remote server into another server (hop).

πŸ” 7. Using an SSH Agent (Optional but Useful)

To avoid entering your passphrase repeatedly:

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_rsa

You can also automate this on login (e.g., via .bashrc, .zshrc, or macOS Keychain).

πŸ” 8. Verify Keys on Server

cat ~/.ssh/authorized_keys

You should see your public key listed there. If login fails, check:

πŸ“š Summary Cheat Sheet

Action Command/Path
Generate Key ssh-keygen -t rsa -b 4096 -C "email"
View Public Key cat ~/.ssh/id_rsa.pub
Copy to Remote ssh-copy-id user@host
Connect via SSH ssh user@host
GitHub Key Test ssh -T git@github.com
Use Specific Key ssh -i path/to/key user@host
SSH Config File ~/.ssh/config
Add Key to Agent ssh-add ~/.ssh/id_rsa

If you want a quick script or config tailored to your use case (e.g., auto-loading keys, working with multiple remotes, or integrating with Git), let me know!