Windows ssh key invalid format

SSH Внезапно возвращается неверный формат

Некоторое время назад я настроил сервер на AWS и использовал их сгенерированный ключ SSH. Я сохранил ключ в Lastpass и успешно извлек его оттуда, и он заработал. Однако, попробовав сегодня снова, я не могу заставить его работать.

-rw——- 1 itsgreg users 1674 Jun 6 12:51 key_name

Я пробовал ssh -i key_name , ssh-keygen -f key_name но ничего не работает, я всегда получаю это сообщение об ошибке:

Load key «key_name»: invalid format

Есть ли способ это исправить?

Проверьте содержимое key_name , если агент говорит invalid format , что с ключом что-то не так — как . Вы уверены, что это правильный ключ? Даже если вам нужен не секретный ключ, агент ssh не вернется, invalid format если ключ работает, вы просто не сможете подключиться. Возможно, вы по какой-то причине поместили туда свой открытый ключ. Проверь это!

Что я сделал, чтобы исправить эту проблему, так это то, что я использую для преобразования PPK-файл, используя PuttyGen .

Сначала загрузите urkey.PPK , затем в меню конвертации выберите экспорт в формат файла Openssh. Это создаст файл newkey.

в настоящее время, ssh -i «newkey» user@127.0.0.1

Выполнено. Надеюсь, это поможет.

Я просил openssh использовать определенный файл идентификации, указав его в файле .ssh / config.

Исходная рабочая конфигурация имела

Это перестало работать без каких-либо изменений. Немного подумав, я заменил «путь к файлу открытого ключа» выше на «путь к файлу закрытого ключа». Это сработало. Причина заключается в том, что файлы открытого и закрытого ключей имеют большие числа, связанные с преступным преступлением, согласно алгоритму RSA. Если вы замените файл закрытого ключа файлом открытого ключа, эти криптографические числа не будут правильно извлечены из блока base64, сохраненного в файлах ключей. Кажется, некоторые версии ssh могут определить расширение .pub и использовать его для определения правильного файла закрытого ключа — а другие версии этого не делают. Это еще один способ, которым эта ошибка может произойти. Надеюсь, это кому-нибудь поможет.

У меня была та же проблема, и оказалось, что у меня в файле по какой-то причине были разделители строк в стиле Windows (CRLF).

Кроме того, файл должен заканчиваться одним LF.

Починить эти сделанные вещи снова.

Вы должны преобразовать ваш ключ .ppk в ключ OpenSSH

Вот как вы это делаете :

  1. Загрузите PuttyGen и создайте свою пару ключей (если у вас нет готовой пары ключей). Сохраните закрытый ключ в вашу папку (.ppk)
  2. Если у вас уже есть закрытый ключ, загрузите файл закрытого ключа (.ppk), нажав кнопку «Загрузить». В противном случае пропустите этот шаг
  3. В меню «Конверсии» выберите «Экспортировать ключ OpenSSH» и сохраните его в своей папке.
  4. Теперь вы готовы использовать ключ для входа на сервер без ввода пароля (я предполагаю, что вы уже поместили открытый ключ в /root/.ssh/authorized_keys, chmod 600 /root/.ssh/authorized_keys и перезапущенный демон SSH)
Читайте также:  How to install php linux

Я только что столкнулся с этим сегодня, когда писал несколько утилит git tagging для моего конвейера CI.

Вот разница между моими двумя ключами:

Я изменил свой код так:

И теперь мой ключ ssh работает.

TL; DR — Я думаю, у вас должен быть символ новой строки в конце вашего закрытого ключа.

Win10 OpenSssh: ssh-add gives err “invalid format” for key file

On windows 10, the ssh-add commant is giving the following error: Could not add identity «C:\users\ \.ssh\id_rsa_win»: invalid format

I generated the key like this: ssh-keygen -t rsa -N ‘my pass phrase’ -C ‘generated by windows openssh’ -f C:\Users\ \.ssh\id_rsa_win

1 Answer 1

Are you running ssh-keygen and ssh-add from an elevated prompt? Please try that. Just type Powershell on the Start Menu, right click on top of it and Run as Administrator . Try generating a key from there and adding it again. That can be the issue.

Some commands to test as well:

Other than that, found this thread where the user magically solved the issue and was unsure if it was whether a restart or an update that solved it. So worst case scenario, maybe try updating your OpenSSH version. You can find the latest versions here

Not the answer you’re looking for? Browse other questions tagged windows-10 openssh or ask your own question.

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.4.16.39093

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Error loading key “/root/.ssh/id_rsa”: invalid format

I am building a CI/CD for my django project using GitLab. As part of my deploy stage, I have

The build breaks down at ssh-add

/.ssh/id_rsa with the error message Error loading key «/root/.ssh/id_rsa»: invalid format .

I have checked people with questions with similar error messages and none seem related to what I am doing.

Notes

  1. I am trying to deploy to amazon ec2
  2. I am following this tutorial https://testdriven.io/blog/deploying-django-to-ec2-with-docker-and-gitlab/ and everything seems to work fine up until this last point.

2 Answers 2

I faced such issue, the error was «Error loading key «/root/.ssh/id_rsa»: invalid format» It was due to protected variable, that only applied on protected branch. I mean to say if you use protected variable on unprotected branch it will not recognize the variable thus failed to recognize it.

