Error loading key invalid format windows

SSH Внезапно возвращается неверный формат Некоторое время назад я настроил сервер на AWS и использовал их сгенерированный ключ SSH. Я сохранил ключ в Lastpass и успешно извлек его оттуда, и он заработал. Однако, попробовав сегодня снова, я не могу заставить его работать. -rw——- 1 itsgreg users 1674 Jun 6 12:51 key_name Я пробовал ssh […]

Содержание

  1. SSH Внезапно возвращается неверный формат
  2. jesugmz / solve-load-pubkey-id_rsa-invalid-format.md
  3. Arch Linux
  4. #1 2020-06-01 13:52:57
  5. [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  6. #2 2020-06-01 14:34:58
  7. Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  8. #3 2020-06-01 16:59:12
  9. Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  10. #4 2020-06-01 17:29:38
  11. Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  12. #5 2020-06-01 17:42:19
  13. Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  14. #6 2020-06-01 17:56:26
  15. Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  16. #7 2020-06-09 12:14:25
  17. Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  18. #8 2020-06-15 02:58:10
  19. Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  20. #9 2020-06-17 17:09:57
  21. Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  22. #10 2020-07-10 15:24:55
  23. Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  24. #11 2020-07-11 07:22:26
  25. Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format
  26. SSH Key Format Issues and Fixing the “invalid format” Error
  27. 1. Introduction
  28. 2. Generate Key Pair
  29. 3. Authorizing the Correct Key
  30. 3.1. ssh-copy-id
  31. 3.2. Manual Key Authorization Problems
  32. 4. Using the Correct Key
  33. 5. Handling Keys Properly
  34. 5.1. Key Naming
  35. 5.2. Key Transfer and Streaming
  36. 6. Summary

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 — Я думаю, у вас должен быть символ новой строки в конце вашего закрытого ключа.

Источник

jesugmz / solve-load-pubkey-id_rsa-invalid-format.md

OpenSSH 8.3p1 introduces the need of having a public SSH key otherwise is gonna show the warning

load pubkey «/root/.ssh/id_rsa»: invalid format

To supress this message we can put in place our SSH public key or generate it from our private key with:

As pointed out in https://bbs.archlinux.org/viewtopic.php?id=256210 there is already a commit ready to fix this in the future.

I am getting this warning in OpenSSH_7.9p1. I have both private and public keys in the same place. Any Idea, what to do?

I am getting this warning in OpenSSH_7.9p1. I have both private and public keys in the same place. Any Idea, what to do?

That message should be for version 8.3p1, anyway, I would check permissions. OpenSSH is very sensible to them.

For me it was due to newer private key format, which generates:

To fix this, I have regenerated file using -m pem option:

For me it was due to newer private key format, which generates:

To fix this, I have regenerated file using -m pem option:

Your solution worked for me precisely. Thanks.

Didn’t work for me 🙁

Maybe you’re using UTF8-bom. You can use sed -i ‘s/^xEFxBBxBF//g’ /root/.ssh/id_rsa to remove bom in the rsa file.
`

i ve had exactle the same error.

Load key «key_name»: invalid format

I have solved it.

I suggest to check two things:

if you are using

/.ssh/config
then pls check that you have specified there you PRIVATE key. If you specified publick key there — you ll get the error

pls check your echo $HOME.
in some OS like ubuntudebian when you type:
$ sudo bash
your $HOME directory stay the same. I mean it is not /root
so OS is looking for ssh keys in /home/user/.ssh/ dir!
But you think it is using /root/.ssh dir
so pls check echo $HOME.

Источник

Arch Linux

You are not logged in.

#1 2020-06-01 13:52:57

[SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

After upgrade today to openssh 8.3p1-1 I am getting warnings for private keys that used to work fine and also work fine with older ssh versions eg OpenSSH_7.6p1.

The warning has the form

load pubkey «mykeyfilepath»: invalid format

I assume this has to do with the update requiring some preferred formatting of the PEM files that I have always used. Is there a way to fix this? Although the warning doesn’t prevent the ssh command from working the stderr output causes warning emails etc etc.

Last edited by replabrobin (2020-06-01 17:57:30)

#2 2020-06-01 14:34:58

Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

As a quick check I downgraded openssh to https://archive.archlinux.org/packages/ … kg.tar.zst and then the warning messages go away so they are caused by the upgrade to 8.3p1-1.

#3 2020-06-01 16:59:12

Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

Did you try to recreate the key into PEM format? (see) man ssh-keygen

edit: what happens if you recreate id_rsa and the pem.key?

Last edited by qinohe (2020-06-01 17:03:31)

#4 2020-06-01 17:29:38

Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

Registered Linux User #482438

#5 2020-06-01 17:42:19

Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

Did you try to recreate the key into PEM format? (see) man ssh-keygen

edit: what happens if you recreate id_rsa and the pem.key?

the above seems related to creating a public key; that’s not what I need. The warning refers directly to the private key.

#6 2020-06-01 17:56:26

Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

duh, I looked at the changes and saw the stuff about rsa. I tried the alleged test

but although I got the warning it still connected so I thought that wasn’t the problem. If I use a different key type eg ed25519 then I see no warning.

The warning seems to be the problem. Obviously there’s no format error in the rsa key file; it seems to be the key type that is deprecated. Thanks for pointing at the solution. It seems we need to change the private key type.

#7 2020-06-09 12:14:25

Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

for me it not now complains (but still works):
load pubkey «/home/user/.ssh/id_rsa»: invalid format.

adding /home/user/.ssh/id_rsa.pub makes the warning go away

#8 2020-06-15 02:58:10

Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

I’m having the same problem, but I’m using .pem keys. All my keys worked fine, now they sill work but keeps giving me the error » load pubkey «key.pem»: invalid format «

Last edited by eduardo_amarall (2020-06-15 02:58:33)

#9 2020-06-17 17:09:57

Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

Having the exact same problem as well. I’m specifying IdentityFile entries for hosts defined in my

/.ssh/config. Specifically using SSH keys in .pem format downloaded from AWS that I have been using for years. There’s no corresponding .pub key file on my machine since AWS automatically deployed the public key to each server you deploy.

In general this sounds like openssh makes a faulty assumption in that there’s going to be a corresponding .pub file next to each private key.

Last edited by Albert Camus (2020-06-17 17:19:28)

#10 2020-07-10 15:24:55

Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

Having the exact same problem as well.

In general this sounds like openssh makes a faulty assumption in that there’s going to be a corresponding .pub file next to each private key.

Yeah, having the same problem since OpenSSH 8.3 client.

Why is there new assumption of public key to be present? It is not needed in the authentication process.
Why is this a warning-worthy event? If it would be an error, the connection wouldn’t happen.
When adding couple of -v arguments, there is nothing mentioned about the missing .pub-file.

The working solution to remove this unnecessary warning is to add the correct public key.

#11 2020-07-11 07:22:26

Re: [SOLVED] openssh load pubkey «mykeyfilepath»: invalid format

Problem was introduced exactly two years ago on 11th July 2018. Fix (commit c514f3c0522855b4d548286eaa113e209051a6d2) was introduced three weeks ago to suppress the warning. The problem will go away when OpenSSH gets updated.

For code-oriented people, I wrote a blog post covering the breaking and fixing commits into Github.

Источник

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.

Источник

The recent beta version of OpenSSH on Windows 10 does not accept my openssh formatted private key:

enter image description here

The same key works on ssh shipped with git shell from github.

Is there a format option for openssh on Windows that I’m missing or is this a bug?

asked Dec 17, 2017 at 21:04

AK_'s user avatar

3

I got this working.. believe it or not by adding a single LF at the end of your private key file. E.G

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

Without the LF the private key worked fine with putty, secureCRT, WinSCP, GIT etc… but Windows (which is used by VisualCode) Kept giving me «invalid Format»

General Grievance's user avatar

answered Jul 30, 2021 at 15:45

Grev's user avatar

GrevGrev

6035 silver badges4 bronze badges

1

Windows 10 currently (as of January 2018) only supports ed25519 keys (reference: https://github.com/PowerShell/Win32-OpenSSH/issues/973). I see that you are trying to connect to Amazon Web Services. If you manage your key using the AWS console, you can only use an RSA key.

However, if you are trying to connect to an existing EC2 instance, you can do the following:

  1. Create the private/public key in Windows cmd using the command «ssh-keygen», if you have not already done this. The key pair is saved in files id_ed25519.pub and id_ed25519 in your .ssh directory
  2. Connect to your AWS EC2 instance. Add the contents of the id_ed25519.pub to your authorized_keys file within the .ssh directory
  3. Now you can connect to your EC2 instance using the Windows 10 SSH client.

answered Jan 2, 2018 at 15:34

simon's user avatar

simonsimon

12.5k25 gold badges77 silver badges110 bronze badges

2

I had a similar issue. I copied it id_rsa from Linux to Windows 10. I knew that it was probably line-terminating issue. So I downloaded dos2unix for Windows https://waterlan.home.xs4all.nl/dos2unix.html, and ran dos2unix id_rsa, and it worked afterwards.

answered Aug 21, 2021 at 1:11

Raza's user avatar

RazaRaza

2,9972 gold badges29 silver badges34 bronze badges

try this

ssh-keygen -o -a 100 -t ed25519 -f ~/.ssh/id_rsa -C "your email"

and catch the folder with this command

cat ~/.ssh/id_rsa.pub

hope this help.

answered May 18, 2019 at 14:09

dhedheerik88's user avatar

For me, a new line at the end of the file solved the problem.

answered Aug 26, 2022 at 3:06

Fenghe Xu's user avatar

0

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

7535 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

1811 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,9762 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

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


June 6, 2020




1-minute read

If you get an ‘invalid format’ error when trying to SSH in to a remote server using a private key file that you know is valid, it may be because the key was generated with PuTTY.

If the key begins with PuTTY-User-Key-File and you are using SSH/openSSH (ie. command line SSH) to connect to your server, you will need to first convert the key file using the puttygen tool that comes with PuTTY.

Launch puttygen and load your existing private key file. From the menu, select Export OpenSSH key (force new file format). Then click Save private key and save your converted key file.

Examine the new key file. The format should begin with BEGIN OPENSSH PRIVATE KEY and look something like the picture shown above. You should now be able to log in to your server using your new key file.

RRS feed

  • Remove From My Forums
  • Question

  • Hi,

    I have a Debian 9.5 VM on which I generated an ssh key pair using `ssh-keygen`
    I then copied the `id_rsa.pub` file to my Windows 10 PC, on which I use
    the Windows 10 built-in OpenSSH Client and OpenSSH Server.

    After starting the `ssh-agent` service, I try to add the `id_rsa.pub` file
    using the `ssh-add` command but it gives me the following error:

    Error loading key "id_rsa_debian.pub": invalid format

    Any ideas why that does not work?
    Thanks!


    Paul Dirac

All replies

    • Proposed as answer by

      Friday, February 22, 2019 9:22 AM

  • Hi Diracsbracket,

    What is your current situation? Have you tried the suggestions provided above? Please remember to

    mark the replies as answers
    if they help, any other questions please feel free to post back. Thank you for choosing Microsoft.

    Best regards,
    Zoe Mo


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact
    tnmff@microsoft.com.

  • Hi Diracsbracket,

    We haven’t heard from you for a couple of days, have you solved the problem? Would you mind letting me know the update of the problem? Please remember to

    mark the replies as answers
    if they help, any other questions please feel free to post back. Thank you for choosing Microsoft.

    Best regards,
    Zoe Mo


    Please remember to mark the replies as answers if they help.
    If you have feedback for TechNet Subscriber Support, contact
    tnmff@microsoft.com.

SSHing into my system succeeds but even without the -v flag I get key_load_public: invalid format message. Below is the output w/ using the verbose flag.

Specifically

debug1: key_load_public: No such file or directory
debug1: identity file /home/myname/.ssh/private_rsa_key-cert type -1

seems to be the problem as I don’t have such a file. However, I checked w/ another system and I also get the same two above lines. However there is no key_load_public: invalid format before that, which is what I actually want to get rid of. Permissions on the authorized_keys file on both remote systems looks the same, permissions on the private_keys look the same too.

    $ ssh -v desired_host
    OpenSSH_7.2p2, OpenSSL 1.0.2g  1 Mar 2016
    debug1: Reading configuration data /home/myname/.ssh/config
    debug1: /home/dli/.ssh/config line 16: Applying options for desired_host
    debug1: Reading configuration data /etc/ssh_config
    debug1: Connecting to desired_host [X.X.X.X] port 22.
    debug1: Connection established.
    key_load_public: invalid format
    debug1: identity file /home/myname/.ssh/private_rsa_key type -1
    debug1: key_load_public: No such file or directory
    debug1: identity file /home/myname/.ssh/private_rsa_key-cert type -1
    debug1: Enabling compatibility mode for protocol 2.0
    debug1: Local version string SSH-2.0-OpenSSH_7.2
    debug1: Remote protocol version 2.0, remote software version OpenSSH_5.3
    debug1: match: OpenSSH_5.3 pat OpenSSH_5* compat 0x0c000000
    debug1: Authenticating to desired_host:22 as 'myname'
    debug1: SSH2_MSG_KEXINIT sent
    debug1: SSH2_MSG_KEXINIT received
    debug1: kex: algorithm: diffie-hellman-group-exchange-sha256
    debug1: kex: host key algorithm: ssh-rsa
    debug1: kex: server->client cipher: aes128-ctr MAC: umac-64@openssh.com compression: none
    debug1: kex: client->server cipher: aes128-ctr MAC: umac-64@openssh.com compression: none
    debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(2048<3072<8192) sent
    debug1: got SSH2_MSG_KEX_DH_GEX_GROUP
    debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
    debug1: got SSH2_MSG_KEX_DH_GEX_REPLY
    debug1: Server host key: ssh-rsa SHA256:EmG/FBK0OCXtaAqAkfHKxoXKLGiZiHUsQpObK6aWd30
    debug1: Host 'desired_host' is known and matches the RSA host key.
    debug1: Found key in /home/myname/.ssh/known_hosts:39
    debug1: rekey after 4294967296 blocks
    debug1: SSH2_MSG_NEWKEYS sent
    debug1: expecting SSH2_MSG_NEWKEYS
    debug1: rekey after 4294967296 blocks
    debug1: SSH2_MSG_NEWKEYS received
    debug1: SSH2_MSG_SERVICE_ACCEPT received
    debug1: Authentications that can continue: publickey,gssapi-keyex,gssapi-with-mic,password
    debug1: Next authentication method: publickey
    debug1: Trying private key: /home/myname/.ssh/private_rsa_key
    debug1: Authentication succeeded (publickey).
    Authenticated to desired_host ([X.X.X.X]:22).
    debug1: channel 0: new [client-session]
    debug1: Requesting no-more-sessions@openssh.com
    debug1: Entering interactive session.
    debug1: pledge: network

asked Apr 27, 2016 at 14:37

hiandbaii's user avatar

1

Same issue for me, different source and solution:

I had both id_rsa.foo (correct private key) and id_rsa.foo.pub (matching pubkey) in my .ssh folder on the client. Removing or renaming the pubkey made the message disappear.

answered Jun 3, 2020 at 14:36

Justin Sane's user avatar

2

There are two separate messages:

This one tells you that .ssh/private_rsa_key is in wrong format:

key_load_public: invalid format
debug1: identity file /home/myname/.ssh/private_rsa_key type -1

This one does not show up in without -v switch and is just informative to tell you that you don’t have a certificate:

debug1: key_load_public: No such file or directory
debug1: identity file /home/myname/.ssh/private_rsa_key-cert type -1

There is nothing to worry about the second message.

answered Apr 27, 2016 at 15:45

Jakuje's user avatar

JakujeJakuje

20.7k7 gold badges50 silver badges70 bronze badges

4

when I issued

ssh myid@mydomain

and got message (even though I successfully logged into remote box)

key_load_public: invalid format

it happened because somehow my local ~/.ssh/xxx.pub actually had contents of my private key file even though the remote host correctly had my public key in file ~myid/.ssh/authorized_keys SO solution was to correct my local ~/.ssh/xxx.pub so it had my public key

answered Oct 14, 2018 at 20:42

Scott Stensland's user avatar

Scott StenslandScott Stensland

2,4732 gold badges23 silver badges23 bronze badges

4

I was having this warning msg with scp and ssh when I used the -i option. I found that cause was extra in public key file. my pub key file had 2 lines with ‘wc -l’; i deleted the extra and now it only has 1 line with ‘wc -l’ and there are no warning messages.
I should clarify that ssh and scp worked correctly with and without the warning message.

answered Dec 6, 2019 at 20:54

Rod Melton's user avatar

1

I finally succeeded by being sure to copy and paste EXACTLY the contents of private RSA key, e.g.

-----BEGIN RSA PRIVATE KEY-----
<content>.....
-----END RSA PRIVATE KEY-----

including all the EOL tabs or whatever was there.

Anthony Geoghegan's user avatar

answered May 21, 2018 at 8:22

Andrew Roe's user avatar

1

I had the same problem and I found the solution.
My keys were created by puttygen. This tool (or kittygen) has a tab called conversion where you can save in three different formats.
I saved in «Export OpenSSH key» format and it gave me the error:
load pubkey «/home/user/.ssh/id_rsa»: invalid format
then I saved and used the key saved in format: «Export OpenSSH key (force new file format)» and the warning is removed.
So the key is this new format.

answered Jun 23, 2020 at 23:27

Massimo's user avatar

This happened to me since I had RSA & DSA keys into my .ssh folder. The DSA key is no longer accepted on the system, so I just removed it and the message disapperared.

answered Dec 18, 2019 at 17:32

Vittorio de Gioia's user avatar


Некоторое время назад я настроил сервер на 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.

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

IdentityFile = <path to public key file> 

Это перестало работать без каких-либо изменений. Немного подумав, я заменил «путь к файлу открытого ключа» выше на «путь к файлу закрытого ключа». Это сработало. Причина заключается в том, что файлы открытого и закрытого ключей имеют большие числа, связанные с преступным преступлением, согласно алгоритму 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.

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

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

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

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

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

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


В моем случае оказалось, что у меня есть новые строки между начальными / конечными «заголовками» и ключевыми данными:

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

- Key data here -

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

Убрав лишние новые строки, чтобы стало

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

решил мою проблему.


Используйте свой закрытый ключ вместо открытого ключа.



У меня возникла эта проблема, потому что у меня был ключ в ~ / .ssh, который на самом деле был недопустимым форматом, и у меня было много ключей, что означало, что SSH пробовал их все, хотя я указал свой файл идентификации в команде. Это просто происходит сбой, потому что он может попробовать только 5 ключей, я думаю, а затем оставил меня с этой ошибкой, которая была законной, только для неправильного файла идентификации. Решение было просто использовать IdentitiesOnly yesв моем ~ / .ssh / config.


У меня была эта ошибка, потому что в начале файла ключа была пустая строка. Легко пропустить, если вы это делаете cat.


Это также ошибка, которую выдает ssh (по крайней мере, в некоторых версиях), если у вас есть секретная фраза в вашем закрытом ключе, и вы неправильно вводите идентификационную фразу при попытке подключения.

(В частности, это случилось со мной с: OpenSSH_7.6p1, LibreSSL 2.6.2, который является встроенным SSH для Mac OS X 10.13.6.)

Поэтому дважды проверьте, что вы используете правильную фразу-пароль и что CAPS LOCK выключен.


Убедитесь, что вы переименовали свой ключ PRIVATE и удалите расширение файла, которое является проблемой.

Шаги, которые я предпринял

Создайте свой открытый ключ:

Убедитесь, что вы находитесь в той же директории, где у вас есть закрытый ключ

Как создать открытый ключ:

ssh-keygen -y -f Private-Key.pem > Public-key.pub

убедитесь, что ключ PUBLIC имеет расширение .pub

после этого предоставьте соответствующие разрешения по соображениям безопасности:

chmod 600 Private-Key.pem
chmod 400 Public-key.pub

ТОГДА самая важная часть и причина, по которой вы получили ошибку «неверный формат»

Убедитесь, что вы переименовали свой ключ PRIVATE и удалите расширение файла:

Удалите .pem из вашего закрытого ключа.

mv Private-Key.pem Private-Key

или если на компьютере с Windows переименуйте закрытый ключ, то же имя просто удалите .pem

Понравилась статья? Поделить с друзьями:
  • Error launching installer windows 10 как исправить
  • Error java installer что делать windows 7
  • Error in ole initialization компас 18 как исправить windows 10
  • Error h is not a valid key name windows 7
  • Error finding your systems active partition windows loader