How to create ssh key windows

  • Главная

  • Инструкции

  • Windows

  • Как сгенерировать SSH-ключ для Windows: пошаговая инструкция

SSH — это сетевой протокол прикладного уровня, необходимый для обеспечения безопасного подключения, а после и управления операционной системой. Через него можно удаленно выполнять команды в терминале компьютера. Создать удаленное подключение к серверу через SSH можно с помощью паролей или SSH-ключей. В данной статье мы рассмотрим, как создать ключи в операционной системе Windows.

SSH-ключ в Windows — это один из способов безопасного подключения к удаленному серверу. Преимущество данного метода подключения — это отсутствие возможности взлома, как это происходит с паролем.

Для подключения создаются два SSH-ключа:

  • Публичный ключ, хранящийся на сервере в определенном каталоге. Это комбинация символов, которая шифрует данные при обращении к серверу.
  • Приватный — зашифрованный ключ, который располагается на компьютере клиента. Он отвечает за расшифровку полученных данных. При его генерации можно добавить пароль для дополнительной защиты.

Для корректной и полной работы SSHключей необходимо будет отключить аутентификацию по паролю.

После создания SSH-ключей в Windows и из сохранении на сервер, при подключении к серверу будет происходить их проверка. Если публичный ключ соответствует приватному, то подключение выполнится.

Существует два варианта генерации SSH-ключей в Windows. Первый — использование OpenSSH клиента, второй — использование клиента PuTTY. Ниже опишем инструкции по созданию ключей, используя и первый, и второй вариант. В качестве операционной системы будет использоваться Windows 10.

OpenSSH клиент

  1. Для начала нужно проверить установлен ли OpenSSH клиент на Windows 10. Для этого зайдем в «Параметры», а после перейдем во вкладку «Приложения». Далее нажимаем на ссылку «Дополнительные компоненты», как показано на картинке ниже.

Image1

В открывшемся окне в строку поиска вводим «Клиент OpenSSH». Если в списке он будет найден, то можно сразу приступать к генерации ключей. Если же он отсутствует, то нужно нажать на кнопку «Добавить компонент», а после найти его и выбрать среди всех доступных, используя строку поиска. Далее останется нажать кнопку «Установить» снизу слева и можно переходить ко второму шагу.

  1. Теперь нужно открыть командную строку. Для этого открываем диалоговое окно «Выполнить» (комбинация клавиш Win+R), вводим в строку cmd и нажимаем кнопку «ОК».

Image3

  1. В открывшемся окне вводим команду:
ssh-keygen

После этого запустится процесс генерации. 

В первую очередь пользователю будет предложено ввести путь к папке, в которой будут храниться ключи. Чтобы оставить вариант по умолчанию (.../.ssh/id_rsa), предложенный системой, нужно нажать клавишу «Enter».

Далее пользователю будет предложено ввести ключевое слово к ключу. Чтобы пропустить этот шаг, нажмите также клавишу «Enter» 2 раза.

  1. Проверим, что все ключи успешно сгенерированы. Для этого переходим в соответствующий каталог на своем компьютере. У нас это /.ssh/id_rsa, так как мы оставили все по умолчанию. 

Image2

Как видно по картинке выше, ключи сгенерированы успешно.

Переходим к варианту их создания с помощью клиента PuTTY.

PuTTY

Клиент PuTTY был популярным, когда OpenSSH отсутствовал в Windows. Но и сейчас его не перестают использовать. Он находится в свободном доступе на официальном сайте разработчика. Рассмотрим ниже подробную инструкцию по генерации SSH-ключей на Windows 10 в PuTTY.

  1. Для начала необходимо скачать архив клиента PuTTY с официального сайта.
  2. После его нужно будет разархивировать и запустить файл puttygen.exe от имени администратора.
  3. В открывшемся окне выбираем классический и повсеместно использующийся тип ключа для генерации — RSA. Длину оставляем 2048 бит и нажимаем кнопку «Генерировать».

