Как сгенерить ssh public key windows

Генерация ключей SSH в среде Windows раньше была сложным процессом, требующим установки сторонних инструментов. После обновления Windows 10 апреля 2018 года,

Генерация ключей SSH в среде Windows раньше была сложным процессом, требующим установки сторонних инструментов. После обновления Windows 10 апреля 2018 года, Windows поставляется с предустановленным клиентом OpenSSH, что означает, что вы можете использовать ssh-keygen для генерации ключей SSH. Давайте разберем, как сгенерировать SHH ключ в Windows 10.

Проверка OpenSSH в Windows 10

Нужно убедиться, что OpenSSH установлен на вашем компьютере, если вы обновили более раннюю версию Windows 10, вам может потребоваться включить ее вручную. Для этого:

  • Откройте параметры «Параметры» > «Приложения«. Затем справа нажмите на ссылку «Дополнительные возможности«.
  • Если вы не видите «Клиент OpenSSH» в появившемся списке, нажмите кнопку «Добавить компонент» и установите его из списка.

Перезагрузите ПК для уверенности.

Клиент OpenSSH в Windows 10

Сгенерировать SHH в Windows 10

Откройте командную строку и введите ssh-keygen

channel

  1. Вам будет предложено подтвердить место сохранения (можете изменить путь). Нажмите Enetr и место будет по умолчанию.
  2. Далее вам будет предложено задать пароль (ключевую фразу) к ключу, он не отображается при вводе, но вводится. Можно без пароля, нажать сразу Enter.
  3. Подтверждение выше заданного пароля.

генерация SSH в Windows 10

Windows сгенерирует вашу пару открытыхзакрытых ключей RSA. Открытый ключ будет сохранен как «id_rsa.pub» в указанной вами директории. Загрузите этот ключ на любые ПК, на которых вам нужен SSH. Затем вы можете открыть соединение, используя встроенный SSH-клиент Windows — введите «ssh user@hostname», чтобы подключиться и аутентифицироваться, используя ваши сгенерированные учетные данные.


Смотрите еще:

  • Быстродействие системы (System Idle Process) грузит процессор
  • Мониторинг CPU, GPU и RAM поверх окон в Windows 10
  • Исправить ошибку BlinitializeLibrary failed 0xc00000bb в Windows 10
  • Сетевой адаптер не имеет допустимых параметров настройки IP
  • Как удалить службу в Windows 10

[ Telegram | Поддержать ]

Introduction

SSH stands for Secure Shell and is a method used to establish a secure connection between two computers.

SSH works by authenticating based on a key pair, with a private key being on a remote server and the corresponding public key on a local machine. When the keys match, access is granted to the remote user.

This guide will show you how to generate an SSH key pair in Windows 10 using OpenSSH or PuTTY.

tutorial on How to generate SSH keys in OpenSSH and putty for Windows 10

Prerequisites

  • A system running Windows 10
  • A user account with administrative privileges
  • Access to the command prompt
  • A web browser (optional, to download PuTTY)

Generate an SSH key in Windows 10 with OpenSSH Client

Step 1: Verify if OpenSSH Client is Installed

First, check to see if you have the OpenSSH client installed:

1. Open the Settings panel, then click Apps.

2. Under the Apps and Features heading, click Optional Features.

screenshot of Windows Optional Features

3. Scroll down the list to see if OpenSSH Client is listed.

  • If it’s not, click the plus-sign next to Add a feature.
  • Scroll through the list to find and select OpenSSH Client.
  • Finally, click Install.
How to find OpenSSH Client in the Windows optional features list

Step 2: Open Command Prompt

1. Press the Windows key.

2. Type cmd.

3. Under Best Match, right-click Command Prompt.

4. Click Run as Administrator.

Image of how to run the Windows Command Prompt as an Admin user.

5. If prompted, click Yes in the Do you want to allow this app to make changes to your device? pop-up.

Step 3: Use OpenSSH to Generate an SSH Key Pair

1. In the command prompt, type the following:

ssh-keygen
OpenSSH command tgenerates an SSH key in Windows

2. By default, the system will save the keys to C:Usersyour_username/.ssh/id_rsa. You can use the default name, or you can choose more descriptive names. This can help distinguish between keys, if you are using multiple key pairs. To stick to the default option, press Enter.

