Error loading key stdin error in libcrypto

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 […]

Содержание

  1. ssh: Error loading key «./id_rsa»: invalid format
  2. 8 Answers 8
  3. gitlab-ci SSH key invalid format
  4. Questions : gitlab-ci SSH key invalid format
  5. Answers 1 : of gitlab-ci SSH key invalid format
  6. Answers 2 : of gitlab-ci SSH key invalid format
  7. Answers 3 : of gitlab-ci SSH key invalid format
  8. Answers 4 : of gitlab-ci SSH key invalid format
  9. Answers 5 : of gitlab-ci SSH key invalid format
  10. Answers 6 : of gitlab-ci SSH key invalid format
  11. Answers 7 : of gitlab-ci SSH key invalid format
  12. Answers 8 : of gitlab-ci SSH key invalid format
  13. Answers 9 : of gitlab-ci SSH key invalid format
  14. Answers 10 : of gitlab-ci SSH key invalid format
  15. Answers 11 : of gitlab-ci SSH key invalid format
  16. Answers 12 : of gitlab-ci SSH key invalid format
  17. Answers 13 : of gitlab-ci SSH key invalid format
  18. Answers 14 : of gitlab-ci SSH key invalid format
  19. SSH Key Format Issues and Fixing the “invalid format” Error
  20. 1. Introduction
  21. 2. Generate Key Pair
  22. 3. Authorizing the Correct Key
  23. 3.1. ssh-copy-id
  24. 3.2. Manual Key Authorization Problems
  25. 4. Using the Correct Key
  26. 5. Handling Keys Properly
  27. 5.1. Key Naming
  28. 5.2. Key Transfer and Streaming
  29. 6. Summary
  30. ssh: ошибка загрузки ключа»./ id rsa»: неверный формат
  31. 1 ответов
  32. SSH Внезапно возвращается неверный формат

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:

8 Answers 8

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

Источник

gitlab-ci SSH key invalid format

Questions : gitlab-ci SSH key invalid format

I would like run deploy script with gitlab-ci, but step ssh-add $SSH_PRIVATE_KEY return an error :

You can see my .gitlab-ci.yml :

On my project setting, i’ve been add SSH_PRIVATE_KEY variable, with the id_rsa from my production server cat

Anyone can help me ?

Answers 1 : of gitlab-ci SSH key invalid format

In my case, it was because I had made my SSH_PRIVATE_KEY variable protected. When I disabled the Protected state, it worked without any error.

Answers 2 : of gitlab-ci SSH key invalid format

In my case I had to put a new line at the end of the SSH_PRIVATE_KEY variable

Answers 3 : of gitlab-ci SSH key invalid format

I made a stupid mistake and added the key without ——BEGIN RSA PRIVATE KEY—— and ——END RSA PRIVATE KEY—— clauses.

Summing up, you should add:

Also, ensure the newline after the closing is present.

Answers 4 : of gitlab-ci SSH key invalid format

It works with variable expansion (curly brackets in double string quotation):

While keeping the SSH_PRIVATE_KEY variable protected!

This approach is simply a less ambiguous method for printing variables; in this case it prevents trimming of the last line break.

Answers 5 : of gitlab-ci SSH key invalid format

It is the SSH public key in

/.ssh/id_rsa.pub by default.

The private key is contained in

Answers 6 : of gitlab-ci SSH key invalid format

If you export key from PuTTYgen, to get key content use its command Conversations — Export OpenSSH key (force new file format)

And trim last spaces and add new line.

Answers 7 : of gitlab-ci SSH key invalid format

You must copy the entire contents of the file(id_rsa), including the final blank line. I solve the problem this way.

Answers 8 : of gitlab-ci SSH key invalid format

Make sure that the newline after the end of the file variable is present. If not, the following error would have appeared:

The ID_RSA was my file variable in this example.

Answers 9 : of gitlab-ci SSH key invalid format

I got it working with a protected variable.

If the variable is file, echo won’t work anymore:

Otherwise; if variable is NOT file, use the following:

Answers 10 : of gitlab-ci SSH key invalid format

for all people reaching this post not finding a solution yet.

Try to make the branch protected, because its a must for protected variables.

Protected: Only exposed to protected branches or protected tags.

Add a CI/CD variable to a project

Answers 11 : of gitlab-ci SSH key invalid format

In my case, it was because I had made my SSH_PRIVATE_KEY variable available in a specific enviroment. I changed it to the one I was using (or you can change it to All, depending on your setup).

Answers 12 : of gitlab-ci SSH key invalid format

I had this issue on gitlab and bitbucket, both were solved adding a n by the end of the key file.

Answers 13 : of gitlab-ci SSH key invalid format

it possible you didn’t copy the content of the public key to the authorized_keys

Answers 14 : of gitlab-ci SSH key invalid format

I had the same problem and after spending some hours trying to understand what was wrong I found that my private key was encrypted (and my computer had the password in cache for so long that I had forgotten that it was encrypted). It’s not so easy to understand if it’s encrypted or not by just looking at the key. You should decrypt the key (set an empty password) and then paste it on a GitLab variable. Then in your .gitlab-ci.yml you can have a similar configuration:

*** Note that if you don’t want to write the key in a file, you can just put it inside the ssh agent with:

*** Note 2: In the Gitlab panel, make sure you have created a variable (and not a file); normally, it should be protected if you want to make it visible in the main branch.

*** Important: For security reasons change the following line:

putting only your host/s (and don’t permit all connections like this). If you put:

when connecting to any host, the ssh-agent will not check the signature and this can be a big vulnerability!

Источник

SSH Key Format Issues and Fixing the “invalid format” Error

Last modified: November 30, 2022

1. Introduction

Due to the widespread use of asymmetric cryptography, end users can employ and leverage it more easily. Still, even the ubiquitous Secure Shell (SSH) algorithm isn’t resistant to user mistakes.

In this tutorial, we talk about issues with the format of keys when establishing an SSH session. First, we generate a sample key pair. Next, we discuss key authorization and the pitfalls around it. After that, we consider reasons for supplying an incorrect identity by mistake when authenticating. Finally, we discuss proper handling to avoid key format issues.

