SSH Authentication for Git: Setup and Configuration

SSH keys allow secure communication with remote repositories without using passwords.

SSH Authentication for Git: Setup and Configuration

SSH (Secure Shell) authentication is the most secure and convenient way to communicate with remote Git repositories. Instead of typing your username and password every time you push or pull, SSH keys provide passwordless authentication using cryptographic key pairs. Once configured, SSH allows you to interact with remote repositories seamlessly without repeatedly entering credentials, while providing stronger security than passwords.

SSH uses a pair of keys: a private key that stays on your local machine and should never be shared, and a public key that you upload to your Git hosting service like GitHub, GitLab, or Bitbucket. When you connect, the server uses your public key to verify that you possess the corresponding private key, without the private key ever leaving your machine. This makes SSH resistant to password theft and brute-force attacks. To understand SSH properly, it is helpful to be familiar with working with remote repositories, basic Git workflow, and encryption basics.

SSH authentication in simple terms:
Your Computer (Private Key)  →  GitHub (Public Key)
        │                              │
        │  "I want to push my code"    │
        │─────────────────────────────→│
        │                              │
        │  Server sends encrypted challenge
        │←─────────────────────────────│
        │                              │
        │  You decrypt with private key
        │─────────────────────────────→│
        │                              │
        │  Server verifies using public key
        │←─────────────────────────────│
        │                              │
        │  Access granted, push proceeds
        │─────────────────────────────→│

What Is SSH Authentication

SSH authentication is a method of verifying your identity to a remote server using cryptographic keys instead of a password. It is based on public-key cryptography, where a mathematically linked pair of keys is generated. The public key can be shared openly, while the private key must be kept secret and secure on your local machine.

When you connect to a remote Git repository via SSH, the server sends a challenge encrypted with your public key. Your SSH client decrypts the challenge using your private key and sends it back. The server verifies that the response matches the expected result, proving that you possess the private key without ever transmitting it over the network. This process is secure even over untrusted networks because the private key never leaves your machine.

  • Private Key: Stored on your local machine. Never share it with anyone. Protect it with a passphrase.
  • Public Key: Uploaded to your Git hosting service. Can be shared freely.
  • SSH Agent: A program that holds your decrypted private keys in memory so you do not have to enter your passphrase repeatedly.
  • SSH URL Format: git@github.com:username/repository.git instead of https://github.com/username/repository.git

Why SSH Authentication Matters

SSH authentication offers significant advantages over HTTPS password authentication for Git operations, especially for developers who interact with remote repositories frequently.

  • No Password Entry: Once configured, you never need to type your username and password again for Git operations.
  • Stronger Security: SSH keys are cryptographically secure and resistant to brute-force attacks and password reuse vulnerabilities.
  • No Token Management: Unlike HTTPS, which often requires personal access tokens when two-factor authentication is enabled, SSH works seamlessly with 2FA.
  • Multiple Keys: You can use different SSH keys for different services or different levels of access.
  • Revocable: If a key is compromised, you can simply remove the public key from your Git hosting service without changing any passwords.
  • Automation Friendly: SSH keys work perfectly in CI/CD pipelines and automated scripts without storing passwords in plain text.

Step-by-Step SSH Setup

Step 1: Check for Existing SSH Keys

Before generating a new SSH key, check if you already have one on your machine.

# List existing SSH keys
ls -la ~/.ssh/

# Look for files named id_rsa (private) and id_rsa.pub (public)
# Other common names: id_ed25519, id_ecdsa

Step 2: Generate a New SSH Key

If you do not have an existing SSH key, generate a new one. ED25519 is the recommended key type for its security and performance.

Generate ED25519 key (recommended):
ssh-keygen -t ed25519 -C "your-email@example.com"

# Follow the prompts:
# - Press Enter to save to default location (~/.ssh/id_ed25519)
# - Enter a passphrase (recommended) or leave empty
Generate RSA key (compatible with older systems):
ssh-keygen -t rsa -b 4096 -C "your-email@example.com"

Step 3: Start SSH Agent and Add Your Key