Note: If a file with the same name already exists, you will be asked whether you want to overwrite the file.

3. You’ll be asked to enter a passphrase. Hit Enter to skip this step.

4. The system will generate the key pair, and display the key fingerprint and a randomart image.

5. Open your file browser.

6. Navigate to C:Usersyour_username/.ssh.

7. You should see two files. The identification is saved in the id_rsa file and the public key is labeled id_rsa.pub. This is your SSH key pair.

SSH key pair and randomart image generated with the SSH keys on Windows 10.

Note: Normally, the public key is identified with the .pub extension. You can use Notepad to see the contents of both the private and public key.

Generate SSH Keys Using PuTTY

Before OpenSSH was included with Windows, the PuTTY tool was the gold standard for generating SSH keys.

Step 1: Install PuTTY

1. Browse to the developer’s page, and download the installer for PuTTY:

  • https://www.chiark.greenend.org.uk/~sgtatham/putty/latest.html

2. Double-click the downloaded file and follow the installation wizard to finish the installation.

  • On the initial dialog of the installation wizard, click Next.
  • Select the destination folder. Use the default installation configuration unless you have a specific need to change it. Click Next to move on to the next screen.
Select destination folder for the PuTTY installation
  • Select PuTTY product features to be installed. Stick to the defaults if you do not have any specific needs. Click Next to move on to the next screen.
Putty product features selected
  • Once the process completes, click Finish to exit the installation wizard.

Step 2: Run the PuTTY SSH Key Generator

1. Press the Windows key.

2. Type puttygen.

3. Under Best Match, right-click PuTTYgen.

4. Click Run as administrator.

5. If prompted, click Yes on the Do you want to allow this app to make changes to your device? pop-up.

Step 3: Use PuTTY to Create a Pair of SSH Keys

The process outlined below will generate RSA keys, a classic and widely-used type of encryption algorithm. The PuTTY keygen tool offers several other algorithms – DSA, ECDSA, Ed25519, and SSH-1 (RSA).

If you require a different encryption algorithm, select the desired option under the Parameters heading before generating the key pair.

1. In the PuTTY Key Generator window, click Generate.

2. Move the cursor around in the gray box to fill up the green bar.

Generating an SSH key pair in Putty.

3. Save the public key:

  • Click the button labeled Save public key.
  • Choose a location to save the key.
  • Give the key a name (e.g., putty_key.pub)
Editing advanced SSH keys options in PuTTY.

4. Save the private key:

  • Click the Conversions menu at the top.
  • Click Export OpenSSH key.
  • You’ll be asked if you want to save a key without a passphrase. Click Yes.
  • Choose a location to save the key (usually the same folder as the public key).
  • Give the key a name (e.g., putty_key).

Using Your SSH Keys

To use your SSH keys, copy your public SSH key to the system you want to connect to. Use your private SSH key on your own system. Your private key will match up with the public key, and grant access.

For further details and troubleshooting, see our guide on paswordless SSH login using SSH keys.

Conclusion

This article has provided two methods of generating SSH key pairs on a Windows 10 system. Use the SSH keys to connect to a remote system without the use of passwords.

В этой статье мы настроим SSH аутентификацию в Windows по RSA или EdDSA ключам для безопасного доступа к удаленным компьютерам/серверам. Рассмотрим, как сгенерировать открытый и закрытый ключи (сертификаты) в Windows и настроить сервер OpenSSH в Windows 10/11 и Windows Server 2019/2022 для аутентификации по ключам (без паролей).

Аутентификация по SSH ключам широко используется в мире Linux, а в Windows этот функционал появился относительно недавно. Идея заключается в том, что на SSH сервере добавляется открытый ключ клиента и при подключении сервер проверяет наличие соответствующего закрытого ключа у клиента. Таким образом удаленный пользователь может аутентифицироваться в Windows без ввода пароля.

Содержание:

  • Генерация SSH ключей на клиенте Windows
  • Настройка OpenSSH в Windows для авторизации по ключам
  • Вход по SSH ключу для локальных администраторов Windows

Генерация SSH ключей на клиенте Windows