For brevity and security reasons, we only consider the newest iteration of SSH version 2 (SSHv2) implemented by OpenSSH.

We tested the code in this tutorial on Debian 11 (Bullseye) with GNU Bash 5.1.4. It should work in most POSIX-compliant environments.

2. Generate Key Pair

Notably, we use a non-standard path instead of the usual $HOME/.ssh.

At this point, we have one example set of two keys:

  • private key: /non-standard/id_rsa
  • public key: /non-standard/id_rsa.pub

Critically, we require the correct permissions for each key:

Following chmod for restricting access to our keys, let’s output them with cat:

After generating a pair, we can explore potential format issues with the use of our new keys for public key authentication.

Usually, we add the public key to the authorized_keys file for our user with a dedicated tool or directly.

3.1. ssh-copy-id

Let’s see how to authorize a key with ssh-copy-id:

Due to our non-standard path outside $HOME/.ssh, ssh-copy-id can’t automatically locate the local keys. Hence, we use the -i argument to specify /non-standard/id_rsa as we did during generation:

Here, ssh-copy-id appends the .pub suffix automatically. Further, when our keys are in their standard location, ssh-copy-id uses the public key (id_rsa.pub) by default.

These mechanisms prevent mistakes when authorizing the key.

3.2. Manual Key Authorization Problems

Unlike ssh-copy-id, the cat command doesn’t perform any checks:

In this case, it might not be easy to spot the problem: supplying /non-standard/id_rsa doesn’t self-rectify to /non-standard/id_rsa.pub, meaning we incorrectly place our private key in the authorized_keys file, resulting in several problems:

  • the format of authorized_keys is now invalid, so public key authentication seizes to work for our user
  • our private key is exposed in a public file
  • the key isn’t authorized

Because of these potential security holes, it’s highly recommended to use ssh-copy-id and the default SSH key paths.

4. Using the Correct Key

Another common problem with public key authentication is the identity file we supply during session setup.

In particular, we might mix up the private and public keys:

If we supply the public instead of the private key as the identity during session establishment, our SSH client tells us that the format is invalid. Of course, the same would happen for any file that’s not a private key in the proper format:

Depending on the key pair naming scheme, this error might not be very helpful. Also, we can experience issues even with the proper key file if we tamper with the format.

5. Handling Keys Properly

Of course, mishandling sensitive and strictly structured data such as SSH keys can lead to security issues.

5.1. Key Naming

The default names of public and private keys depend on the exact key type. For example, when using RSA, the defaults are id_rsa and id_rsa.pub, respectively.

In most cases, the public key has the name of the private key but with a .pub extension. In fact, the .pub suffix can be critical for the correct key detection and use. Moreover, preserving the proper naming scheme can be vital in general.

This is especially important when transferring key data.

5.2. Key Transfer and Streaming

When relocating key content, any formatting must be preserved along with the data. In other words, no changes to the key contents are allowed apart from the public key comments.

While the public key is usually a single line, private keys are longer and spread across multiple lines, so they are more prone to issues:

After confirming the current format of our private key with cat, we use the same command in a subshell to assign that to a variable. At this point, we lose the newlines since we don’t use quotes around $(). Thus, the $prk variable contains an incorrect value, which we transfer to /non-standard/id_rsa_bad.

Finally, using that key as an identity results in an invalid format error. Naturally, any other reason for bad formatting will result in the same.

6. Summary

In this article, we looked at common causes for malformed SSH keys, as well as their consequences.

In conclusion, although we can generate and use key pairs fairly easily, there are ways to do it incorrectly and methods to avoid such mistakes.

If you have a few years of experience in the Linux ecosystem, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Источник

ssh: ошибка загрузки ключа»./ id rsa»: неверный формат

Почему-то один из моих ssh ключей «просто сломался» — он просто перестал работать:

копировать ключ внутри чистый ВМ, ключ работает. Даже с точно такой же версией ssh (OpenSSH_7.8p1, OpenSSL 1.1.0 i-fips 14 Aug 2018 в Fedora 28). Поэтому оно должно быть связано с некоторым config на моей системе я предполагаю.

также своеобразно: GNOME каким-то образом умудряется добавлять ключ на логин с seahorse. Тогда ssh-add -L перечислены ключ, но это не используется:

1 ответов

традиционно OpenSSH использовал тот же формат закрытого ключа, что и более старый формат PEM, используемый OpenSSL. (Поскольку он использует OpenSSL для разбора ключа, он также принимает новый формат PKCS#8.)

так что вопрос может быть один из:

ваша версия OpenSSL не загружает этот формат ключа. Возможно, он случайно включил режим FIPS и отказывается от любых алгоритмов, кроме тех, которые являются частью его первоначальной проверки FIPS?

попробуйте загрузить ключ в openssl инструмент командной строки (который, Да, также может быть связан с другим libcrypto, и вы должны проверить с ldd):

попробуйте преобразовать его в формат PKCS#8:

ваш OpenSSH был построен без поддержки OpenSSL. Хотя бы ssh -V говорит, что поддержка была включена, что не означает the ssh-add двоичный то же самое – это может произойти из другой частичной установки.

использовать type -a ssh и type -a ssh-add для сравнения мест установки.

как только вы знаете путь, используйте ldd /usr/bin/ssh-add чтобы убедиться, что он связан с libcrypto.so (криптографическая библиотека OpenSSL).

если ничего не работает, попробуйте преобразовать ключ в новый формат OpenSSH. замазка. Установите putty пакет для Fedora, и использование:

также своеобразно: GNOME каким-то образом умудряется добавлять ключ на логин с seahorse.

более старые версии Gnome Keyring имеют внутреннюю копию кода агента SSH и независимы от системы OpenSSH. Таким образом, они будут принимать ключи, которые ваш OpenSSH не будет. (Но, с другой стороны, это означает серьезное отставание с точки зрения поддержки функций (таких как ключи Ed25519), а последний Gnome Keyring просто использует систему вместо этого ssh-агент.)

Источник

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)

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

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

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

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

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

Источник

