Generating a new SSH key and adding it to the ssh-agent
After you’ve checked for existing SSH keys, you can generate a new SSH key to use for authentication, then add it to the ssh-agent.
About SSH key passphrases
You can access and write data in repositories on GitHub.com using SSH (Secure Shell Protocol). When you connect via SSH, you authenticate using a private key file on your local machine. For more information, see «About SSH.»
When you generate an SSH key, you can add a passphrase to further secure the key. Whenever you use the key, you must enter the passphrase. If your key has a passphrase and you don’t want to enter the passphrase every time you use the key, you can add your key to the SSH agent. The SSH agent manages your SSH keys and remembers your passphrase.
If you don’t already have an SSH key, you must generate a new SSH key to use for authentication. If you’re unsure whether you already have an SSH key, you can check for existing keys. For more information, see «Checking for existing SSH keys.»
If you want to use a hardware security key to authenticate to GitHub, you must generate a new SSH key for your hardware security key. You must connect your hardware security key to your computer when you authenticate with the key pair. For more information, see the OpenSSH 8.2 release notes.
Generating a new SSH key
You can generate a new SSH key on your local machine. After you generate the key, you can add the key to your account on GitHub.com to enable authentication for Git operations over SSH.
Note: GitHub improved security by dropping older, insecure key types on March 15, 2022.
As of that date, DSA keys ( ssh-dss ) are no longer supported. You cannot add new DSA keys to your personal account on GitHub.com.
RSA keys ( ssh-rsa ) with a valid_after before November 2, 2021 may continue to use any signature algorithm. RSA keys generated after that date must use a SHA-2 signature algorithm. Some older clients may need to be upgraded in order to use SHA-2 signatures.
Open Terminal Terminal Git Bash .
Paste the text below, substituting in your GitHub email address.
Note: If you are using a legacy system that doesn’t support the Ed25519 algorithm, use:
This creates a new SSH key, using the provided email as a label.
When you’re prompted to «Enter a file in which to save the key», you can press Enter to accept the default file location. Please note that if you created SSH keys previously, ssh-keygen may ask you to rewrite another key, in which case we recommend creating a custom-named SSH key. To do so, type the default file location and replace id_ssh_keyname with your custom key name.
At the prompt, type a secure passphrase. For more information, see «Working with SSH key passphrases.»
Adding your SSH key to the ssh-agent
Before adding a new SSH key to the ssh-agent to manage your keys, you should have checked for existing SSH keys and generated a new SSH key. When adding your SSH key to the agent, use the default macOS ssh-add command, and not an application installed by macports, homebrew, or some other external source.
Start the ssh-agent in the background.
Depending on your environment, you may need to use a different command. For example, you may need to use root access by running sudo -s -H before starting the ssh-agent, or you may need to use exec ssh-agent bash or exec ssh-agent zsh to run the ssh-agent.
If you’re using macOS Sierra 10.12.2 or later, you will need to modify your
/.ssh/config file to automatically load keys into the ssh-agent and store passphrases in your keychain.
First, check to see if your
/.ssh/config file exists in the default location.
If the file doesn’t exist, create the file.
/.ssh/config file, then modify the file to contain the following lines. If your SSH key file has a different name or path than the example code, modify the filename or path to match your current setup.
Notes:
If you chose not to add a passphrase to your key, you should omit the UseKeychain line.
If you see a Bad configuration option: usekeychain error, add an additional line to the configuration’s’ Host *.github.com section.
Add your SSH private key to the ssh-agent and store your passphrase in the keychain. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Note: The —apple-use-keychain option stores the passphrase in your keychain for you when you add an SSH key to the ssh-agent. If you chose not to add a passphrase to your key, run the command without the —apple-use-keychain option.
The —apple-use-keychain option is in Apple’s standard version of ssh-add . In MacOS versions prior to Monterey (12.0), the —apple-use-keychain and —apple-load-keychain flags used the syntax -K and -A , respectively.
If you don’t have Apple’s standard version of ssh-add installed, you may receive an error. For more information, see «Error: ssh-add: illegal option — K.»
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
If you have GitHub Desktop installed, you can use it to clone repositories and not deal with SSH keys.
Ensure the ssh-agent is running. You can use the «Auto-launching the ssh-agent» instructions in «Working with SSH key passphrases», or start it manually:
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Start the ssh-agent in the background.
Depending on your environment, you may need to use a different command. For example, you may need to use root access by running sudo -s -H before starting the ssh-agent, or you may need to use exec ssh-agent bash or exec ssh-agent zsh to run the ssh-agent.
Add your SSH private key to the ssh-agent. If you created your key with a different name, or if you are adding an existing key that has a different name, replace id_ed25519 in the command with the name of your private key file.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Generating a new SSH key for a hardware security key
If you are using macOS or Linux, you may need to update your SSH client or install a new SSH client prior to generating a new SSH key. For more information, see «Error: Unknown key type.»
Insert your hardware security key into your computer.
Open Terminal Terminal Git Bash .
Paste the text below, substituting in the email address for your account on GitHub.
Note: If the command fails and you receive the error invalid format or feature not supported, you may be using a hardware security key that does not support the Ed25519 algorithm. Enter the following command instead.
When you are prompted, touch the button on your hardware security key.
When you are prompted to «Enter a file in which to save the key,» press Enter to accept the default file location.
When you are prompted to type a passphrase, press Enter.
Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»
Help us make these docs great!
All GitHub docs are open source. See something that's wrong or unclear? Submit a pull request.
Добавление нового ключа SSH в учетную запись GitHub
Чтобы настроить учетную запись в GitHub.com для использования нового (или существующего) ключа SSH, необходимо также добавить ключ в учетную запись.
Сведения о добавлении ключей SSH в учетную запись
Вы можете получать доступ к данным в репозиториях и записывать их в GitHub.com с помощью SSH (протокол Secure Shell). При подключении через SSH проверка подлинности выполняется с помощью файла закрытого ключа на локальном компьютере. Дополнительные сведения см. в разделе Сведения о протоколе SSH.
Вы также можете использовать SSH для подписывания фиксаций и тегов. Дополнительные сведения о подписи фиксации см. в разделе Сведения о проверке подписи фиксации.
После создания пары ключей SSH необходимо добавить открытый ключ в GitHub.com, чтобы включить доступ по протоколу SSH для вашей учетной записи.
Перед добавлением нового ключа SSH в учетную запись в GitHub.com, выполните следующие действия.
- Проверьте существующие ключи SSH. Дополнительные сведения см. в разделе Проверка наличия существующих ключей SSH.
- Создайте новый ключ SSH и добавьте его в агент SSH вашего компьютера. Дополнительные сведения см. в разделе Создание нового ключа SSH и его добавление в ssh-agent.
Добавление нового ключа SSH в вашу учетную запись
После добавления нового ключа проверки подлинности SSH в учетную запись в GitHub.com можно перенастроить любые локальные репозитории для использования SSH. Дополнительные сведения см. в разделе Управление удаленными репозиториями.
Примечание. GitHub улучшили безопасность за счет удаления старых небезопасных типов ключей 15 марта 2022 г.
По состоянию на эту дату ключи DSA ( ssh-dss ) больше не поддерживаются. Вы не можете добавить новые ключи DSA в личную учетную запись в GitHub.com.
Ключи RSA ( ssh-rsa ) с valid_after до 2 ноября 2021 г. могут продолжать использовать любой алгоритм подписи. Ключи RSA, созданные после этой даты, должны использовать алгоритм подписи SHA-2. Для использования сигнатур SHA-2 может потребоваться обновить некоторые старые клиенты.
Скопируйте открытый ключ SSH в буфер обмена.
Если файл открытого ключа SSH имеет другое имя или путь, отличный от примера кода, измените имя файла или путь в соответствии с текущей настройкой. При копировании ключа не добавляйте символы перевода строки и пробелы.
Совет. Если pbcopy не работает, можно найти скрытую папку .ssh , открыть файл в любом текстовом редакторе и скопировать ключ в буфер обмена.
Совет: С помощью подсистема Windows для Linux (WSL) можно использовать clip.exe . clip В противном случае вы можете найти скрытую .ssh папку, открыть файл в любом текстовом редакторе и скопировать его в буфер обмена.
Совет. Кроме того, можно найти скрытую папку .ssh , открыть файл в любом текстовом редакторе и скопировать ключ в буфер обмена.
В разделе «Безопасность» на боковой панели щелкните
Ключи SSH и GPG.
Щелкните Создать ключ SSH или Добавить ключ SSH.