На клиентском, компьютере, с которого вы будет подключаетесь к удалённому серверу Windows с OpenSSH, вам нужно сгенерировать пару ключей (открытый и закрытый). Закрытый ключ хранится на клиенте (не отдавайте его никому!), а открытый ключ нужно скопировать в файл authorized_keys на SSH сервере. Чтобы сгенерировать SSH ключи на клиенте Windows, вы должны установить клиент OpenSSH.

В Windows 10/11 и Windows Server 2019/2022 клиент OpenSSH устанавливается как отдельный встроенный компонент с помощью PowerShell:

Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

Запустите обычную (непривилегированную сессию PowerShell) и сгенерируйте пару ED25519 ключей:

ssh-keygen -t ed25519

По умолчанию утилита ssh-keygen генерирует ключи RSA 2048. В настоящий момент вместо RSA ключей рекомендуется использовать именно ED25519.

Утилита попросит вас указать пароль для защиты закрытого ключа. Если вы укажете пароль, то каждый раз при использовании этого ключа для SSH авторизации, вы должны будете вводить этот пароль. Я не стал указывать пароль для ключа (не рекомендуется).

windows ssh-keygen генерация пары ssh ключей

Generating public/private ed25519 key pair. Enter file in which to save the key (C:Usersmyuser/.ssh/id_ed25519):  

Enter passphrase (empty for no passphrase): Enter same passphrase again: Your identification has been saved in C:Usersmyuser/.ssh/id_ed25519. Your public key has been saved in C:Usersmyuser/.ssh/id_ed25519.pub. The key fingerprint is: SHA256:C2wXeCQSUcJyq0 [email protected] The key's randomart image is: +--[ED25519 256]--+ | ..*O=..o. | +----[SHA256]-----+

Утилита ssh-keygen создаст каталог .ssh в профиле текущего пользователя Windows (%USERPROFILE%.ssh) и сгенерирует 2 файла:

  • id_ed25519
    – закрытый ключ (если вы сгенерировали ключ типа RSA, файл будет называться
    id_rsa
    )
  • id_ed25519.pub
    – публичный ключ (аналогичный RSA ключ называется
    id_rsa.pub
    )

открытый и закрытый ssh ключи в windows

После того, как ключи созданы, вы можете добавить закрытый ключ в службу SSH Agent, которая позволяет удобно управлять закрытыми ключами и использовать их для аутентификации.

SSH Agent может хранить закрытые ключи и предоставлять их в контексте безопасности текущего пользователя. Запустите службу ssh-agent и настройте автоматический запуск с помощью PowerShell команд управления службами:

Set-service ssh-agent StartupType ‘Automatic’
Start-Service ssh-agent

Добавьте ваш закрытый ключ в базу ssh-agent:

ssh-add "C:Usersuser.sshid_ed25519"

Identity added: C:Userskbuldogov.sshid_ed25519 ([email protected])

добавить ключ в ssh агент windows
Или так:

ssh-add.exe $ENV:UserProfile.sshid_ed25519

Настройка OpenSSH в Windows для авторизации по ключам

SSH сервер (в этом примере это удаленный компьютер с Windows 11 и настроенной службой OpenSSH).

Скопируйте файл id_ed25519.pub в каталог .ssh профиля пользователя, под которым вы будете подключаться к SSH серверу. Например, у меня в Windows 11 создан пользователь user1, значит я должен скопировать ключ в файл C:Usersuser1.sshauthorized_keys.

В данном примере подразумевается, что user1 это обычная учетная запись пользователя без прав локального администратора на компьютере с сервером SSH.

Если каталог .ssh в профиле отсутствует, его нужно создать вручную.

файл с открытым ключом на сервере ssh authorized_keys

Можно скопировать ключ на SSH сервер с клиента с помощью SCP:

scp C:Usersyouruser.sshid_rsa.pub [email protected]:c:usersuser1.sshauthorized_keys

В один файл authorized_keys можно добавить несколько открытых ключей.

По умолчанию в OpenSSH сервере в Windows отключена аутентификация по ключам. Вы можете проверить это в конфигурационном файле sshd_config. Проще всего получить список разрешенных способов аутентификации в OpenSSH с помощью такой PowerShell команды (Select-String используется как аналог grep в PowerShell):

