How to create ssh key for git
How to create ssh key for git
What is an SSH KEY?
An SSH key is an access credential for the SSH (secure shell) network protocol. This authenticated and encrypted secure network protocol is used for remote communication between machines on an unsecured open network. SSH is used for remote file transfer, network management, and remote operating system access. The SSH acronym is also used to describe a set of tools used to interact with the SSH protocol.
SSH uses a pair of keys to initiate a secure handshake between remote parties. The key pair contains a public and private key. The private vs public nomenclature can be confusing as they are both called keys. It is more helpful to think of the public key as a «lock» and the private key as the «key». You give the public ‘lock’ to remote parties to encrypt or ‘lock’ data. This data is then opened with the ‘private’ key which you hold in a secure place.
How to Create an SSH Key
SSH keys are generated through a public key cryptographic algorithm, the most common being RSA or DSA. At a very high level SSH keys are generated through a mathematical formula that takes 2 prime numbers and a random seed variable to output the public and private key. This is a one-way formula that ensures the public key can be derived from the private key but the private key cannot be derived from the public key.
SSH keys are created using a key generation tool. The SSH command line tool suite includes a keygen tool. Most git hosting providers offer guides on how to create an SSH Key.
Generate an SSH Key on Mac and Linux
Both OsX and Linux operating systems have comprehensive modern terminal applications that ship with the SSH suite installed. The process for creating an SSH key is the same between them.
1. execute the following to begin the key creation
This command will create a new SSH key using the email as a label
2. You will then be prompted to «Enter a file in which to save the key.»
You can specify a file location or press “Enter” to accept the default file location.
3. The next prompt will ask for a secure passphrase.
A passphrase will add an additional layer of security to the SSH and will be required anytime the SSH key is used. If someone gains access to the computer that private keys are stored on, they could also gain access to any system that uses that key. Adding a passphrase to keys will prevent this scenario.
At this point, a new SSH key will have been generated at the previously specified file path.
4. Add the new SSH key to the ssh-agent
The ssh-agent is another program that is part of the SSH toolsuite. The ssh-agent is responsible for holding private keys. Think of it like a keychain. In addition to holding private keys it also brokers requests to sign SSH requests with the private keys so that private keys are never passed around unsecurly.
Before adding the new SSH key to the ssh-agent first ensure the ssh-agent is running by executing:
Once the ssh-agent is running the following command will add the new SSH key to the local SSH agent.
The new SSH key is now registered and ready to use!
Generate an SSH Key on Windows
Windows environments do not have a standard default unix shell. External shell programs will need to be installed for to have a complete keygen experience. The most straight forward option is to utilize Git Bash. Once Git Bash is installed the same steps for Linux and Mac can be followed within the Git Bash shell.
Windows Linux Subsystem
Modern windows environments offer a windows linux subsystem. The windows linux subsystem offers a full linux shell within a traditional windows environment. If a linux subsystem is available the same steps previously discussed for Linux and Mac can be followed with in the windows linux subsystem.
Summary
SSH keys are used to authenticate secure connections. Following this guide, you will be able to create and start using an SSH key. Git is capable of using SSH keys instead of traditional password authentication when pushing or pulling to remote repositories. Modern hosted git solutions like Bitbucket support SSH key authentication.
Generating a new SSH key and adding it to the ssh-agent
In this article
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 Enterprise Cloud, 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.
Paste the text below, substituting in your GitHub Enterprise Cloud 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,» press Enter. This accepts the default file location.
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.
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 * 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.
Add the SSH key to your account on GitHub Enterprise Cloud. 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 Enterprise Cloud. For more information, see «Adding a new SSH key to your GitHub account.»
Start the ssh-agent in the background.
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 Enterprise Cloud. 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.
Paste the text below, substituting in the email address for your account on GitHub Enterprise Cloud.
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.
How to generate ssh keys (for github)
Question: How do I generate ssh private and public keys (to be used in GitHub/GitLab) using command line.
The command below generates the error
I am using Windows XP.
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
The command to run is only
All the rest beginning with line 2 of your script is the output of ssh-keygen.
And replace you@example.com with your email address.
Here is the command
This will generate a key for you. You have to copy that and insert into your Github’s account (just one time).
Step 1: Generate Your SSH Key
Step 2: Use the Key
Then add the key we just generated. If you selected a different path than the default, be sure to replace that path in the command.
Step 3: Add the SSH Key on GitHub
if clip not found then add the next command
Finally Result something like on your cmd
copy from your cmd and go to your GitHub account setting find ssh and gpg keys
Explanation : ssh-keygen is a tool for creating new authentication key pairs for SSH. Such key pairs are used for automating logins, single sign-on, and for authenticating hosts
(for example cloning project from your private repo on Github straight to your aws machine).
Synopsis: ssh-keygen [-q] [-b bits] [-t dsa | ecdsa | ed25519 | rsa] [-N new_passphrase] [-C comment] [-f output_keyfile]
3.1. Генерация SSH-ключа для работы с GitHub
Во-первых, нам нужно проверить, установлен ли у вас уже SSH-ключ. Введите это в терминал:
Если в консоли появляется сообщение с текстом «Нет такого файла или каталога», значит, у вас еще нет SSH-ключа, и вам нужно будет его создать. Если в выводе консоли не появилось никакого сообщения, значит, у вас уже есть ключ.
Добавление созданных SSH-ключей в SSH-агент
Убедимся что SSH-агент включён:
Запускаем агента, он работает в фоновном режиме. В консоли должен появиться id запущенного процесса.
Пример (у вас он будет свой)
Добавим SSH-ключ в SSH-агент.
Если вы хотите использовать уже существующие ключи, вместо только что сгенерированных, тогда нужно заменить id_rsa при вводе команды в консоли именем существующего файла, содержащий приватный ключ.
В случаем использования только что созданных ключей просто вводим в консоль Git команду:
Результат который получите (у вас будет свой)
А теперь вам нужно сообщить GitHub, какой у вас SSH-ключ, чтобы вы могли отправлять свой код, не вводя каждый раз пароль.
Сначала вы перейдете туда, где GitHub получает наш SSH-ключ. Войдите в GitHub и щелкните изображение своего профиля в правом верхнем углу. Затем нажмите на Settings в раскрывающемся меню.
Выделите и скопируйте результат, который начинается с ssh-rsa и заканчивается вашим адресом электронной почты.
Если у вас будет ошибка, то этот ключ можно найти на вашем локальном компьютере.
Откройте в любом текстовом редакторе, скопируйте ключ и добавьте на сайте.
How to create ssh key for git
На данный момент, один из самых популярных репозиториев для системы контроля версий GitHub, использует аутентификацию пользователей через открытые SSH-ключи. Это позволяет работать с сервисом без ввода логина и пароля, а также удобно производить контроль доступа к своему репозиторию.
Рассмотрим вариант создания и добавления SSH-ключей к своему GitHub аккаунту.
Подготовка
Для начала скачаем и установим клиент GitHub по ссылке https://git-scm.com
Теперь попробуем клонировать существующий репозиторий c GitHub для понимания одной из самых популярных ошибок, возникающих при начале работы с Git. Для этого откроем установленную консоль Git Bash, нажав правую кнопку мыши и выбрав пункт Git Bash Here.
Не забудем предварительно перейти в подготовленный каталог для удобства экспериментов с Git. В моем случае это будет каталог C:/domains/test.
Введем в консоли Git Bash команду клонирования удаленного репозитория с GitHub:
Именно здесь мы столкнемся с фатальной ошибкой скачивания из-за ограничения доступа к GitHub:
Решим эту проблему созданием публичного ключа для GitHub.
Генерация SSH-ключей для GitHub
Итак, мы сгенерировали SSH-ключи и теперь перейдем к следующему этапу.
Добавление созданных SSH-ключей в SSH-агент
Следующим шагом будет добавление приватного ключа в GitHub аккаунт.
Добавление нового SSH-ключа в GitHub аккаунт
Проверим, что все нами сделано верно, опять введя в консоль Git команду клонирования удаленного репозитория:
Через несколько секунд получим на своем локальном компьютере полную копию нужного нам репозитория.
Таким образом единожды проведя операцию создания публичного SSH-ключа и внеся его в свой профиль на GitHub, мы обеспечим себе удобную и безопасную работу с удаленным репозиторием.
Источники информации:
- http://docs.github.com/en/enterprise-cloud@latest/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent
- http://stackoverflow.com/questions/3828823/how-to-generate-ssh-keys-for-github
- http://codebra.ru/ru/lessons-additionally/git/3/1
- http://bogdanov-blog.ru/generatsiya-ssh-klyuchej-dlya-github/