According to the docs at
https://docs.gitlab.com/ee/ci/ssh_keys/

I can add a private ssh key as CI Variable and add it for my pipeline with

- eval $(ssh-agent -s)
- echo "$SSH_PRIVATE_KEY" | tr -d 'r' | ssh-add -

However, I get an error

Error loading key «(stdin)»: incomplete message

I used following command to generate the key pair:

ssh-keygen -t rsa -b 2048

and tried several things to resolve the issue:

a) With and without blank line at the end of the variable
b) Change type of variable to file
c) Change the way the key is generated (different -t and -b options)
d) First write to file and then add from file
e) Change encoding
f) Edit /etc/ssh/ssh_config and add the lines

HostKeyAlgorithms +ssh-rsa
PubkeyAcceptedKeyTypes +ssh-rsa 

=> Could not solve the issue until now.

Related question:

Error loading key «(stdin)»: invalid format Gitlab CI

Some alternative commands that did not work:

echo "$SSH_PRIVATE_KEY" | tr -d 'r' | ssh-add - > /dev/null

echo "$SSH_PRIVATE_KEY" | base64 -d | ssh-add -

Another error message that I got while trying:

Error loading key «(stdin)»: error in libcrypto

Edit

As a workaround, instead of adding the private key as CI variable, I use a shell executor and manually logged in on the gitlab runner host, changed user to «gitlab-runner» and established an ssh connection. My corresponding CI Job looks like this (you need to replace remote-server.de and user@remote-server.de):

job_back_end_deploy:
  stage: deploy
  #variables:
  #  CI_DEBUG_TRACE: "true"  # uncomment this to get more detailed console output
  before_script:
  # In order for this to work, an SSH connection already needs to be manually prepared
  # between the user "gitlab-runner" on the host of the gitlab-runner and on the target server
  # you would like to connect to
  # Also see https://docs.gitlab.com/ee/ci/ssh_keys/#ssh-keys-when-using-the-shell-executor
  # -------------------------------------
  ## change to user "gitlab-runner"
  # su - gitlab-runner
  ## generate ssh key-pair
  # ssh-keygen -t rsa -b 2048
  ## copy public key to the remote server you would like to connect to (asks for password)
  # ssh-copy-id -p 222 -i /home/gitlab-runner/.ssh/id_rsa.pub user@remote-server.de
  # -----------------------------  
  #
  # verify SSH host keys, also see
  # https://docs.gitlab.com/ee/ci/ssh_keys/#verifying-the-ssh-host-keys
  - ssh-keyscan 'remote-server.de' >> ~/.ssh/known_hosts
  script:    
  - echo 'Copying files to remote server...'
  - scp -P 222 -r ./back_end/ user@remote-server.de:./public_html/back_end/   # add -v option to see more output if you want
  tags:
    - visualization 

Содержание

  1. ssh: ошибка загрузки ключа»./ id rsa»: неверный формат
  2. 1 ответов
  3. Deployment key mapping: Key comments not written for some key types/formats? #93
  4. Comments
  5. pmeth commented Aug 25, 2021
  6. cosminionut1996 commented Aug 27, 2021 •
  7. mpdude commented Aug 27, 2021
  8. mpdude commented Aug 27, 2021
  9. pmeth commented Aug 27, 2021
  10. SSH Внезапно возвращается неверный формат
  11. GITLAB CI Ошибка загрузки ключа «/ dev / fd / 63»: неверный формат ОШИБКА: сбой задания: код выхода 1
  12. [Solved] SSH-Connection / Load key — invalid format #671
  13. Comments
  14. torstenzenk commented Jul 14, 2020 •

ssh: ошибка загрузки ключа»./ id rsa»: неверный формат

Почему-то один из моих ssh ключей «просто сломался» — он просто перестал работать:

копировать ключ внутри чистый ВМ, ключ работает. Даже с точно такой же версией ssh (OpenSSH_7.8p1, OpenSSL 1.1.0 i-fips 14 Aug 2018 в Fedora 28). Поэтому оно должно быть связано с некоторым config на моей системе я предполагаю.

также своеобразно: GNOME каким-то образом умудряется добавлять ключ на логин с seahorse. Тогда ssh-add -L перечислены ключ, но это не используется:

1 ответов

традиционно OpenSSH использовал тот же формат закрытого ключа, что и более старый формат PEM, используемый OpenSSL. (Поскольку он использует OpenSSL для разбора ключа, он также принимает новый формат PKCS#8.)

так что вопрос может быть один из:

ваша версия OpenSSL не загружает этот формат ключа. Возможно, он случайно включил режим FIPS и отказывается от любых алгоритмов, кроме тех, которые являются частью его первоначальной проверки FIPS?

попробуйте загрузить ключ в openssl инструмент командной строки (который, Да, также может быть связан с другим libcrypto, и вы должны проверить с ldd):

попробуйте преобразовать его в формат PKCS#8:

ваш OpenSSH был построен без поддержки OpenSSL. Хотя бы ssh -V говорит, что поддержка была включена, что не означает the ssh-add двоичный то же самое – это может произойти из другой частичной установки.

использовать type -a ssh и type -a ssh-add для сравнения мест установки.

как только вы знаете путь, используйте ldd /usr/bin/ssh-add чтобы убедиться, что он связан с libcrypto.so (криптографическая библиотека OpenSSL).

если ничего не работает, попробуйте преобразовать ключ в новый формат OpenSSH. замазка. Установите putty пакет для Fedora, и использование:

также своеобразно: GNOME каким-то образом умудряется добавлять ключ на логин с seahorse.

более старые версии Gnome Keyring имеют внутреннюю копию кода агента SSH и независимы от системы OpenSSH. Таким образом, они будут принимать ключи, которые ваш OpenSSH не будет. (Но, с другой стороны, это означает серьезное отставание с точки зрения поддержки функций (таких как ключи Ed25519), а последний Gnome Keyring просто использует систему вместо этого ssh-агент.)

Источник

I tried this action and in the output for the adding ssh-agent step, I see the following message for each key i added:

My comments are in the format git@github.com:Myorg/myrepo.git . I tried it with and without quotes.

Why doesn’t it work?

The text was updated successfully, but these errors were encountered:

Similar issue here. I’m using the same format for the comment, the command is something like ssh-keygen -C «git@github.com:org/repo.git» .
Not sure what’s going on and can’t find alternatives.

I am also not sure where this is coming from, but others reported similar issues before… the key comment seems to be (stdin) (sic!) only.

Can you load your keys into a ssh-agent running locally and then list keys with ssh-add -l ? Does that show the same comment?

With which command did you create keys, and which tool/platform/SSH implementation did you use?

#76 and #88 are similar, but were closed before we could find the root issue and/or document what to watch out for.

the command i used was

ssh-add -l does not show the comment, but should it? the comment is on the public key. i wasn’t aware that private keys could have comments.

By the way, I was following another similar issue, where the poster said he switched from a PEM to an openssh key which got him further, so I tried to convert the PEM key to OpenSSH and it seemed to work

I had tried it previously but it didn’t authenticate, but I think that might have been because I forgot to update the pub key after switching to OpenSSH. With GitHub this is several steps to test different options and very easy to make a mistake 🙁

So maybe this problem can be solved by updating the documentation and removing the PEM mention and switch to OpenSSH?

Источник

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)

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

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

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

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

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