cat "C:ProgramDatasshsshd_config"| Select-String "Authentication"

#PubkeyAuthentication yes
#HostbasedAuthentication no
# HostbasedAuthentication
 PasswordAuthentication yes
#GSSAPIAuthentication no

включить ssh аутентфикацию по ключам в windows

В этом примере строка PubkeyAuthentication закомментирована, значит этот способ аутентификации отключен.

Откройте файл sshd_config с помощью блокнота, раскоментируйте строку:

Notepad C:ProgramDatasshsshd_config

PubkeyAuthentication yes

параметр PubkeyAuthentication yes в файле sshd_config

Также в конфигурационном файле sshd_config придется отключить режим StrictModes. По умолчанию этот режим включен и запрещает аутентификацию по ключам, если закрытый и открытый ключ недостаточно защищены. Раскомментируйте строку
#StrictModes yes
, измените на
StrictModes no
.

sshd_config отключить StrictModes

Сохраните файл и перезапустите службу sshd:

Restart-Service sshd

Теперь вы можете подключиться к SSH серверу без ввода пароля пользователя. А если вы не задали пароль (passphrase) для закрытого ключа, вы сразу автоматически подключитесь к вашему удаленному серверу Windows.

Для подключения через SSH к удаленному хосту используется следующая команда:

ssh (username)@(имя или IP адрес SSH сервера)

Например,

ssh [email protected]

Это означает, что вы хотите подключиться к удаленному SSH серверу с адресом 192.168.1.90 под учетной записью admin. Служба SSH Agent автоматически попытается использовать для авторизации сохраненный ранее закрытый ключ.

  • Если вы не хотите использовать ssh-agent для управления ключами, вы можете указать путь к закрытому ключу, который нужно использовать для SSH аутентификации:
    ssh [email protected] -i "C:Usersuser.sshid_ed25519"
  • Для подключения с помощью учетной записи пользователя из домена Active Directory используется формат:
    ssh [email protected]@168.1.90 -i <private_key_absolute_path>

первое подключение к windows по ssh добавить отпечаток ключа

При первом подключении нужно добавить отпечаток ключа SSH сервера в доверенные. Наберите yes -> Enter.

The authenticity of host '192.168.1.90 (192.168.1.90)' can't be established.
ECDSA key fingerprint is SHA256:LNMJTbTS0EmrsGYTHB3Aa3Tisp+7fvHwZHbTA900ofw.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes

Информацию по аутентификации в Windows с помощью SSH ключей можно найти в журнале события. В современных версиях OpenSSH логи пишутся не в текстовые файлы, а в отдельный журнал Event Viewer (Application and services logs -> OpenSSH -> Operational).

При успешном подключении с помощью ключа в журнале появится событие:

EventID 4
sshd: Accepted publickey for locadm from 192.168.14.1 port 55772 ssh2: ED25519 SHA256:FEHDWM/J74FbIzCCoJNbh14phS67kQgh7k8UrKPSvCM

событие ssh аутентфикации по ключу в event viewer windows 11

Если вы не смогли подключиться к вашему SSH серверу по RSA ключу, и у вас все равно запрашивается пароль, скорее всего пользователь, под которым вы подключаетесь, входит в группу локальных администраторов сервера (SID группы S-1-5-32-544). Об этом далее.

ssh подключение по ключу под администратором

Вход по SSH ключу для локальных администраторов Windows

В OpenSSH используются особые настройки доступа по ключам для пользователей с правами локального администратора Windows.

В первую очередь, вместо ключа authorized_keys в профиле пользователя нужно использовать файл с ключами C:ProgramDatasshadministrators_authorized_keys. Вам нужно добавить ваш ключ в этот текстовый файл (в целях безопасности права на этот файл должны быть только у группы Administrators и SYSTEM).

файл administrators_authorized_keys ключи для ssh входа под локальными администраторами

Вы можете изменить NTFS права на файл с помощью:

  • утилиты icacls:
    icacls.exe "C:ProgramDatasshadministrators_authorized_keys" /inheritance:r /grant "Administrators:F" /grant "SYSTEM:F
  • или с помощью PowerShell командлетов get-acl и set-acl:
    get-acl "$env:programdatasshssh_host_rsa_key" | set-acl "$env:programdatasshadministrators_authorized_keys"