The SSH agent holds your decrypted private keys in memory, so you do not have to enter your passphrase for every Git operation.

# Start SSH agent in the background
eval "$(ssh-agent -s)"

# Add your private key to the agent
ssh-add ~/.ssh/id_ed25519

# On macOS, you can also add to keychain
ssh-add --apple-use-keychain ~/.ssh/id_ed25519

Step 4: Copy Your Public Key

The public key is what you will add to your Git hosting service. It is safe to share and is stored in a file with the .pub extension.

# Copy public key to clipboard (Linux)
cat ~/.ssh/id_ed25519.pub

# Copy public key to clipboard (macOS)
pbcopy < ~/.ssh/id_ed25519.pub

# Copy public key to clipboard (Windows - Git Bash)
cat ~/.ssh/id_ed25519.pub | clip

Step 5: Add Public Key to Your Git Hosting Service

GitHub

  1. Go to Settings → SSH and GPG keys
  2. Click "New SSH Key"
  3. Enter a descriptive title (e.g., "My Work Laptop")
  4. Paste your public key and click "Add SSH Key"

GitLab

  1. Go to Preferences → SSH Keys
  2. Paste your public key
  3. Set an expiration date (optional)
  4. Click "Add Key"

Bitbucket

  1. Go to Personal settings → SSH keys
  2. Click "Add key"
  3. Paste your public key and add a label
  4. Click "Add key"

Step 6: Test Your SSH Connection

Before using Git, test that your SSH key is properly configured and authenticated.

# Test connection to GitHub
ssh -T git@github.com

# Expected output:
# Hi username! You've successfully authenticated, but GitHub does not provide shell access.

# Test connection to GitLab
ssh -T git@gitlab.com

# Test connection to Bitbucket
ssh -T git@bitbucket.org

Configuring Git to Use SSH

Once your SSH key is set up, you need to use SSH URLs for your remote repositories instead of HTTPS URLs.

# Check current remote URL
git remote -v

# Change remote URL from HTTPS to SSH
git remote set-url origin git@github.com:username/repository.git

# Example HTTPS to SSH conversion:
# HTTPS: https://github.com/username/repository.git
# SSH:   git@github.com:username/repository.git

Managing Multiple SSH Keys

If you use multiple Git hosting services or have different keys for work and personal projects, you can configure SSH to use different keys for different hosts using the ~/.ssh/config file.

SSH config file example (~/.ssh/config):
# Personal GitHub account
Host github.com
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_personal

# Work GitHub account
Host github-work
    HostName github.com
    User git
    IdentityFile ~/.ssh/id_ed25519_work

# GitLab account
Host gitlab.com
    HostName gitlab.com
    User git
    IdentityFile ~/.ssh/id_ed25519_gitlab

# Use work key for work repository
# Clone with: git clone git@github-work:company/repo.git

SSH Key Security Best Practices

  • Use a Passphrase: Always protect your private key with a strong passphrase. If someone steals your key file, they still need the passphrase to use it.
  • Use SSH Agent: Use ssh-add to load your key into the SSH agent so you only enter your passphrase once per session.
  • Use ED25519 Keys: ED25519 provides better security and performance than RSA. Use RSA 4096 only if you need compatibility with older systems.
  • Rotate Keys Periodically: Generate new keys and remove old ones from your Git hosting service periodically, especially after a device is lost or sold.
  • Different Keys for Different Devices: Use separate keys for each device so you can revoke access for a lost laptop without affecting other devices.
  • Never Share Private Keys: Never send your private key to anyone, including IT support. No legitimate service will ever ask for your private key.

Common SSH Authentication Mistakes to Avoid

  • Using HTTPS URL Instead of SSH: Your remote URL must start with git@ for SSH authentication. Check with git remote -v.
  • Wrong Key Permissions: SSH requires strict permissions. Private keys must be readable only by you (600).
  • Not Starting SSH Agent: Without the SSH agent running, you will be prompted for your passphrase every time.
  • Adding Wrong Key to Service: You must add the public key (.pub file), not the private key.
  • Incorrect SSH URL Format: The format is git@host:username/repo.git, not git@host/username/repo.git (note the colon).
  • Firewall Blocking Port 22: Some corporate networks block port 22. You may need to use HTTPS or configure SSH to use port 443.