Источник

GITLAB CI Ошибка загрузки ключа «/ dev / fd / 63»: неверный формат ОШИБКА: сбой задания: код выхода 1

Вот мой код giltlab-ci.yml:

Running with gitlab-runner 11.8.0 (4745a6f3) on Allence-Tunisie-docker-runner sH47eTgb Using Docker executor with image ntfactory/ci-tool:0.0.2 . Pulling docker image ntfactory/ci-tool:0.0.2 . Using docker image sha256:7fe7b170806f6846271eec23b41c4f79202777f62c0d7a32165dc41722900979 for ntfactory/ci-tool:0.0.2 . Running on runner-sH47eTgb-project-11060727-concurrent-0 via a732493b4b94. Cloning repository. Cloning into ‘/builds/allence-tunisie/e-formation’. Checking out 0a6b48ef as feat/gitlab-ci. Skipping Git submodules setup Checking cache for default. No URL provided, cache will not be downloaded from shared cache server. Instead a local version of cache will be extracted. Successfully extracted cache $ which ssh-agent || ( apt-get update -y && apt-get install openssh-client -y ) /usr/bin/ssh-agent $ eval $(ssh-agent -s) Agent pid 12 $ mkdir -p

/.ssh $ echo «$SSH_PRIVATE_KEY» | tr -d ‘r’ | ssh-add — > /dev/null Error loading key «(stdin)»: invalid format ERROR: Job failed: exit code 1

хотя я пробовал — эхо «$ SSH_PRIVATE_KEY» | tr -d ‘ r’ | ssh-add -> / dev / null я получаю эту ошибку

Error loading key «(stdin)»: invalid format

Эта ошибка возникает, когда закрытый ключ в $ SSH_PRIVATE_KEY имеет неправильный формат, вы можете легко протестировать его локально, если добавите в него несколько случайных символов. В частности, это происходит в Travis-CI, когда вы просто копируете и вставляете закрытый ключ в переменную SSH_PRIVATE_KEY в онлайн-форме. Это связано с символами новой строки после и перед блоками —— BEGIN RSA PRIVATE KEY ——, —— END RSA PRIVATE KEY ——. По этой причине я использую кодировку base64, чтобы убедиться, что ключ отформатирован правильно.

Закодируйте свой закрытый ключ RSA

кот my_private_key | base64 -w0

Добавьте строку base64 в переменные вашего проекта.

Источник

[Solved] SSH-Connection / Load key — invalid format #671

Describe the bug
Under «Edit Connection > Connection > Connection Details > Private Key >Private Key file» i select a name.ppk file that works perfectly in putty on Debian.
The output in Asbru-cm is:
Load key «/home/myusername/files/name.ppk»: invalid format :

Renaming the file to just name throws the same message:
Load key «/home/myusername/files/name»: invalid format

ls -la in that folder:
drwxr-xr-x 2 myusername.myusername 4096 Jul 14 21:51 .
drwxr-xr-x 30 myusername.myusername 4096 Jul 14 13:40 ..
-rwx—— 1 myusername.myusername 1482 Jul 14 21:51 name
-rwx—— 1 myusername.myusername 1482 Okt 27 2018 name.ppk

To Reproduce
Steps to reproduce the behavior:
0. Make SSH Connection

  1. Go to ‘..Edit Connection > Connection > Connection Details > Private Key >Private Key file.’
  2. Add a keyfile > Click on ‘Save and Close.’
  3. Choose that connection and connect
  4. See error

Expected behavior
Smooth login as in putty:

Screenshots
If applicable, add screenshots to help explain your problem.

Environment (please complete the following information):

Client OS: Debian GNU/Linux 10 (buster)

Ásbrú Version
Ásbrú Connection Manager 6.2.1 (asbru-cm) started with PID 13275
INFO: Desktop environment detected : xfce
INFO: Config directory is ‘/home/myusername/.config/asbru’
INFO: Used config file ‘/home/myusername/.config/asbru/asbru.nfreeze’
INFO: Virtual terminal emulator (VTE) version is 0.54
INFO: Theme directory is ‘/opt/asbru/res/themes/default’

Additional context
this happens on all my external servers where i can ssh to with putty without any problem.
I have to say the the ssh-servers only accept auth with publickey. Anything else is permitted.

The text was updated successfully, but these errors were encountered:

Источник

UPDATED

When I am trying to generate a public key it still gives me an error
«error in libcrypto»

Load key «breakthis»: error in libcrypto

Private key is given below

I am trying to solve a Hack the box machine

I was able to get a private key
then I converted that private key into a hash for JOHNTHERIPPER and cracked it successfully

But now when I try to login in through ssh I am getting the following error
I have searched a lot but not able to resolve these error


ssh -i id_rsa joanna@10.10.10.171

load pubkey "id_rsa": invalid format 

Load key "id_rsa": error in libcrypto

joanna@10.10.10.171's password: 