настройка ntfs прав доступа к файлу administrators_authorized_keys для ssh доступа по ключам в windows

После этого SSH аутентификация по ключам работает даже при отключенном режиме StrictModes

alert]Чтобы использовать ключ authorized_keys из профиля пользователя, и не переносить данные открытого ключа в файл administrators_authorized_keys, вы можете закомментировать строку в файле конфигурации OpenSSH (C:ProgramDatasshsshd_config).

Закомментируйте строки:

#Match Group administrators
# AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

Match Group administrators AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys

Дополнительно в файле sshd_config вы можете запретить SSH подключение по паролю по паролю:

PasswordAuthentication no

После сохранения изменений в файле sshd_config не забудьте перезапустить службу sshd.

restart-service sshd

Если вы установили PasswordAuthentication no, и некорректно настроите аутентификацию по ключам, то при подключении по ssh будет появляться ошибка:

[email protected]: Permission denied (publickey,keyboard-interactive).

ошибка ssh аутентфикации в windows по ключу Permission denied publickey keyboard interactive

В OpenSSH на Linux доступна опция PermitRootLogin, позволяющая ограничить доступ к SSH серверу под аккаунтом root. В Windows OpenSSH эта директива не доступна и для ограничения доступа администраторов нужно использовать параметр DenyGroups.

Итак, вы настроили SSH аутентификацию в Windows по открытому RSA-ключу (сертификату). Теперь вы можете использовать такой способ аутентификации для безопасного доступа к удаленным северам, автоматического поднятия проброса портов в SSH туннеле, запуска скриптов и других задачах автоматизации.

Modified: 13 Dec 2022 21:28 UTC

On Windows, you can create SSH keys in many ways. This document explains how to use two SSH applications, PuTTY and Git Bash.

We recommend ECDSA or RSA keys. DSA keys are supported, but not recomended.

PuTTY

PuTTY is an SSH client for Windows. You can use PuTTY to generate SSH keys. PuTTY is a free open-source terminal emulator that functions much like the Terminal application in macOS in a Windows environment. This section shows you how to manually generate and upload an SSH key when working with PuTTY in the Windows environment.

About PuTTY

PuTTY is an SSH client for Windows that you will use to generate your SSH keys. You can download PuTTY from www.chiark.greenend.org.uk.

When you install the PuTTY client, you also install the PuTTYgen utility. PuTTYgen is what you will use to generate your SSH key for a Windows VM.

This page gives you basic information about using PuTTY and PuTTYgen to log in to your provisioned machine. For more information on PuTTY, see the PuTTY documentation

Generating an SSH key

To generate an SSH key with PuTTYgen, follow these steps:

  1. Open the PuTTYgen program.
  2. For Type of key to generate, select SSH-2 RSA.
  3. Click the Generate button.
  4. Move your mouse in the area below the progress bar. When the progress bar is full, PuTTYgen generates your key pair.
  5. Type a passphrase in the Key passphrase field. Type the same passphrase in the Confirm passphrase field. You can use a key without a passphrase, but this is not recommended.
  6. Click the Save private key button to save the private key. Warning! You must save the private key. You will need it to connect to your machine.
  7. Right-click in the text field labeled Public key for pasting into OpenSSH authorized_keys file and choose Select All.
  8. Right-click again in the same text field and choose Copy.

PuTTY key generator

Importing your SSH key

Now you must import the copied SSH key to the portal.

  1. After you copy the SSH key to the clipboard, return to your account page.
  2. Choose to Import Public Key and paste your SSH key into the Public Key field.
  3. In the Key Name field, provide a name for the key. Note: although providing a key name is optional, it is a best practice for ease of managing multiple SSH keys.
  4. Add the key. It will now appear in your table of keys under SSH.

The SSH Keys table

Warning! PuTTY and OpenSSH use different formats of public SSH keys. If the text you pasted in the SSH Key starts with —— BEGIN SSH2 PUBLIC KEY, it is in the wrong format. Be sure to follow the instructions carefully. Your key should start with ssh-rsa AAAA….

Once you upload your SSH key to the portal, you can connect to your virtual machine from Windows through a PuTTY session.

Git Bash