В поле «Название» добавьте описательную метку для нового ключа. Например, если вы используете личный ноутбук, можно назвать этот ключ «Личный ноутбук».
Выберите тип ключа: ключ проверки подлинности или ключ подписывания. Дополнительные сведения о подписи фиксации см. в разделе Сведения о проверке подписи фиксации.
Вставьте открытый ключ в поле «Ключ».

Нажмите кнопку Добавить ключ SSH.

При появлении запроса подтвердите доступ к GitHub. Дополнительные сведения см. в разделе Режим sudo.
Дополнительные сведения о GitHub CLI см. в разделе Сведения о GitHub CLI.
Прежде чем использовать GitHub CLI для добавления ключа SSH в учетную запись, необходимо пройти проверку подлинности в GitHub CLI. Дополнительные сведения см. в разделе gh auth login в документации по GitHub CLI.
В настоящее время для добавления ключей проверки подлинности SSH можно использовать только GitHub CLI, добавлять ключи подписывания SSH нельзя.
Чтобы добавить ключ проверки подлинности SSH в учетную запись GitHub, используйте подкоманду ssh-key add , указав открытый ключ.
Чтобы указать заголовок для нового ключа, используйте флаг -t или —title .
Если вы создали ключ SSH, следуя инструкциям в разделе Создание нового ключа SSH и его добавление в ssh-agent, вы можете добавить ключ в учетную запись с помощью этой команды.
Quick Step-By-Step Guide to Generating an SSH Key in GitHub
Easy, Straight-Forward, and Non-Technical Explanation
So this tutorial is for both of us. I have had to set up SSH keys maybe two or three times, and every time it was always a nightmare. I never enjoyed it. Most tutorials I found were complicated and hard to follow.
In this article, I am simplifying the process. I’m giving an easy-to-follow, non-technical, step-by-step guide to generating SSH keys. It is going to be in plain English so even an elementary student can follow — and there are pictures. Who doesn’t love pictures?
Let’s get started.
Windows Terminal
To get started, we want to open our Windows Terminal. For this tutorial, I am using the Ubuntu Terminal.
You want to make sure that you’re currently in the Desktop folder. As shown in the screenshot above, I am currently in the Desktop folder.
If you are not in the desktop folder, let’s fix that.
- use cd folder-name-here to go into a folder. Replace folder-name-here with the folder you want to enter.
- use cd
Use these commands to get to the Desktop folder.
Open the SSH Folder
So my professor taught me to store SSH keys in a .ssh folder that way they are all contained in the same folder. Let me show you how to do that.
To create this folder we will do:
mkdir is a command to create a directory (aka a folder) in the current folder. Since we’re currently in the Desktop folder, this command will create a folder called .ssh in the Desktop.
And in the future, if you want to check if this folder already exists, we will do:
Above is the result of ls -larths and you can see our .ssh folder at the very bottom. I highlighted it in yellow.
After you have created this folder, we want to enter it. Enter the folder with the following command:
Create SSH Keys
We’re inside the SSH folder. If you’re like me, then we already have SSH keys inside this folder. We have the private and public RSA keys.
You can use ls to check if keys already exist.
In my case, they do exist. There is id_rsa which is our private key. Don’t share it with anyone. And there is id_rsa.pub which is our public key. Feel free to share it with your neighbors.
If you don’t have keys, let’s create them. Inside the .ssh folder, run the following command:
This command will generate RSA keys with 4096 bits. This offers high-level encryption. You can customize it differently if you want.
To view customizations you can make, run man ssh-keygen . It will show you all the flags you can use. However, if you’re a beginner, the command above should work fine for now. It will get the job done.
Run the command. It will begin generating your public and private RSA key pair. It will ask for a file, password, and password again. You can skip all three by pressing enter.
Then, you’re done. The RSA keys are generated. As mentioned earlier, you can use ls to check if keys already exist.
You should see something like this.
Once, we have the public key which is id_rsa.pub , we want to view it. We want to see the SSH key.
Open the file id_rsa.pub using the following command
You should see something like this. Copy the entire chunk — and I mean the entire chunk. And then we’re going to paste it into GitHub.
Authenticating with GitHub
Prior to August 13, 2021, you were allowed to authenticate by typing a username and password every time you pushed or pulled from GitHub. For example, when pushing changes made in a local repo to GitHub, the session would look something like this:
Using your GitHub password is no longer allowed after August 13, 2021. Instead, you need to adopt one of several authentication options. Two of these options are covered here: Personal Access Token (PAT) or SSH-based authentication. Both techniques require some degree of configuration on both your GitHub account and your local machine, but the PAT will be the easiest to set up for your students.
Note that your choice of authentication will be dictated by the way you connect to your GitHub repo. If you use PAT, you will connect to your repo over HTTPS –this is the connection used in this workshop. If you use an SSH key, you will connect to your GitHub repo over SSH .
For example, if jdcolby clones repo1 from her GitHub account using HTTPS , she would type:
If jdcolby clones that same repo1 repository from her GitHub account using SSH , she would type:
Instructions on setting up authentication using both techniques follow.
Personal access token (PAT) based authentication
First, you need to follow these steps on GitHub:
Click on your avatar (upper right-hand corner) and select Settings.
On the left sidebar, click on Developer settings (this should be near the bottom of the left sidebar.
In the left sidebar, click Personal access tokens.
Click Generate new token (button near the upper left-hand side).
In the Note field, assign a name to this token such as the local computer you are creating this token for.
In the next field, you can set an expiration date for this token, or make it permanent. In this example, we’ll set it for 90 days.
From the scopes menu, select repo. This will allow you to read/write to your repo.
Click Generate token at the bottom of the page.
Copy and temporarily save the token before closing the window.
When copying the token id, be careful not to add any empty spaces to the beginning or end of the token. It might be a good idea to temporarily paste the token into a plain text editor.
Note that you will not be able to access the token string once you exit the window! You might want to keep this window open until you’ve completed the steps outlined next.
Once you’ve created your token on GitHub, you simply substitute your GitHub password with your access token. For example, if you are cloning a private repo that your account has access to, you would enter the above token instead of your GitHub password.
When you paste your token, you will not see it displayed on the command line. This might lead you to believe that it did not paste. Do not attempt a re-paste since this will only add the token to the end of the already pasted token.
Pasting your token each time you push or pull from your repo may prove cumbersome after a while. It might therefore be best to cache your token. This step is OS specific and is highlighted in the next subsections.
Saving tokens in Windows
If you are using a Windows based Git application, you might see the following window pop-up when you are first asked to enter your token.
If so, you can paste the token into the Personal Access Token field.
Alternatively, you can add a git setting via the Windows Bash environment as follows:
Note that this config option only works in the Git for Windows Bash shell. This option will not work in a Windows WSL Ubuntu environment. If you are using WSL Ubuntu, you need to follow the Linux instructions listed below.
The credentials get stored in Windows’ Credential Manager. You can delete this stored credential by accessing the Credential Manager via Control Panel >> All Control Panel Items >> Credential Manager or by simply typing Credential Manager in the Windows’ task bar.
Saving tokens in Mac
You’ll need the OSX keychain credential helper. If you installed Git using Homebrew or via the Xcode command line, then osxkeychain helper should be part of the installation.
You can check for its installation via the following command:
To have Git store the token in osxkeychain, type:
The next time you are prompted for a user name and password, simply type your GitHub account name, then your personal access token. This will be a one time operation after which the token will be permanently stored.
Click here to for more information on using Keychain with Git.
Saving tokens in Linux
To temporarily cache the token on Linux, use the following command:
Note, however, that the token is only cached for 15 minutes by default. If you want the token to be cached for a longer period of time, add the 'cache —timeout=XX\' option where XX is time in seconds. For example, to cache the token for 24 hours (86,400 seconds), type:
To permanently cache the token on Linux, type: (https://stackoverflow.com/a/12240995):
The next time you are prompted for your GitHub user name and token, the information will be stored permanently in a .git-credentials file under your home folder. Note, however, that this file is not encrypted. For a more secure permanent solution, you might want to check the SSH based authentication option.
SSH based authentication
NOTE: If you adopt an SSH based approach to authentication, you will need to connect to your repo via ssh . For example, if user jdcolby ’s repo name is repo1 , you would connect to it via:
This differs from the HTTPS option adopted in this workshop:
Checking for existing SSH keys
You might or might not already have public keys under
If you do, look for the files ending with .pub . The contents of these public keys are used to link your local repos to your GitHub account. By default, the filenames of the public keys are one of the following: id_ed25519.pub or id_rsa.pub . If these files exist in your
/.ssh folder, you can jump to the Adding SSH key to your GitHub account section of this tutorial.
Generating a new SSH key
In your Bash shell, type the following (note that the email address should be the one tied to your GitHub account). For example, jdcolby would type the following:
This creates a new SSH key, using the provided email as a label. Accept the default file location and press the Enter key.
At the prompt, type a secure passphrase. This passphrase will be used instead of your password when performing a Git/GitHub transaction from your computer, so don’t forget it!
You will then see an output similar to this:
Adding the SSH key to the ssh-agent process
Next, you need to add the previously generated key to a process called ssh-agent .
Windows and Linux
You’ll then be prompted to enter the passphrase used in the earlier step.
Edit (or create it if non-existent) the
/.ssh/config file by adding the following lines of code.
Next, add the key to the ssh-agent . Note the use of the -K option.
Adding SSH key to your GitHub account
Now that you’ve completed the step on your computer, you will will switch to your GitHub account. But before you do, you will need to copy the SSH public key generated on the previous step to your clipboard.
\.ssh you should see a file ending with .pub such as id_ed25519.pub . This is the public key generated earlier in this tutorial that you will share with your GitHub account.
Open the contents of the
/.ssh/id_ed25519.pub file in your home folder.
Copy its contents. It should start with ssh-ed5519 . and end with your email address.
- On GitHub, click on your avatar, then select Settings.
- On the left sidebar, click on SSH and GPG keys.
- Click on New SSHkey.
- Assign a Title for this key (this is only used for your reference but is should be descriptive enough for you to know which client computer it is referencing).
- Paste the key from the .ssh/id_ed25519.pub file in the Key field (be careful not to add empty spaces).
- Click Add SSH key. You might be prompted to type your GitHub password.
Next, you can test your connection from your Bash environment.
In Bash, type the following (do not substitute the git@github.com address).
You might see the following warning (including the public key as shown below):
Type yes to continue.
The next warning should list your account name (e.g. jdcolby in this working example).
Cloning a GitHub repo using SSH
At this point, you should be all set. As mentioned at the beginning of this page, when using SSH to connect to your GitHub repo, you need to use the SSH protocol. For example, to clone repo1 , you would type:
You might be prompted for the passphrase that was used in an earlier step when you created the SSH key.
Converting an existing HTTPS local repo to SSH
If you’ve already cloned a repo using HTTPS on your local computer, you will need to make a few changes to your local repo before benefitting from the SSH system.
First, check that you are indeed using HTTPS:
To change from a HTTPS URL to a SSH URL, type:
Avoiding the need to enter a passphrase
If you do not wish to type your passphrase every time you perform a Git/GitHub transaction you can try one of the suggested methods below for your OS.
Windows and Linux
You need to instruct Bash to launch ssh-agent every time you start a new Bash session. One approach is to edit (or create if non existent)
/.bashrc by adding the following lines:
Once saved, every time you fire up a new Windows Bash session, you’ll be prompted for this passphrase at the beginning of the session at which point you will no longer be requested to enter the passphrase.
On most recent versions of Mac you will probably be prompted to save the passphrase to your Mac keychain, if not, you can add the following lines to your