asked Apr 2, 2020 at 3:42

Raghav Talwar's user avatar

Raghav TalwarRaghav Talwar

191 gold badge1 silver badge3 bronze badges

9

ERROR: load pubkey «id_rsa»: invalid format

It happens when public key is used in ~/.ssh/config instead of using private key.

answered Dec 28, 2022 at 21:07

Alex's user avatar

AlexAlex

2892 silver badges9 bronze badges

As mentioned by Alex, a using a public key in ~.ssh/.config seems to cause cause the error in libcrypto for me as long as that key is not loaded by a running SSH agent.

It happened for me when my keeagent crashed. However, restarting the agent seems to allow such setup as mentioned in here

answered Jan 6 at 14:42

kf06925's user avatar

I got this error, when I was using 2 github accounts with 2 ssh keys, but get rid of this error when i changed my config file like below,

myDir$ ssh -T git@github.com
Load key "/home/taxi/.ssh/mhmd_personal.pub": error in libcrypto
git@github.com: Permission denied (publickey).

From this

Host *
  AddKeysToAgent yes
  IdentityFile ~/.ssh/mhmd_personal.pub
  # IdentityFile ~/.ssh/id_ed25519

to

Host *
  AddKeysToAgent yes
  IdentityFile ~/.ssh/mhmd_personal
  # IdentityFile ~/.ssh/id_ed25519

removed the .pub extension from config file.

answered Sep 28, 2022 at 6:29

Md. Sultanul Arefin's user avatar

2

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

$ ssh-add ./id_rsa
Error loading key "./id_rsa": invalid format

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.

# cat ./id_rsa
-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,...

...
-----END RSA PRIVATE KEY-----

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:

sign_and_send_pubkey: signing failed: agent refused operation

asked Oct 29, 2018 at 8:12

FlorianLudwig's user avatar

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:

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

    openssl rsa -noout -text < id_rsa
    openssl pkey -noout -text < id_rsa
    

    Try converting it to PKCS#8 format:

    umask 077
    openssl pkey < id_rsa > id_rsa.pkcs8
    ssh-add id_rsa.pkcs8
    
  2. 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:

puttygen id_rsa -o id_rsa.newformat -O private-openssh-new
ssh-add id_rsa.newformat

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

answered Oct 29, 2018 at 8:32

user1686's user avatar

user1686user1686

401k59 gold badges845 silver badges915 bronze badges

8

I was getting the same error message when passing in the private key through a CI pipeline variable in Gitlab.

The error was caused by not having a newline character at the end of the variable and was fixed by manually adding it.

answered Jul 3, 2020 at 12:23

AdrianoKF's user avatar

AdrianoKFAdrianoKF

3312 silver badges4 bronze badges

3

In my case, the problem was caused by incorrect end of line characters in id_rsa file. After copying file content, Windows text editor wanted to help me and converted EOLs to CR LF.

answered Sep 19, 2019 at 14:24

Kamil's user avatar

KamilKamil

2032 silver badges8 bronze badges

4

In my case, I just copied id_rsa private key but not the public part id_rsa.pub. It worked but complained with ‘invalid format’ each time I did server operations.
Copying id_rsa.pub as well solved the problem.

answered Jun 23, 2020 at 9:29

Ilya Palopezhentsev's user avatar

2

I recently had this problem, and in my case it was due to having an invalid certificate (i.e. $HOME/.ssh/id_rsa-cert.pub), which confusingly gave this same error even though my private key was still valid and SSH continued to work.

It was fixed by either removing the invalid (in my case, zero-sized) cert file, or replacing it with a valid certificate, as the case may be.

answered Apr 20, 2020 at 4:56

Jake McGinty's user avatar

3

In my case, on Windows, the solution was to use the Puttygen option Conversions > Export SSH key (force new file format)

answered Aug 24, 2020 at 0:20

cja's user avatar

cjacja

1831 gold badge1 silver badge8 bronze badges

Oh boy, just went through doing this for a team member… and the problem proved to be puttygen not doing things the nice way.
I was finally able to fix it by using Windows Powershell and the command:

ssh-keygen -t rsa

it was an instant fix !

jkmartindale's user avatar

answered Jun 3, 2021 at 20:32

AlexD's user avatar

AlexDAlexD

2182 silver badges4 bronze badges

1

I was struggling with this issue and it ended up being extra newlines before and after the
-----BEGIN RSA PRIVATE KEY----- and -----END RSA PRIVATE KEY----- lines respectively;
removing them fixed it and now works fine.

hernandanielg@laptop:~$ diff -c id_rsa .ssh/id_rsa

  *** id_rsa    2022-04-26 06:41:51.650982783 -0500
  --- .ssh/id_rsa   2022-04-26 06:39:47.971676083 -0500
  ***************
  *** 1,5 ****
    -----BEGIN RSA PRIVATE KEY-----
  - 
    Proc-Type: 4,ENCRYPTED
    
  --- 1,4 ----
  ***************
  *** 52,56 ****
    somehash
  - 
    -----END RSA PRIVATE KEY-----
  --- 51,54 ----

JW0914's user avatar

answered Apr 26, 2022 at 11:49

Hernan Garcia's user avatar

So a while ago I set up a server on AWS, and used their generated SSH key. I saved the key to Lastpass, and have successfully retrieved it from there before, and got it working. However, after trying that again today, I can’t get it to work.

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

I’ve tried ssh -i key_name, ssh-keygen -f key_name, but nothing works, I always get this error message:

Load key "key_name": invalid format

Is there any way to fix this?

asked Jun 6, 2017 at 12:06

Gregor Menih's user avatar

1

Check the contents of key_name, if the agent says invalid format, then there’s something wrong with the key — like .. are you sure that’s the correct key? Even if it’s not the private key you need, the ssh agent won’t return invalid format if the key is working, you simply won’t be able to connect. You might have placed your public key in there, for some reason. Check it!

answered Jun 6, 2017 at 12:23

13dimitar's user avatar

13dimitar13dimitar

2,4081 gold badge13 silver badges15 bronze badges

11