The Git installation package comes with SSH. Using Git Bash, which is the Git command line tool, you can generate SSH key pairs. Git Bash has an SSH client that enables you to connect to and interact with Triton containers on Windows.

To install Git:

  1. (Download and initiate the Git installer](https://git-scm.com/download/win).
  2. When prompted, accept the default components by clicking Next.
  3. Choose the default text editor. If you have Notepad++ installed, select Notepad++ and click Next.
  4. Select to Use Git from the Windows Command Prompt and click Next.
  5. Select to Use OpenSSL library and click Next.
  6. Select to Checkout Windows-style, commit Unix-style line endings and click Next.
  7. Select to Use MinTTY (The default terminal of mYSYS2) and click Next.
  8. Accept the default extra option configuration by clicking Install.

When the installation completes, you may need to restart Windows.

Launching GitBash

To open Git Bash, we recommend launching the application from the Windows command prompt:

  1. In Windows, press Start+R to launch the Run dialog.
  2. Type C:Program FilesGitbinbash.exe and press Enter.

Generating SSH keys

First, create the SSH directory and then generate the SSH key pair.

One assumption is that the Windows profile you are using is set up with administrative privileges. Given this, you will be creating the SSH directory at the root of your profile, for example:

C:Usersjoetest
  1. At the Git Bash command line, change into your root directory and type.
mkdir .ssh
  1. Change into the .ssh directory C:Usersjoetest.ssh

  2. To create the keys, type:
ssh-keygen.exe
  1. When prompted for a password, type apassword to complete the process. When finished, the output looks similar to:
Ssh-keygen.exe
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/joetest/.ssh/id_rsa): /c/Users/joetest/.ssh/
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/joetest/.ssh/
Your public key has been saved in /c/Users/joetest/.ssh/
The key fingerprint is:
SHA256:jieniOIn20935n0awtn04n002HqEIOnTIOnevHzaI5nak joetest@periwinkle
The key's randomart image is:

 +---[RSA 2048]----+
 |*= =+.           |
 |O*=.B            |
 |+*o* +           |
 |o +o.  .         |
 | ooo  + S        |
 | .o.ooo* o       |
 |  .+o+*oo .      |
 |   .=+..         |
 |   Eo            |
 +----[SHA256]-----+

$ dir .ssh
id_rsa  id_rsa.pub

Uploading an SSH key

To upload the public SSH key to your Triton account:

  1. Open Triton Service portal, select Account to open the Account Summary page.
  2. From the SSH section, select Import Public Key.
  3. Enter a Key Name. Although naming a key is optional, labels are a best practice for managing multiple SSH keys.
  4. Add your public SSH key.

When Triton finishes the adding or uploading process, the public SSH key appears in the list of SSH keys.

What are my next steps?

  • Adding SSH keys to agent.
  • Set up the Triton CLI and CloudAPI on Windows.
  • Set up the Triton CLI and CloudAPI.
  • Create an instance in the Triton Service Portal.
  • Set up the triton-docker command line tool.
  • Visit PuTTYgen to learn more about the PuTTYgen and to see
    the complete installation and usage guide.

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):

  1. open command prompt (cmd)
  2. enter ssh-keygenand press enter
  3. press enter to all settings. now your key is saved in c:Users.sshid_rsa.pub
  4. Open your git client and set it to use open SSH

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.

2018-06-04 UDPATE:

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:

  1. open the start menu
  2. Type «optional feature»
  3. select «Add an optional feature»
  4. Click «Add a feature»
  5. Install «Open SSH Client»
  6. Restart the computer

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:

  1. Install putty
  2. Open PuttyGen
  3. Check the Type of key and number of bytes to usePuttyGen parameters
  4. Move the mouse over the progress bar generating key with mouse input
  5. Now you can define a passphrase and save the public and private keys key created dialog

For openssh keys, a few more steps are required:

  1. copy the text from «Public key for pasting» textbox and save it as «id_rsa.pub»
  2. To save the private key in the openssh format, go to Conversions->Export OpenSSH key ( if you did not define a passkey it will ask you to confirm that you do not want a pass key)
    menu for converting key to OpenSSH format
  3. Save it as «id_rsa»

Now that the keys are saved. Start pagent and add the private key there ( the ppk file in Putty’s format)
pagent keys dialog

