How to generate ssh key windows
How to generate ssh key windows
Как сгенерировать SSH-ключ для доступа на сервер
Введение
Использование SSH-ключей — простой и надежный способ обеспечения безопасности соединения с сервером. В отличие от пароля, взломать SSH-ключ практически невозможно. Сгенерировать SSH-ключ очень просто.
SSH-ключ для Linux/MacOS
Откройте терминал и выполните команду:
На консоль будет выведен следующий диалог:
Нажмите на клавишу Enter. Далее система предложит ввести кодовую фразу для дополнительной защиты SSH-подключения:
Этот шаг можно пропустить. При ответе на этот и следующий вопрос просто нажмите клавишу Enter.
После этого ключ будет создан, а на консоль будет выведено следующее сообщение:
Далее выполните в терминале команду:
На консоль будет выведен ключ. Скопируйте его и вставьте в соответствующее поле:
Нажмите на кнопку «Добавить».
Добавив ключ, выполните в терминале команду:
После этого соединение с сервером будет установлено. Вводить пароль при этом не потребуется.
SSH-ключ для Windows
В OC Windows подключение к удаленным серверам по SSH возможно, например, с помощью клиента Putty. Скачать его можно здесь (ссылка взята с официального сайта). Putty не требует установки — чтобы начать с ним работать, достаточно просто распаковать скачанный архив.
По завершении распаковки запустите файл puttygen.exe.
Выберите тип ключа SSH-2 RSA и длину 2048 бит, а затем нажмите на кнопку Generate:
Во время генерации водите курсором в пустой области окна (это нужно для создания псевдослучайности):
Сохраните сгенерированную пару ключей на локальной машине (кнопки Save public key и Save private key).
Скопируйте сгененированный ключ и вставьте его в соответствующее поле:
Заключение
В этой инструкции мы рассмотрели, как создать шифрованный протокол для связи с сервером: сгенерировали SSH-ключ для Linux/MacOS и Windows. Теперь вы можете входить в систему без пароля учетной записи.
Key-based authentication in OpenSSH for Windows
Applies to Windows Server 2022, Windows Server 2019, Windows 10 (build 1809 and later)
Most authentication in Windows environments is done with a username-password pair, which works well for systems that share a common domain. When working across domains, such as between on-premises and cloud-hosted systems, it becomes vulnerable to brute force intrusions.
By comparison, Linux environments commonly use public-key/private-key pairs to drive authentication that doesn’t require the use of guessable passwords. OpenSSH includes tools to help support key based authentication, specifically:
This document provides an overview of how to use these tools on Windows to begin using key-based authentication with SSH. If you’re unfamiliar with SSH key management, we strongly recommend you review NIST document IR 7966 titled «Security of Interactive and Automated Access Management Using Secure Shell (SSH)».
About key pairs
Key pairs refer to the public and private key files that are used by certain authentication protocols.
SSH public key authentication uses asymmetric cryptographic algorithms to generate two key files – one «private» and the other «public». The private key files are the equivalent of a password, and should stay protected under all circumstances. If someone acquires your private key, they can sign in as you to any SSH server you have access to. The public key is what is placed on the SSH server, and may be shared without compromising the private key.
Key based authentication enables the SSH server and client to compare the public key for a user name provided against the private key. If the server-side public key can’t be validated against the client-side private key, authentication fails.
Multi-factor authentication may be implemented with key pairs by entering a passphrase when the key pair is generated (see user key generation below). The user will be prompted for the passphrase during authentication. The passphrase is used along with the presence of the private key on the SSH client to authenticate the user.
A remote session opened via key based authentication does not have associated user credentials and hence is not capable of outbound authentication as the user, this is by design.
Host key generation
Public keys have specific ACL requirements that, on Windows, equate to only allowing access to administrators and System. On first use of sshd, the key pair for the host will be automatically generated.
You need to have OpenSSH Server installed first. Please see Getting started with OpenSSH.
By default the sshd service is set to start manually. To start it each time the server is rebooted, run the following commands from an elevated PowerShell prompt on your server:
Since there’s no user associated with the sshd service, the host keys are stored under C:\ProgramData\ssh.
User key generation
To use key-based authentication, you first need to generate public/private key pairs for your client. ssh-keygen.exe is used to generate key files and the algorithms DSA, RSA, ECDSA, or Ed25519 can be specified. If no algorithm is specified, RSA is used. A strong algorithm and key length should be used, such as Ed25519 in this example.
To generate key files using the Ed25519 algorithm, run the following command from a PowerShell or cmd prompt on your client:
The output from the command should display the following output (where «username» is replaced by your username):
You can press Enter to accept the default, or specify a path and/or filename where you would like your keys to be generated. At this point, you’ll be prompted to use a passphrase to encrypt your private key files. The passphrase can be empty but it’s not recommended. The passphrase works with the key file to provide two-factor authentication. For this example, we’re leaving the passphrase empty.
Remember that private key files are the equivalent of a password should be protected the same way you protect your password. Use ssh-agent to securely store the private keys within a Windows security context, associated with your Windows account. To start the ssh-agent service each time your computer is rebooted, and use ssh-add to store the private key run the following commands from an elevated PowerShell prompt on your server:
Once you’ve added the key to the ssh-agent on your client, the ssh-agent will automatically retrieve the local private key and pass it to your SSH client.
It is strongly recommended that you back up your private key to a secure location, then delete it from the local system, after adding it to ssh-agent. The private key cannot be retrieved from the agent providing a strong algorithm has been used, such as Ed25519 in this example. If you lose access to the private key, you will have to create a new key pair and update the public key on all systems you interact with.
Deploying the public key
To use the user key that was created above, the contents of your public key (\.ssh\id_ed25519.pub) needs to be placed on the server into a text file. The name and location of the file depends on whether the user account is a member of the local administrators group or a standard user account. The following sections cover both standard and administrative users.
Standard user
The contents of your public key (\.ssh\id_ed25519.pub) needs to be placed on the server into a text file called authorized_keys in C:\Users\username\.ssh\. You can copy your public key using the OpenSSH scp secure file-transfer utility, or using a PowerShell to write the key to the file.
The example below copies the public key to the server (where «username» is replaced by your username). You’ll need to use the password for the user account for the server initially.
Administrative user
The contents of your public key (\.ssh\id_ed25519.pub) needs to be placed on the server into a text file called administrators_authorized_keys in C:\ProgramData\ssh\. You can copy your public key using the OpenSSH scp secure file-transfer utility, or using a PowerShell to write the key to the file. The ACL on this file needs to be configured to only allow access to administrators and System.
The example below copies the public key to the server and configures the ACL (where «username» is replaced by your user name). You’ll need to use the password for the user account for the server initially.
This example shows the steps for creating the administrators_authorized_keys file. This only applies to administrator accounts and must be user instead of the per user file within the user’s profile location.
These steps complete the configuration required to use key-based authentication with OpenSSH on Windows. Once the example PowerShell commands have been run, the user can connect to the sshd host from any client that has the private key.
Управление ключами OpenSSH
Область применения Windows Server 2019, Windows 10: Windows Server 2022,
Чаще всего при аутентификации в Windows используется пара «имя пользователя — пароль», что подходит для систем с общим доменом. При работе с несколькими доменами, например с локальными и облачными системами, возникает риск атак методом перебора.
С другой стороны, среды Linux традиционно используют для аутентификации пару открытого и закрытого ключей, что делает ненужным использование угадываемых паролей. OpenSSH содержит средства, поддерживающие такой сценарий:
В этом документе описано, как использовать эти средства в Windows для перехода на аутентификацию на основе ключей по протоколу SSH. Если вы ничего не знаете об управлении ключами через SSH, мы настоятельно рекомендуем ознакомиться с документом NIST IR 7966 о защите интерактивного и автоматизированного управления доступом через Secure Shell (SSH).
Сведения о парах ключей
Парой ключей называются файлы открытого и закрытого ключей, которые используются в некоторых протоколах аутентификации.
При аутентификации SSH на основе открытого ключа используются асимметричные алгоритмы шифрования для создания двух файлов ключей, один из которых считается закрытым, а второй открытым. Файлы закрытых ключей выполняют функцию паролей, а значит, должны быть постоянно защищены. Если кто-то получит ваш закрытый ключ, он сможет войти от вашего имени на любой сервер с поддержкой SSH, к которому у вас есть доступ. Открытый ключ размещается на сервере SSH. Его можно свободно распространять, не компрометируя закрытый ключ.
Если на сервере SSH используется аутентификация с помощью ключей, сервер и клиент SSH сравнивают открытый ключ, связанный с предоставленным именем пользователя, с закрытым ключом. Если открытый ключ на стороне сервера не проходит проверку по закрытому ключу, сохраненному на стороне клиента, аутентификация не будет выполнена.
Многофакторную проверку подлинности можно реализовать с помощью пар ключей, введя парольную фразу при создании пары ключей (см. раздел о создании пользовательских ключей ниже). При аутентификации пользователю предлагается ввести эту парольную фразу. Она применяется вместе с закрытым ключом для аутентификации пользователя.
Создание ключей узла
Для открытых ключей действуют определенные требования к ACL, которые в среде Windows соответствуют предоставлению доступа только администраторам и системной учетной записи. При первом использовании sshd будет автоматически создана пара ключей для узла.
Сначала необходимо установить OpenSSH Server. См. статью о начале работы с OpenSSH.
По умолчанию служба sshd настроена для запуска вручную. Чтобы запускать ее каждый раз при перезагрузке сервера, выполните следующие команды в командной строке PowerShell с повышенными привилегиями на сервере:
Так как со службой sshd не связан какой-либо пользователь, ключи узла сохраняются в папке C:\ProgramData\ssh.
Создание ключей пользователя
Чтобы использовать аутентификацию на основе ключей, необходимо заранее создать для клиента одну или несколько пар открытого и закрытого ключей. Программа ssh-keygen.exe используется для создания файлов ключей, при этом вы можете задать алгоритмы DSA, RSA, ECDSA или Ed25519. Если алгоритм не указан, используется RSA. Необходимо использовать надежный алгоритм и соответствующую длину ключа, например Ed25519 в этом примере.
Чтобы создать файлы ключей с помощью алгоритма Ed25519, выполните следующую команду в командной строке PowerShell или в командной строке на клиенте:
Эта команда возвращает такие выходные данные (username заменяется вашим именем пользователя):
Можно нажать клавишу ВВОД, чтобы принять вариант по умолчанию, или указать путь и (или) имя файла для создания файлов ключей. На этом этапе вам будет предложено указать парольную фразу для шифрования файлов закрытого ключа. Она может быть пустой, но это не рекомендуется. Парольная фраза в сочетании с файлом ключа позволяет выполнить двухфакторную аутентификацию. В нашем примере парольная фраза остается пустой.
Теперь у вас есть пара открытого и закрытого ключей Ed25519 в указанном расположении. Файлы PUB являются открытыми ключами, а файлы без расширения — закрытыми.
Помните, что файлы закрытых ключей выполняют функцию пароля и должны защищаться так же тщательно. Для этого, чтобы безопасно хранить закрытые ключи в контексте безопасности Windows, связанным с определенным именем входа Windows, используйте ssh-agent. Запустите службу ssh-agent от имени администратора и выполните ssh-add, чтобы сохранить закрытый ключ.
После этого при каждом выполнении аутентификации с этого клиента с использованием закрытого ключа, ssh-agent будет автоматически извлекать его и передавать клиенту SSH.
Мы настоятельно рекомендуем создать резервную копию закрытого ключа в безопасном расположении, а затем удалить его из локальной системы после добавления в ssh-agent. Закрытый ключ нельзя получить из агента, если использовался надежный алгоритм, например Ed25519 в этом примере. Если вы утратите доступ к закрытому ключу, вам нужно будет создать новую пару ключей и обновить открытый ключ во всех системах, с которыми вы работаете.
Развертывание открытого ключа
Чтобы использовать созданный выше ключ пользователя, поместите содержимое открытого ключа (
\.ssh\id_ed25519.pub) на сервер в текстовый файл, имя и расположение которого зависят от того, принадлежит ли учетная запись пользователя к учетной записи участника группы локальных администраторов или обычного пользователя.
Обычный пользователь
Содержимое открытого ключа (
\.ssh\id_ed25519.pub) нужно разместить на сервере в текстовом файле authorized_keys в папке C:\Users\username\.ssh\. Клиентский компонент OpenSSH включает scp (служебная программа безопасной передачи файлов) для упрощения этого процесса.
В приведенном ниже примере открытый ключ копируется на сервер (username заменяется именем пользователя). Изначально необходимо будет использовать пароль для учетной записи пользователя на сервере.
Администратор
Содержимое открытого ключа (
\.ssh\id_ed25519.pub) нужно разместить на сервере в текстовом файле administrators_authorized_keys в папке C:\ProgramData\ssh\. Клиентский компонент OpenSSH включает scp (служебная программа безопасной передачи файлов) для упрощения этого процесса. Список управления доступом для этого файла должен быть настроен на предоставление доступа только администраторам и системе.
В приведенном ниже примере открытый ключ копируется на сервер и настраивает список управления доступом (username заменяется именем пользователя). Изначально необходимо будет использовать пароль для учетной записи пользователя на сервере.
Эти действия завершают настройку, которая требуется для использования аутентификации OpenSSH на основе ключей в среде Windows. Теперь пользователь может подключаться к узлу sshd с любого клиента, где есть закрытый ключ.
How Do I Generate SSH Keys?
An SSH key allows you to log into your server without a password. This guide describes creating SSH keys using a Linux, Mac, or Windows workstation in OpenSSH format, suitable for use with Vultr server instances.
Create an SSH Key with OpenSSH
OpenSSH is standard and should be present on macOS and most Linux distributions. We also have installation instructions for Windows 10 users. Follow these steps to create an SSH key with the OpenSSH utilities.
By default, the keys are stored in the
/.ssh directory. Most SSH clients automatically use these default filenames:
Algorithm | Public key | Private key |
---|---|---|
ED25519 (preferred) | id_ed25519.pub | id_ed25519 |
RSA (at least 2048-bit key size) | id_rsa.pub | id_rsa |
DSA (deprecated) | id_dsa.pub | id_dsa |
ECDSA | id_ecdsa.pub | id_ecdsa |
Press ENTER to save the key in the default location.
You may enter a passphrase for your key. We recommend using a passphrase, but you can press ENTER to bypass this prompt. If you use a passphrase, you will enter it each time you use the key unless you also use ssh-agent.
Your key is generated and saved.
Make a backup of the private key. The key cannot be recovered if lost.
Install OpenSSH on Windows 10
The OpenSSH client is an installable component for Windows 10 1809.
Once you’ve installed OpenSSH, follow the instructions above to create your SSH key.
Create an SSH Key on Windows with PuTTYgen
PuTTYgen is part of the PuTTY suite of utilities. It is available for all versions of Windows.
Recover a Lost Public Key
If you have access to the private key, you can recover the public key with OpenSSH.
For example, to regenerate the public key for
/example_key and send the output to
If a password is set for the key, you will be prompted to enter it.
Change the Key’s Passphrase
Enter your old and new passphrase (twice) at the prompts.
View the Key’s Fingerprint
The output is something like this:
Transfer a Key to Your Server
OpenSSH includes a utility to transfer a key to your server. When using this utility, you must authenticate to your server using SSH.
You will be prompted to authenticate with your server and transfer the key to the remote server’s authorized_keys file.
About SSH Key Formats
OpenSSH 6.5 introduced ED25519 keys in 2014, and they are available on most operating systems. It’s believed that ED25519 keys are more secure than RSA, with better performance. If you use an RSA key, the US National Institute of Science and Technology recommends a key size of at least 2048 bits.
More Information
For more information about managing SSH keys, see our other guides:
Generate new ssh keys in Windows 10 / 11 [closed]
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
I need to have 3 SSH keys for different repos.
12 Answers 12
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
p.s.: If you installed git with bash integration (like me) open «Git Bash» instead of «cmd» on first step
2019-04-07 UPDATE: I tested today with a new version of windows 10 (build 1809, «2018 October’s update») and not only the open SSH client is no longer in beta, as it is already installed. So, all you need to do is create the key and set your client to use open SSH instead of putty(pagent):
I tested on Git Extensions and Source Tree and it worked with my personal repo in GitHub. If you are in an earlier windows version or prefer a graphical client for SSH, please read below.
On windows 10, starting with version 1709 (win+R and type winver to find the build number), Microsoft is releasing a beta of the OpenSSH client and server. To be able to create a key, you’ll need to install the OpenSSH server. To do this follow these steps:
Now you can open a prompt and ssh-keygen and the client will be recognized by windows. I have not tested this. If you do not have windows 10 or do not want to use the beta, follow the instructions below on how to use putty.
ssh-keygen does not come installed with windows. Here’s how to create an ssh key with Putty:
For openssh keys, a few more steps are required:
Now that the keys are saved. Start pagent and add the private key there ( the ppk file in Putty’s format)
Remember that pagent must be running for the authentication to work
Источники информации:
- http://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_keymanagement
- http://docs.microsoft.com/ru-ru/windows-server/administration/openssh/openssh_keymanagement
- http://www.vultr.com/docs/how-do-i-generate-ssh-keys/
- http://stackoverflow.com/questions/31813080/generate-new-ssh-keys-in-windows-10-11