Starting openssh 7.6, it defaults to a new more secure format. You can force it to convert to that format using the commands below to change your key password. In case you don’t have and/or don’t want a password, you can simply press enter and it will still rewrite the key in the new format

ssh-keygen -f ~/.ssh/id_rsa -p

answered Jul 16, 2020 at 10:03

kim0's user avatar

kim0kim0

1,1507 silver badges7 bronze badges

6

I had the same issue, and it turns out I had Windows-style (CRLF) line separators in the file for some reason.

In addition, the file must end with a single LF.

Fixing those made things dandy again.

answered Mar 29, 2019 at 15:23

AKX's user avatar

AKXAKX

7635 silver badges7 bronze badges

9

I fixed this issue in Windows by converting the private key to OpenSSH format using the PuTTY Key Generator.

  1. Start Menu | All apps | PuTTY | PuTTYgen
  2. Load my.ppk
  3. Conversions | Export OpenSSH key
  4. Save my_openssh.ppk

Start Menu, All apps, PuTTY section, PuTTYgen

PuTTYgen, Conversions, Export OpenSSH

Now this works:

ssh -i "my_openssh.ppk" user@example.com

Mac conversion: (thanks @ChrisGillatt)

brew install putty 
puttygen ~/.ssh/my.ppk -O private-openssh -o ~/.ssh/my_openssh.ppk

Bob Stein's user avatar

Bob Stein

1,0421 gold badge7 silver badges9 bronze badges

answered Jul 21, 2018 at 3:44

Ras's user avatar

RasRas

4214 silver badges3 bronze badges

2

If you get a warning about an invalid public key format but the command still works then it may be because you only have a private key file and are using OpenSSH 8.3.

OpenSSH 8.3 includes a change to the ssh client where it looks for the private key’s corresponding public key file and outputs this load pubkey "/home/user/.ssh/id.rsa": invalid format warning but continues to connect successfully. Tools using ssh, such as scp or git may show key_load_public: invalid format.

The client does not need the public key when connecting, only the private key. So this check is pointless and it has already been removed by an upstream commit but isn’t in a relase (yet).

There’s a discussion about this on the ArchLinux forum.

answered Jul 28, 2020 at 12:31

starfry's user avatar

starfrystarfry

5811 gold badge7 silver badges13 bronze badges

3

In my case, it turned out that I had newlines between the start/end «headers» and the key data:

-----BEGIN RSA PRIVATE KEY-----

- Key data here -

-----END RSA PRIVATE KEY-----

Removing the extra new lines, so it became

-----BEGIN RSA PRIVATE KEY-----
- Key data here -
-----END RSA PRIVATE KEY-----

solved my problem.

answered Sep 13, 2019 at 13:59

user50849's user avatar

user50849user50849

3232 silver badges7 bronze badges

2

I just ran into this today when was writing some git tagging utils for my CI pipeline.

Here was the difference between my two keys:

$ diff ~/.ssh/gitlab ~/.ssh/git_ssh_key
27c27
< -----END OPENSSH PRIVATE KEY-----
---
> -----END OPENSSH PRIVATE KEY-----
 No newline at end of file

I changed my code like so:

     with open(ssh_key_file, 'w') as skf:
-        skf.write(ssh_key)
+        skf.write(ssh_key + 'n')

And now my ssh key works.

TL;DR — I guess you have to have a newline at the end of your private key.

answered Aug 4, 2019 at 16:38

Robert J's user avatar

Robert JRobert J

2412 silver badges4 bronze badges

2

After a recent update in Fedora 32 I started to get this warnings when connecting to remote hosts.

I solved the problem adding pkcs11: to the IdentityFile parameter in my .ssh/config like this:

IdentityFile pkcs11:~/.ssh/my_key.pem 

For reference, excerpt from ssh_config man page:

The authentication identity can be also specified in a form of PKCS#11 URI starting with a string pkcs11:.

answered Jun 2, 2020 at 9:08

Vicente Quintans's user avatar

5

I was asking openssh to use a particular identity file by specifying it in .ssh/config file.

The original working configuration had

IdentityFile = <path to public key file> 

This stopped working without any changes. On a little thinking I replaced the «path to public key file» above with «path to private key file» . That worked. The reasoning is that both public and private key files have large peudoprime related numbers as per the RSA algorithm. If you replace the private key file by public key file, these cryptographic numbers would not be extracted correctly from the base64 block saved within the key files. It seems some versions of ssh can figure out the .pub extension and use it to identify the correct private key file — and other versions dont do that. This is another way this error can happen. Hope it helps someone.

answered Apr 17, 2018 at 12:41

vpathak's user avatar

vpathakvpathak

1911 silver badge1 bronze badge

3

In my case, this was happening because I was missing a blank line between DEK-Info and the actual key data. I had:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,6E6F6E65206F6620796F757220627573
VGhpcyBpcyBub3QgbXkgYWN0dWFsIGtleSBzb3JyeSB0byBkaXNhcHBvaW50IHlv
...

But it needed to be:

-----BEGIN RSA PRIVATE KEY-----
Proc-Type: 4,ENCRYPTED
DEK-Info: AES-128-CBC,6E6F6E65206F6620796F757220627573

VGhpcyBpcyBub3QgbXkgYWN0dWFsIGtleSBzb3JyeSB0byBkaXNhcHBvaW50IHlv
...

answered Jan 7, 2021 at 18:23

Joshua Davies's user avatar

1

You should convert your .ppk key to OpenSSH key

Here is how you do it:

  1. Download PuttyGen and generate your keypair (if you don’t have keypair ready). Save private key to your folder (.ppk)
  2. If you are already had the private key, load the private key file (.ppk) by pressing the «Load» Button. Otherwise, skip this step
  3. Under menu «Conversions», choose Export OpenSSH key then save it to your folder
  4. Now you are ready to use the key to login your server without typing the password (I assume you already put the public key under /root/.ssh/authorized_keys, chmod 600 /root/.ssh/authorized_keys, And Restarted SSH demon )

answered Apr 20, 2019 at 9:31

Dylan B's user avatar

Dylan BDylan B

1611 silver badge3 bronze badges