Image5

  1. Во время генерации нужно водить курсором по серой области внутри окна до заполнения зеленой полоски. Это позволит улучшить защищенность генерируемого ключа, благодаря созданию псевдослучайности.
  2. После успешной генерации нужно сохранить публичный и приватный ключ на компьютере. Для этого создадим папку на диске.

Image4

Ключи успешно созданы и сохранены на локальной машине. На этом этапе их генерация закончена.

Заключение

В данной инструкции были рассмотрены два варианта создания SSH-ключей в Windows. Для подключения к серверу нужно скопировать в него созданный публичный ключ. При попытке соединиться с сервером будет происходить проверка публичного ключа на стороне сервера с приватным на стороне клиента. Если вы пользуетесь облачными серверами Timeweb Cloud, то можете добавить сгенерированный публичный ключ в разделе «SSH-ключи» в панели управления. 

SSH is a secure network protocol that allows you to connect to your windows and send commands to it. Using an SSH key, you can securely connect to servers in other countries. Users can control their servers remotely, send commands, and run applications as if they were physically in front of the server. This feature makes it an essential tool for system administrators and programmers.

What is an SSH Key?

This can be defined as an authentication tool for verifying the identity of hosts and users. Windows use a password-based connection when connecting to servers via SSH. The latter is considered more secure. By eliminating the need to store passwords in files, security is improved. This makes accessing a user’s password impossible for a hacked server.

The SSH key method creates a secure connection between devices by using public and private keys generated using cryptography. To establish a secure connection, both keys are needed. The private key is stored in a remote machine, while the public key is stored on the user’s device. While using an SSH key, ensure you have a reliable Windows VPS.

Why Do I Need an SSH Key?

Your PC is vulnerable to external and malevolent attacks when working between different domains and cloud-hosted systems. Using this tool is tantamount to securing a safe access and connection to servers. Each user is given a unique set of SSH keys. These keys are saved on the user’s device. SSH hosting can be made easier by utilizing Ultahost’s VPS service.

How To Create SSH Keys in Windows

  Generating SSH on Windows involves 4 easy-to-follow steps which are:

  1. Launch Windows command prompt by hitting the Windows key and typing “cmd.”
  2. Then type ssh-keygen and press enter.
  3. After step 2, you will be asked to give your key a name and save it in a specific location. If you use the defaults, your keys will be saved as C:\User[YourUserName].ssh — in the C-drive, where your user account is stored.
  4. Afterward, you will be asked to provide a passphrase. This is an important security measure that will keep your key secure. We strongly recommend that you follow through with this step. If not, just click enter.

 Your keys have been successfully generated, securely saved, and ready for immediate use. When you look in your “.ssh” folder, you will see two files: “id_rsa” (with no file extension) and “id_rsa.pub.” The first file is the private key that should be kept to yourself, while the second (public key) is the key you use to authenticate when uploading to servers.

How To Use

Following key generation, the server must be properly configured to grant users login access. Four simple steps are required for configuration:

  • Navigate to the “.ssh” folder where you stored your keys.
  • Open the public key file with a text editor and copy the contents to your clipboard.
  • Connect to your Windows coreOS by using Device Portal.
  •  Go to the SSH tab in the left pane and paste the contents you copied into a” Public Key” box. 

After configuration,To complete the process, you just need to connect your Factory OS device. This can be done in three stages:

  • Open a command prompt window on your PC
  • Enter this command: ssh -i C:\Users\User/.ssh/id_rsa [email protected]. Where  C:\Users\User/.ssh/id_rsa is your private key, user is the username you chose when setting up, 192.168.1.2 is your factory OS device IP address.
  • Enter the password for your user if you configured your key to require a password.

Congratulations! You have completed the task and the server is now accessible. Begin your VPS hosting today with Ultahost.

Conclusion

SSH keys add an extra layer of security when connecting to servers. They are easy to create and use. Give it a try.

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\.ssh\id_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

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

  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.

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.

    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.

  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 public key to your account on GitHub. For more information, see «Adding a new SSH key to your GitHub account.»

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:\Users\your_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:\Users\your_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.

  • How to download windows store on windows 10
  • How to create popup windows
  • How to disable updates windows 10
  • How to check windows build
  • How to create file in windows terminal