Remember that pagent must be running for the authentication to work

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.

  1. Open TerminalTerminalGit Bash.

  2. Paste the text below, substituting in your GitHub email address.

    $ ssh-keygen -t ed25519 -C "your_email@example.com"

    Note: If you are using a legacy system that doesn’t support the Ed25519 algorithm, use:

    $ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

    This creates a new SSH key, using the provided email as a label.

    > Generating public/private ALGORITHM key pair.

    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.

    > Enter a file in which to save the key (/Users/YOU/.ssh/id_ALGORITHM: [Press enter]

    > Enter a file in which to save the key (/c/Users/YOU/.ssh/id_ALGORITHM):[Press enter]

    > Enter a file in which to save the key (/home/YOU/.ssh/ALGORITHM):[Press enter]

  3. At the prompt, type a secure passphrase. For more information, see «Working with SSH key passphrases.»

    > Enter passphrase (empty for no passphrase): [Type a passphrase]
    > Enter same passphrase again: [Type passphrase again]

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.

  1. Start the ssh-agent in the background.

    $ eval "$(ssh-agent -s)"
    > Agent pid 59566

    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.

  2. 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.

      $ open ~/.ssh/config
      > The file /Users/YOU/.ssh/config does not exist.
    • If the file doesn’t exist, create the file.

      $ touch ~/.ssh/config
    • Open your ~/.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.

      Host *.github.com
        AddKeysToAgent yes
        UseKeychain yes
        IdentityFile ~/.ssh/id_ed25519
      

      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.

        Host *.github.com
          IgnoreUnknown UseKeychain
        
  3. 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.

    $ ssh-add --apple-use-keychain ~/.ssh/id_ed25519

    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.»

  4. 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.

  1. 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:

    # start the ssh-agent in the background
    $ eval "$(ssh-agent -s)"
    > Agent pid 59566
  2. 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.

    $ ssh-add ~/.ssh/id_ed25519
  3. Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»

  1. Start the ssh-agent in the background.

    $ eval "$(ssh-agent -s)"
    > Agent pid 59566

    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.

  2. 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.

    $ ssh-add ~/.ssh/id_ed25519
  3. 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.»

  1. Insert your hardware security key into your computer.

  2. Open TerminalTerminalGit Bash.

  3. Paste the text below, substituting in the email address for your account on GitHub.

    $ ssh-keygen -t ed25519-sk -C "YOUR_EMAIL"

    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.

    $ ssh-keygen -t ecdsa-sk -C "your_email@example.com"
  4. When you are prompted, touch the button on your hardware security key.

  5. When you are prompted to «Enter a file in which to save the key,» press Enter to accept the default file location.

    > Enter a file in which to save the key (/Users/YOU/.ssh/id_ed25519_sk): [Press enter]
    > Enter a file in which to save the key (/c/Users/YOU/.ssh/id_ed25519_sk):[Press enter]
    > Enter a file in which to save the key (/home/YOU/.ssh/id_ed25519_sk):[Press enter]
  6. When you are prompted to type a passphrase, press Enter.

    > Enter passphrase (empty for no passphrase): [Type a passphrase]
    > Enter same passphrase again: [Type passphrase again]
  7. Add the SSH key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»

1. Overview

SSH, the secure shell, is often used to access remote Linux systems. But its authentication mechanism, where a private local key is paired with a public remote key, is used to secure all kinds of online services, from GitHub and Launchpad to Linux running on Microsoft’s Azure cloud.

Generating these keys from Linux is easy, and thanks to Ubuntu on WSL, you can follow the same process from Windows 10. But even without Ubuntu, SSH keys can also be generated with the free and open source OpenSSH client built into Windows 10 or with PuTTY for Windows 8.1 and earlier.

Over the following few steps, we’ll guide you through the process of generating SSH keys using Ubuntu on WSL, OpenSSH, and PuTTY.

Requirements

All you need is a PC running Windows and one of the following installed:

  • Ubuntu on WSL for Windows 10
  • The OpenSSH client built into Windows 10
  • The puttygen.exe executable from PuTTY for Windows 7 or 8.1

If you don’t already have Ubuntu on WSL, take a look at our Install Ubuntu on WSL tutorial.

screenshot

Originally authored by Graham Morrison.


2. Passphrase considerations

When creating the SSH key pair, as shown in the following steps, you can choose to either lock your private key with a passphrase or use no passphrase at all.

Adding a passphrase requires the same passphrase to be entered whenever the key pair is used. Not adding a passphrase removes this requirement. For this reason, creating a key pair without a passphrase is more convenient and potentially essential for certain scripts and automation tasks. But it’s also less secure.

If a third-party gains access to a private key without a passphrase they will be able to access all connections and services using the public key.

A good compromise between convenience and security is to generate a separate key pair for each service or connection you want to use, adding a passphrase only for critical services. If you suspect a key has been compromised, simply generate a new pair for that service and remove the less secure key.


3. Key generation with Ubuntu on WSL

Launch Ubuntu on WSL from the start menu and make sure SSH is installed by entering following command at the command prompt:

sudo apt install openssh-client

The key generation process is identical to the process on a native Linux or Ubuntu installation. With SSH installed, run the SSH key generator by typing the following:

ssh-keygen -t rsa

77777777

You will be asked two questions. The first asks where to save the key, and you can press return to accept the default value. The second question asks for the passphrase. As discussed, entering a passphrase will require you to use the same passphrase whenever the key is accessed.

However, the passphrase isn’t a requirement, and pressing return (twice) will generate a key pair without one. Consequently, you won’t be asked for a passphrase when using your key.

When the process has finished, the private key and the public key can be found in the ~/.ssh directory accessible from the Ubuntu terminal, or the following folder from Windows file manager:

\wsl$\Ubuntuhome<username>.ssh

888888


4. Key generation with OpenSSH

Recent versions of Windows 10 include the OpenSSH client by default, but if yours does not or you’re unsure, follow these steps:

Open Settings and then navigate to Apps > Apps and Features > Optional Features:

image7

image6

Scan this list to see if OpenSSH client is already installed. If not, at the top of the page select Add a feature, then, to install the OpenSSH client, locate OpenSSH Client and click Install

Once the installation completes, return to Apps > Apps and Features > Optional Features and you should see the OpenSSH component(s) listed:

image10

You can optionally install the OpenSSH client using PowerShell, first launch ‘Windows PowerShell’ as an Administrator. To check the status of the OpenSSH client type the command:

Get-WindowsCapability -Online | ? Name -like 'OpenSSH.Client*'

This should return:

Name  : OpenSSH.Client~~~~0.0.1.0
State : Installed

image8

If OpenSSH client is listed as “NotPresent” you can install by typing:

Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0

The command should return:

Path          :
Online        : True
RestartNeeded : False

image5

Finally, to generate your keys, launch ‘Windows PowerShell’ as an Administrator, and type:

ssh-keygen

55555


5. Key generation with Putty

To generate a key pair with the PuTTY key generator, simply run puttygen.exe and click the Generate button in the window that appears.

You will be asked to move the mouse and press keys to improve the random number generation at the heart of SSH security. After this, the raw contents of the public key will be displayed alongside its fingerprint and a timestamp comment.

Two important fields, Key passphrase and Confirm passphrase, allow you to enter a passphrase to protect the private key.

Finally, you will need to export both the private and public keys separately:

  • to export the private key, select Export OpenSSH key from the Conversions menu
  • to export the public key, click Save public key from the main window

Public keys typically use the .pub suffix. By convention, the private key is usually called id_rsa and the public key id_rsa.pub, but this isn’t a requirement. It’s common to have many keys with more descriptive filenames, for instance.

screenshot


6. Getting help

Congratulations! You have just generated a SSH key pair from Windows 10. You can now add the public key to those services you wish to authenticate.

If you need more details on using SSH keys, take a look at the Ubuntu community documentation, and if you get stuck, help is always at hand:

  • Ask Ubuntu
  • Ubuntu Forums
  • IRC-based support

Was this tutorial useful?

Thank you for your feedback.


Like this post? Please share to your friends:
  • Как сгенерировать ssh keys для git windows
  • Как сгенерировать csr запрос в windows
  • Как связаться с системным администратором windows 10
  • Как связаться с windows по телефону
  • Как связать устройство android с windows 10