1

Use your private key instead of the public key.

answered Apr 3, 2018 at 12:11

Richard's user avatar

2

I’ve faced with the compatibility issue in Win32-OpenSSH 8.1.

None of the answers here worked for me so I found my own way: convert key to the new format using PuTTYgen utility.

  1. Run fresh version of puttygen
  2. Open the key (Conversions > Import key). Enter passphrase.
  3. Save key in new OpenSSH format (Conversions > Export OpenSSH key (force new file format))

enter image description here

answered Nov 18, 2020 at 18:17

Ilya Serbis's user avatar

I started seeing this problem when I upgraded to Ubuntu 20.10. It uses OpenSSH_8.3p1.

I fixed it using:

ssh-keygen -y -f mykey.pem > mykey.pem.pub

Andrew Schulman's user avatar

answered Jan 6, 2021 at 16:05

mark amos's user avatar

Confusingly, the error says «pubkey» while pointing to a private key file.

A missing public key file (or other problems with it) causes this error — see this answer for details.

answered Oct 3, 2020 at 9:47

uvsmtid's user avatar

uvsmtiduvsmtid

8771 gold badge6 silver badges13 bronze badges

You are logging with the wrong user

In my case, I was trying to connect to an Amazon AWS EC2 instance, but getting the error

load pubkey "MyPrivateKey.pem": invalid format

This was because I was trying to log with the wrong user (ec2-user)

I was using an Ubuntu machine, with user ubuntu instead of ec2-user (as is stated on the official Amazon Linux server OS).

But why that error?

It turns out Amazon uses an old format (puttygen says upon loading «openssh ssh-2 private key (old pem format)») that openssh doesn’t like very much, so it is really a warning and not an error.

The real error (there is no such user on that server) is hidden by the server (otherwise you could brute force login names), but instead a «Connection closed» is shown.


You can find the name you use to connect to your machine on AWS under Actions>Connect.


How to fix the warning?

Just follow the answer of «Ras», which is, use PuTTYgen to convert to the OpenSSH format.

kenlukas's user avatar

kenlukas

2,9862 gold badges14 silver badges25 bronze badges

answered Jun 11, 2020 at 16:35

F. Alessandro's user avatar

I got this error when I use my public key with ssh-add. I should have used the private key. The public key can cause this error.

ssh-add rsakey.pub
Error loading key "rsakey.pub": invalid format

However, this is fine:

ssh-add rsakey

answered Jan 13, 2021 at 18:35

thebiggestlebowski's user avatar

In my case the problem was that the private key was in the following format:

-----BEGIN OPENSSH PRIVATE KEY-----
...
-----END OPENSSH PRIVATE KEY-----

whereas the SSH server expected the following format:

-----BEGIN RSA PRIVATE KEY-----
...
-----END RSA PRIVATE KEY-----

answered Feb 1, 2021 at 14:48

syntagma's user avatar

I was having this problem with Mac OSX 11.4 and ssh version OpenSSH_8.1p1, LibreSSL 2.7.3. I tried all of the other solutions and nothing worked (i.e., I regenerated keys, tried newlines etc.).

Then I read this on the GitHub docs and by adding the following to my ~/.ssh/config I no longer got the error

Host *
    AddKeysToAgent yes
    UseKeychain yes
    IdentityFile ~/.ssh/id_rsa

answered Aug 1, 2021 at 0:07

Michael Hall's user avatar

I had this issue because I had a key in ~/.ssh that actually was an invalid format and I had a lot of keys, which meant SSH was trying them all, even though I specified my identity file in the command. It just happens to fail because it can only try 5 keys I think, and then left me with that error, which was legit, just for the wrong identity file. The solution was to just use IdentitiesOnly yes in my ~/.ssh/config.

answered Feb 12, 2019 at 8:51

Elijah Lynn's user avatar

Elijah LynnElijah Lynn

1393 silver badges17 bronze badges

I had this error because there was a blank line at the beginning of the key file. Easy to miss if you are cating it out.

answered Feb 15, 2019 at 3:01

Elijah Lynn's user avatar

Elijah LynnElijah Lynn

1393 silver badges17 bronze badges

This is also the error ssh (at least some versions) emits if you have a passphrase on your private key, and enter the passphrase wrong when you attempt to connect.

(In particular, this happened to me with:
OpenSSH_7.6p1, LibreSSL 2.6.2,
which is the built-in SSH for Mac OS X 10.13.6 .)

So double-check that you’re using the right passphrase, and that CAPS LOCK is off.

answered Feb 15, 2019 at 3:31

ssh user on os x's user avatar

My issue was due to encoding. Looking in VSCode the encoding of the file (which I had created using Out-File in PowerShell) was UTF-16LE. When I switched to UTF-8, the key was valid.

answered Mar 24, 2020 at 13:02

john's user avatar

johnjohn

1,9951 gold badge17 silver badges30 bronze badges

For anyone who has tried sudo puttygen ~/.ssh/your-key.pem -O private-openssh -o ~/.ssh/your-key-new.pem and got an error message saying puttygen: this command would perform no useful action there is an even newer format so you need to amend the command as follows:

sudo puttygen ~/.ssh/your-key.pem -O private-openssh-new -o ~/.ssh/your-key-new.pem

I was using a key generated by AWS on Manjaro which is a bit more bleeding edge than most other distros, still worked but the warning message was annoying.

