If you are working with Git and GitHub, it is a good practice to use SSH keys for authentication instead of typing your username and password every time. In this guide, we’ll generate an SSH key, configure Git, and push code to GitHub.
Run the following command to create a new SSH key (RSA, 4096-bit):
ssh-keygen -t rsa -b 4096 -C "your@email.com"
When prompted, enter the file location where you want to save your key (you can customize it):
Enter file in which to save the key (/c/Users/wts/.ssh/id_rsa): /c/Users/wts/.ssh/id_rsa
Navigate to your .ssh folder and check your keys:
ls -al ~/.ssh
Print the public key to your terminal (then copy it):
cat ~/.ssh/id_rsa.pub
Set your Git username and email (use the email on your GitHub account):
git config user.name "your-username"
git config user.email "your@gmail.com"
Make Git always use the newly generated key for GitHub:
git config core.sshCommand "ssh -i ~/.ssh/id_rsa"
Check or edit the Git configuration if needed:
git config -e
Add the remote repository:
git remote add origin git@github.com:your-username/your-repo.git
If you need to change the URL later:
git remote set-url origin git@github.com:your-username/your-repo.git
ssh -T git@github.com
You should see a message like:
Hi your-username! You've successfully authenticated, but GitHub does not provide shell access.
Initialize your repository:
git init
Stage and commit your files:
git add .
git commit -m "First commit"
Set the remote (if not already set) and push to GitHub:
git remote add origin git@github.com:your_username/test.git
git push --set-upstream origin main
Done! You’ve successfully set up SSH with GitHub and pushed your first commit securely.