I managed to fix it with the help of guys from the ##aws irc channel

The Problem

I generated a PKCS#1 key format instead of a PKCS#8 format. The PKCS#1 is represented as:

Читайте также:  Взлом пароля wifi mac os

The PKCS#8 is represented as:

Solution

I simply copied the PRIVATE KEY and converted it here https://decoder.link/rsa_converter

Edited As indicated below, it is not a good idea to use websites to do the conversion. Especially when your private key is likely being sent to their servers. Instead, do the conversion locally as indicated here by @csgeek

ssh: Error loading key “./id_rsa”: invalid format

For some reason one of my ssh keys «just broke» — it just stopped working:

Copying the key inside a clean VM, the key does work. Even with the exact same ssh version (OpenSSH_7.8p1, OpenSSL 1.1.0i-fips 14 Aug 2018 on Fedora 28). So it must be related to some config on my system I assume.

Also peculiar: GNOME somehow manages to add the key on login with seahorse. Then ssh-add -L does list the key but it is not usable:

6 Answers 6

Traditionally OpenSSH used the same private key format is identical to the older PEM format used by OpenSSL. (Because it uses OpenSSL for parsing the key, it will accept the newer PKCS#8 format as well.)

So the issue can be one of:

Your OpenSSL version refuses to load this key format. Perhaps it has accidentally enabled FIPS mode and refuses any algorithms except those part of its original FIPS validation?

Try loading the key into the openssl command-line tool (which, yes, might also be linked to a different libcrypto, and you should check with ldd):

Try converting it to PKCS#8 format:

Your OpenSSH has been built without OpenSSL support. Even though ssh -V says the support was enabled, that does not automatically mean the ssh-add binary is the same – it might come from a different partial installation.

Use type -a ssh and type -a ssh-add to compare installation locations.

Once you know the path, use ldd /usr/bin/ssh-add to verify that it’s linked to libcrypto.so (the OpenSSL cryptographic library).

If nothing works at all, try converting your key to the new OpenSSH-proprietary format using. PuTTY. Install the putty package for Fedora, and use:

Also peculiar: GNOME somehow manages to add the key on login with seahorse.

Older GNOME Keyring versions have an internal copy of the SSH agent code and are independent from the system OpenSSH. So they will accept keys that your OpenSSH won’t. (But on the other hand, this means severe lagging in terms of feature support (such as Ed25519 keys), and the latest GNOME Keyring just uses the system ssh-agent instead.)

key_load_public: invalid format

I used PuTTY Key Generator to generate a 4096 bit RSA-2 key with a passphrase.

I save the .ppk and an openSSL format public key. The putty format public key doesn’t work.

In any case, my error is as follows:

What’s the issue?

I use Pageant to load the keys and i use Git Bash to try the ssh connection. I’ve also loaded the key into GitHub, not sure what i’m doing wrong.

Читайте также:  Как ставить usb windows

I’ve tried adding a new line and not adding a new line in GitHub

/.ssh/known_hosts is bad — ssh is looking for github’s public key. You can run ‘file key’ to find out key file’s format. – mosh Nov 17 ’17 at 14:40

12 Answers 12

As Roland mentioned in their answer, it’s a warning that the ssh-agent doesn’t understand the format of the public key and even then, the public key will not be used locally.

However, I can also elaborate and answer why the warning is there. It simply boils down to the fact that the PuTTY Key Generator generates two different public key formats depending on what you do in the program.

Note: Throughout my explanation, the key files I will be using/generating will be named id_rsa with their appropriate extensions. Furthermore, for copy-paste convenience, the parent folder of the keys will be assumed to be

/.ssh/ . Adjust these details to suit your needs as desired.

The Formats

When you save a key using the PuTTY Key Generator using the «Save public key» button, it will be saved in the format defined by RFC 4716.

OpenSSH

Contrary to popular belief, this format doesn’t get saved by the generator. However it is generated and shown in the text box titled «Public key for pasting into OpenSSH authorized_keys file». To save it as a file, you have to manually copy it from the text box and paste it into a new text file.

For the key shown above, this would be:

The format of the key is simply ssh-rsa and can be created by rearranging the SSH-2 formatted file.

Regenerating Public Keys

If you are making use of ssh-agent , you will likely also have access to ssh-keygen .

If you have your OpenSSH Private Key ( id_rsa file), you can generate the OpenSSH Public Key File using:

If you only have the PUTTY Private Key ( id_rsa.ppk file), you will need to convert it first.

  1. Open the PuTTY Key Generator
  2. On the menu bar, click «File» > «Load private key»
  3. Select your id_rsa.ppk file
  4. On the menu bar, click «Conversions» > «Export OpenSSH key»
  5. Save the file as id_rsa (without an extension)

Now that you have an OpenSSH Private Key, you can use the ssh-keygen tool as above to perform manipulations on the key.

Bonus: The PKCS#1 PEM-encoded Public Key Format

To be honest, I don’t know what this key is used for as I haven’t needed it. But I have it in my notes I’ve collated over the years and I’ll include it here for wholesome goodness. The file will look like this:

This file can be generated using an OpenSSH Private Key (as generated in «Regenerating Public Keys» above) using:

Alternatively, you can use an OpenSSH Public Key using:

Оцените статью