For more info you can use man puttygen but the relevent section is below:

  -O output-type
    Specify the type of output you want puttygen to produce. Acceptable options are:

    private
      Save the private key in a format usable by PuTTY. This will either be the standard SSH-1 key format, or PuTTY's own SSH-2 key format.

    public Save  the  public key only. For SSH-1 keys, the standard public key format will be used (`1024 37 5698745...'). For SSH-2 keys, the public key will be output in the format specified by
      RFC 4716, which is a multi-line text file beginning with the line `---- BEGIN SSH2 PUBLIC KEY ----'.

    public-openssh
      Save the public key only, in a format usable by OpenSSH. For SSH-1 keys, this output format behaves identically to public. For SSH-2 keys, the public key will be output in the  OpenSSH
      format, which is a single line (`ssh-rsa AAAAB3NzaC1yc2...').

    fingerprint
      Print the fingerprint of the public key. All fingerprinting algorithms are believed compatible with OpenSSH.

    private-openssh
      Save an SSH-2 private key in OpenSSH's format, using the oldest format available to maximise backward compatibility. This option is not permitted for SSH-1 keys.

    private-openssh-new
      As private-openssh, except that it forces the use of OpenSSH's newer format even for RSA, DSA, and ECDSA keys.

    private-sshcom
      Save an SSH-2 private key in ssh.com's format. This option is not permitted for SSH-1 keys.

    If no output type is specified, the default is private.

answered Aug 9, 2020 at 13:20

Bob's user avatar

I did something like the information here
https://github.com/marketplace/actions/webfactory-ssh-agent

SSH Private Key Format
If the private key is not in the PEM format, you will see an Error loading key «(stdin)»: invalid format message.

Use ssh-keygen -p -f path/to/your/key -m pem to convert your key file to PEM, but be sure to make a backup of the file first 😉.

It solved my issue.

answered Aug 17, 2021 at 4:24

Dicky Macias's user avatar

If you are on windows using Cygwin, Gitbash, MSYS or similar tools, try to start your command in elevated mode (run as administrator).

I had to do this to re-export the public key file.
If you are using .ssh/config file, make sure that the private key file is referenced there IdentityFile ~/.ssh/id_rsa.

Creating your private key file using puttygen will lead to similar error messages too, use OpenSSH to generate your private-public key-pair.

Using the public key file (~/.ssh/id_rsa.pub) as your identity file (IdentityFile in .ssh/config) will cause misleading error messages like

  • invalid format
  • connection timeout

answered Oct 11, 2021 at 12:33

linux64kb's user avatar

TL;DR

FWIW, I ran into this problem today.

I never figured out what the new install of Win32 «portable openssh» 8.0.p1 didn’t like about the key files — I just created new keys and added them to github and gitlab:

ssh-keygen -o -t rsa -b 4096 -C "New format OpenSSH for github" -f C:Usersmburr.sshgithub.mburr-precor.key-2.id_rsa

Details

I had a working install of OpenSSH from the https://github.com/PowerShell/openssh-portable project (as installed by Chocolatey). But a few days ago I had to perform a «repair install» of Windows and therefore had to reinstall OpenSSH.

After that my keys used to authenticate to github and gitlab would no longer work giving the «invalid format» error. These were the identical key files that had been on the system before (the Repair Reinstall didn’t remove those files).

I found no problems with line endings (all LF and an LF at the end of the file). The keys worked on a Linux system — and I later found that they worked with the OpenSSH included with Git for Windows v2.33.1.

 using the Win32 "portable OpenSSH" (from https://github.com/PowerShell/openssh-portable as installed by Chocolatey)
# Private key file error: "invalid format"
#

C:devtrees>"c:Program FilesOpenSSH-Win64ssh.exe" -V
OpenSSH_for_Windows_8.0p1, LibreSSL 2.6.5

C:devtrees>"c:Program FilesOpenSSH-Win64ssh.exe" -F c:utilemptyfile -i c:usersmburr.sshgithub.mburr.id_rsa -T git@github.com
Load key "c:\users\mburr\.ssh\github.mburr.id_rsa": invalid format
git@github.com: Permission denied (publickey).


#-------------------------------------------------------
# using the OpenSSH that comes with Git for Windows v2.33.1
# No problem with the private key
#

C:devtrees>c:gitusrbinssh.exe -V
OpenSSH_8.8p1, OpenSSL 1.1.1l  24 Aug 2021

C:devtrees>c:gitusrbinssh.exe -F c:utilemptyfile -i c:usersmburr.sshgithub.mburr.id_rsa -T git@github.com
Enter passphrase for key 'c:usersmburr.sshgithub.mburr.id_rsa':
Hi mburr! You've successfully authenticated, but GitHub does not provide shell access.

(emptyfile is just that. I specified it as the config file with -F to force ssh to ignore ~/.ssh/config)

I never figured out what the Win32 «portable openssh» 8.0.p1 didn’t like about the key files — I just created new keys and added them to github and gitlab:

ssh-keygen -o -t rsa -b 4096 -C "New format OpenSSH for github" -f C:Usersmburr.sshgithub.mburr-precor.key-2.id_rsa

Problem solved.

answered Oct 28, 2021 at 1:01

Michael Burr's user avatar

In my case the private key must have been added to the agent with:

ssh-add ~/.ssh/private_id_rsa

answered Mar 4, 2022 at 6:46

0x416e746f6e's user avatar

0x416e746f6e0x416e746f6e

1511 gold badge1 silver badge6 bronze badges

I encountered this problem because the key file did not end with a newline character.

answered Apr 17, 2022 at 5:21

david.barkhuizen's user avatar

Skip to content

GitLab

Next
    • GitLab: the DevOps platform
    • Explore GitLab
    • Install GitLab
    • How GitLab compares
    • Get started
    • GitLab docs
    • GitLab Learn
  • Pricing
  • Talk to an expert

  • /


  • Help

    • Help
    • Support
    • Community forum

    • Submit feedback
    • Contribute to GitLab

    Projects
    Groups
    Snippets

  • Register

  • Sign in

Closed


Open


Issue created Oct 25, 2020 by Alexander Popov@AlexWayfer

Docs feedback: Unable to import SSH key for runner

https://docs.gitlab.com/ee/ci/ssh_keys/#ssh-keys-when-using-the-docker-executor

I see:

- echo "$SSH_PRIVATE_KEY" | tr -d 'r' | ssh-add -

But this command does not work: not with ed25519 format, neither with rsa; not with tr -d, neither without it.

Error loading key "(stdin)": invalid format

I found similar issue #220880 (closed) without response.

Понравилась статья? Поделить с друзьями:
  • Error loading kernel cache 0x9 хакинтош что делать
  • Error loading kernel cache 0x7 хакинтош
  • Error loading kernel cache 0x1
  • Error loading jvm at odis
  • Error loading java agent in