Fix common SSH permission issues:
# Fix private key permissions (must be 600)
chmod 600 ~/.ssh/id_ed25519

# Fix .ssh directory permissions (must be 700)
chmod 700 ~/.ssh

# Fix config file permissions (must be 644)
chmod 644 ~/.ssh/config

Troubleshooting SSH Connection Issues

Error Message Likely Cause Solution
Permission denied (publickey) The server does not recognize your public key Verify the public key is added to your Git hosting account, and you are using the correct private key
Could not open a connection to your authentication agent SSH agent is not running Start SSH agent with eval "$(ssh-agent -s)"
Bad permissions on ~/.ssh/id_ed25519 Private key permissions are too permissive Run chmod 600 ~/.ssh/id_ed25519
ssh: connect to host github.com port 22: Connection refused Port 22 is blocked by firewall Use HTTPS instead, or configure SSH to use port 443
Verbose SSH debugging:
# Run SSH with verbose output to see exactly what is happening
ssh -Tv git@github.com

# For even more detail
ssh -Tvvv git@github.com

SSH vs HTTPS for Git

Feature SSH HTTPS
Authentication SSH key pair (public + private) Username + password or personal access token
Setup Complexity Initial setup requires key generation and configuration No setup required (but tokens needed for 2FA)
Daily Usage No credentials after initial SSH agent setup Credentials or token required each push (or cached)
Security Very secure, private key never leaves your machine Secure, but passwords can be stolen or reused
Two-Factor Authentication Works seamlessly Requires personal access token instead of password
Firewall Friendliness Uses port 22 (sometimes blocked) Uses port 443 (always open)
Best For Frequent Git users, developers, automation Occasional users, restricted networks

Frequently Asked Questions

  1. What is the difference between SSH and HTTPS for Git?
    SSH uses cryptographic key pairs for authentication and requires initial setup but offers passwordless operation afterward. HTTPS uses username and password or personal access tokens, works on any network (including those blocking port 22), but requires entering credentials more frequently.
  2. Can I use both SSH and HTTPS for the same repository?
    Yes. You can have multiple remotes or change the remote URL at any time. However, you cannot push using one protocol and pull using another without updating the remote URL.
  3. What is a passphrase and do I need one?
    A passphrase encrypts your private key on disk. If someone steals your key file, they still need the passphrase to use it. You should always use a passphrase, then use ssh-add to load the key into SSH agent so you only enter it once per session.
  4. How do I change my SSH key passphrase?
    Run ssh-keygen -p -f ~/.ssh/id_ed25519. You will be prompted for your old passphrase and then the new one.
  5. What is the difference between ED25519 and RSA keys?
    ED25519 is a modern elliptic curve cryptography with better security and performance. RSA 4096 is older but more widely supported. ED25519 is recommended for most users. Use RSA only if you need compatibility with older systems.
  6. What should I learn next after understanding SSH authentication?
    After mastering SSH for Git, explore working with remote repositories, Git workflows, Git best practices, and encryption basics for comprehensive security knowledge.

Conclusion

SSH authentication is the gold standard for secure, convenient access to remote Git repositories. By using cryptographic key pairs instead of passwords, SSH provides stronger security while eliminating the friction of repeatedly entering credentials. Once configured, you can push, pull, and clone repositories seamlessly without interruption.

The setup process is straightforward: generate a key pair, add your public key to your Git hosting service, and configure your local repository to use SSH URLs. Using an SSH agent with a passphrase-protected key gives you the best of both worlds: strong security and passwordless convenience.

While SSH requires initial configuration and may be blocked on some corporate networks, the benefits for frequent Git users far outweigh these minor drawbacks. For teams and individual developers alike, SSH authentication is the recommended way to interact with remote Git repositories.

To deepen your understanding, explore related topics like working with remote repositories, Git workflows, Git best practices, and encryption basics. Together, these skills form a complete foundation for secure and efficient version control.