However when I try to add my new SSH key I get the following error: “key is invalid. you must supply a key in openssh public key format.”
Hi @csperando, welcome to the community
The email at the end of your key is ok as comments are supported for that key type.
All ssh-ed25519 keys will always be 80 (68 removing the ssh-ed25519) characters in length (do not worry about the comment/email at the end).
Anyway on checking you keylength it has an extra 7 characters, which would explain the error message related to an unrecognised key format.
Could you try deleting and regenerating your key, and we can debug from there it f does not work.
ssh-keygen -t ed25519 -C "your_email@example.com"
Then try adding your SSH ‘Public’ Key part to your GitHub account (e.g. id_ed25519.pub, or replacing id_ed25519 in the command with the name of your private key file you used)
If you are still not working/the key length is incorrect, can you provide some more details on steps to reproduce, such as environment OS, are you using Git and what version, are you using Git Bash or Git CMD?
Follow the instructions below from scratch and you will be able to sort this issue.
Many Git servers authenticate using SSH public keys. In order to provide a public key, each user in your system must generate one if they don’t already have one. This process is similar across all operating systems. First, you should check to make sure you don’t already have a key. By default, a user’s SSH keys are stored in that user’s ~/.ssh directory. You can easily check to see if you have a key already by going to that directory and listing the contents:
$ cd ~/.ssh
$ ls
authorized_keys2 id_dsa known_hosts
config id_dsa.pub
You’re looking for a pair of files named something like id_dsa or id_rsa and a matching file with a .pub extension. The .pub file is your public key, and the other file is the corresponding private key. If you don’t have these files (or you don’t even have a .ssh directory), you can create them by running a program called ssh-keygen, which is provided with the SSH package on Linux/macOS systems and comes with Git for Windows:
$ ssh-keygen -o
Generating public/private rsa key pair.
Enter file in which to save the key (/home/schacon/.ssh/id_rsa):
Created directory '/home/schacon/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/schacon/.ssh/id_rsa.
Your public key has been saved in /home/schacon/.ssh/id_rsa.pub.
The key fingerprint is:
d0:82:24:8e:d7:f1:bb:9b:33:53:96:93:49:da:9b:e3 schacon@mylaptop.local
First it confirms where you want to save the key (.ssh/id_rsa), and then it asks twice for a passphrase, which you can leave empty if you don’t want to type a password when you use the key. However, if you do use a password, make sure to add the -o option; it saves the private key in a format that is more resistant to brute-force password cracking than is the default format. You can also use the ssh-agent tool to prevent having to enter the password each time.
Now, each user that does this has to send their public key to you or whoever is administrating the Git server (assuming you’re using an SSH server setup that requires public keys). All they have to do is copy the contents of the .pub file and email it. The public keys look something like this:
$ cat ~/.ssh/id_rsa.pub
ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAklOUpkDHrfHY17SbrmTIpNLTGK9Tjom/BWDSU
GPl+nafzlHDTYW7hdI4yZ5ew18JH4JW9jbhUFrviQzM7xlELEVf4h9lFX5QVkbPppSwg0cda3
Pbv7kOdJ/MTyBlWXFCR+HAo3FXRitBqxiX1nKhXpHAZsMciLq8V6RjsNAQwdsdMFvSlVK/7XA
t3FaoJoAsncM1Q9x5+3V0Ww68/eIFmb1zuUFljQJKprrX88XypNDvjYNby6vw/Pb0rwert/En
mZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx
NrRFi9wrf+M7Q== schacon@mylaptop.local
Andrey Bogatyrev
Проблема с добавлением SSH ключа на GitHub.
Генерировал уже не один ключ.
Пытаюсь понять в чем проблема использую GitHub Docs:
# Ensure the ssh-agent is running.
$ eval "$(ssh-agent -s)"
Agent pid 1276
# Add your SSH private key to the ssh-agent.
$ ssh-add ~/.ssh/id_ed25519
Identity added: /c/Users/M72e-2/.ssh/id_ed25519 (2way@yandex.ru)
# Копирую ключ из Git Bush (либо из сохраненного файла в текстовом редакторе)
$ clip < ~/.ssh/id_ed25519.pub
# Пытаюсь добавить ключ в GitHub (с почтой и без)
SHA256:NAVXvX3fI7CGSl+9UScomAQ1CbyPnBes5vRAd2Q1Ho4 2way@yandex.ru , но всегда выдает ошибку:
"Key is invalid. You must supply a key in OpenSSH public key format".
# ключ существует
$ ls -al ~/.ssh
total 23
drwxr-xr-x 1 M72e-2 197121 0 Aug 20 23:48 ./
drwxr-xr-x 1 M72e-2 197121 0 Aug 20 23:34 ../
-rw-r--r-- 1 M72e-2 197121 464 Aug 21 02:53 id_ed25519
-rw-r--r-- 1 M72e-2 197121 97 Aug 21 02:53 id_ed25519.pub
-rw-r--r-- 1 M72e-2 197121 92 Aug 20 23:48 known_hosts
В чем проблема?
4
0
Aleksandr Litvinov
Ключ, который нужно вставить в github должен начинаться с «ssh-ed25519». Если вы открываете публичный ключ и видите там строку с «SHA256» вначале, то возможно вы как-то не так сгенерировали ключ. Правильная команда:
ssh-keygen -t ed25519 -C "your_email@example.com"
0
Елизавета Пантюхина
Aleksandr Litvinov, у меня такая же проблема. Ключ начинается с SHA256, но команду я ввела правильно, перепроверила и повторно вводила. Ссылка со скриншотом команды https://ibb.co/QMM4Ld6
0
Andrey Bogatyrev
`**Aleksandr Litvinov**,
# Все получилось.
# После команды:
$ ssh-keygen -t ed25519 -C "2way@yandex.ru"
# Получаю такое сообщение:
Generating public/private ed25519 key pair.
Enter file in which to save the key (/c/Users/M72e-2/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/M72e-2/.ssh/id_ed25519
Your public key has been saved in /c/Users/M72e-2/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:tSbaOFigLSfQuzFpSoX9bZdM6UTmV8OZHxlzOHO5oU0 2way@yandex.ru
# Изначально для GitHub добавлял этот ключ - "SHA256:......",
# но это приводило к ошибке "Key is invalid. ..."
# Ключ нужен именно из файла /id_ed25519.pub,
# причем смог его скопировать только именно из Bash:
$ cd /c/Users/M72e-2/.ssh
$ cat id_ed25519.pub
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIODl7HLIHn++hPLdUwLT7TbTjraz/cOw+MmpCvxo6Wpg 2way@yandex.ru`
# SHA256:... - это приватный ключ?
1
Aleksandr Litvinov
Abo, здорово, что получилось!
Елизавета, вам нужно получить содержимое сгенерированного файла, а не то, что выводится после выполнения команды.
То, что вы видите в выводе создания ключа — это отпечаток открытого ключа, а не сам ключ.
0
У меня только что была эта проблема. Супер разочаровывает. Я полагал, что моя ситуация могла повлиять на причину проблемы. Я использую планшет, пытаюсь настроить ключ на сайте githubs через браузер планшета (Chrome) и копирую ключ из приложения ssh, подключенного к моему удаленному серверу Linux.
В итоге произошло то, что каким-то образом, когда я скопировал ключ в браузер, он ввел несколько разрывов строк. Не только это, но и удаление символа из каждой точки, где была вставлена новая строка.
Поэтому, чтобы заставить его работать, мне приходилось вручную находить каждый новый разрыв строки, а затем искать эту часть ключа, чтобы найти недостающий символ. Затем я добавил символ и удалил новую строку. После того, как я выследил каждое изменение, ключ работал нормально.
Кстати, я сам не добавлял новых разрывов строк, таких как упомянутый другими после ssh-rsa.
Надеюсь, это поможет другим. Я понятия не имею, почему это произошло. Глупо, что копирование в буфер обмена изменит скопированный текст. О, я тоже скопировал прямо из Вима.
Hi! I am trying to enter SSH key on GitHub. I generated it with “ssh-keygen” command. And I got a message “Key is invalid. You must supply a key in OpenSSH public key format”. What should I do? My SSH key is a big amount of symbols, as it should be. It doesn’t start with “ssh-rsa” or other words, described in GitHub. How should I get the key in correct form?
I generated it with “ssh-keygen” command.
That command is the right one, but could you add the complete command?
My SSH key is a big amount of symbols, as it should be. It doesn’t start with “ssh-rsa” or other words, described in GitHub.
Then it’s likely you’re not copying the right file. The filename should end with .pub. ssh-keygen should have asked you where to store the file, if you accepted the default it should be named something like id_rsa.pub (if using RSA).
View full answer
I generated it with “ssh-keygen” command.
That command is the right one, but could you add the complete command?
My SSH key is a big amount of symbols, as it should be. It doesn’t start with “ssh-rsa” or other words, described in GitHub.
Then it’s likely you’re not copying the right file. The filename should end with .pub. ssh-keygen should have asked you where to store the file, if you accepted the default it should be named something like id_rsa.pub (if using RSA).
0 replies
Answer selected
I am having the same issue and Yes i am copying the .pub file and not the pvt key . Still it won’t work . I tried everything , generated and regenerated the key multiple times. Any help plz. I am on windows
1 reply
I just had the same issue and realised that there is a Microsoft Publisher document appearing when the file is marked as «.pub»
If you right click this and open it in notepad you will have your public key.
Я в основном копирую следующий код в github с терминала Linux. Что-то не так с этим?
Ssh-ed25519 AAAAC3NzaC1lZDIlNTE5AAAAIKsxrHHSghWvO8MO+UlzmTHLxSp1BeuPX855Ywwdgi75 «мой адрес электронной почты»
Он имеет 80 символов (кроме моей электронной почты). Как мне это решить? Спасибо! 🙂
1 ответ
Я просто генерирую ключ ed25519 для тестирования (ssh-keygen -t ed25519 -P "" -f test), и он выглядит так:
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAICKFNOBwj9d9fSEmG1jgouYbltgmRcYFHMkGN8QnuEoE vonc@vclp
# compare to yours
ssh-ed25519 AAAAC3NzaC1lZDIlNTE5AAAAIKsxrHHSghWvO8MO+UlzmTHLxSp1BeuPX855Ywwdgi75 "my email"
Единственная разница заключается в том, что электронная почта заключена в двойные кавычки, но я попытался добавить свой в профиль My GitHub, устанавливая ключи SSH, даже с двойными кавычками: это работает.
Однако вы запускаете «Key is invalid. You must supply a key in OpenSSH public key format» с окончательным электронным письмом или без него.
Так что попробуйте перегенерировать один: ssh-keygen -t ed25519 -P "" -f test: его содержимое test.pub должно работать.
0
VonC
3 Авг 2022 в 12:21
у меня есть проблема, которая кажется о формате SSH-ключа, используемого GitHub. Я использовал Git Bash для создания нового SSH-ключа
$ ssh-keygen -t rsa -C "youremail@youremail.com"
затем я скопировал ключ в раздел SSH в настройках моей страницы учетной записи GitHub. Тем не менее, он пришел с уведомлением о проблеме следующим образом
Key is invalid. It must begin with 'ssh-ed25519', 'ssh-rsa', 'ssh-dss', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384', or 'ecdsa-sha2-nistp521'. Check that you're copying the public half of the key
после этого я отредактировал свой SSH-ключ, начиная с ssh-rsa и моего адреса электронной почты в конце. Тем не менее, вопрос до сих пор нет.
может ли кто-нибудь рассказать о решении это?
спасибо!
6 ответов
просто выполните эти шаги, и вы настроите свой ssh-ключ в кратчайшие сроки:
-
создать новый ключ SSH (или пропустите этот шаг, если у вас уже есть ключ)
ssh-keygen -t rsa -C "your@email" -
после того, как у вас есть ключ в
ssh-keygen будет генерировать вам пару ключей, один частный и один открытый. Похоже, вы загрузили не ту. GitHub хочет открытый ключ, как правило, здесь:~/.ssh/id_rsa.pub.
Если вы используете mac и ввод инструкции github (например,создание нового ключа SSH и добавление его в ssh-agent, вы, вероятно, печатаете и только нашив (авто-завершение) в:
$ pbcopy
, а не
$ pbcopy
с бывшим вы на самом деле копирование и попытка вставить закрытый ключ.
надеюсь, что это сэкономит вам время.
открыть ~/.ssh/id_rsa.pub, затем откройте его с помощью редактора и скопируйте открытый ключ в свой github
Я столкнулся с той же проблемой, и оказалось, что это связано с тем, что в комментарии. Github, по-видимому, не любит -, _ в порядке, хотя.
другой способ скопировать открытый ключ в буфер обмена
clip < ~/.ssh/id_rsa.pub
I have generated SSH keys for a new server installation according to the procedure outlined here. However, when I copy the contents of id_rsa.pub to my keys list on GitHub, I get the error message «Key is invalid. Ensure you’ve copied the file correctly.»
The generated key is valid, and I am copying it exactly as is (all in one line with no whitespace at the beginning/end).
Anybody have an idea what could be going on?
23 Answers
I came here because I had the same problem. From your question, I realized that I was copying the contents from the wrong file, without the .pub extension (it was my private key, i.e. the id_rsa file, which should be kept private at all times!)
From a MAC:
vi ~/.ssh/id_rsa.pub
Copy exactly from the end (with be the last letter of your email domain extension) of the block of characters to the beginning, which starts with ssh-rs …
If it doesn’t work, you are surely not copying properly.
It worked.
If you are on Windows, use notepad and copy-paste as described above.
I hope that helped.
Here are some steps that are not at all clear when copy/pasting your public key. (For the record, I used Putty Key Generator for my keys.)
- On the first line, enter ssh-rsa.
- Make sure you add one space after ssh-rsa
- When you copy/paste the key into the Key textbox it should preserve the n characters (x0A). If you are using Notepad on Windows, you won’t see these new lines until you copy the text to Github.
Notice on this screenshot, there’s a space after ssh-rsa (See the cursor.) The public key text also includes three n characters, so you can see the public key text bumps down to the next line three times in the textbox.
I try several ways, but none of them helps(my os is ubuntu). Then I thought if I can print the content of ~/.ssh/id_rsa.pub by using command «more».
I sorry than I have no reputation to post images! when i have, i will post it!
Here is a url where you can see the image:

I copied the content from the command line, and it WORKED!!!
I know this is question is a cpl years old now, but if someone in 2018 encounter this:

then below is a no-brainer:
my problem was I tried to copy the private key
id_rsa
instead of public key content
id_rsa.pub
as my SSH gitlab repository key, so after you:
ssh-keygen -t rsa -C "[email protected]" -b 4096
please remember about the .pub file extension to copy from:
- OSX:
pbcopy < ~/.ssh/id_rsa.pub
- Linux:
xclip -sel clip < ~/.ssh/id_rsa.pub
- Windows PowerShell
cat ~/.ssh/id_rsa.pub | clip
this makes perfect sense, because you should always only share your public key, not the private one 🙂
Someone suggested to use $ vi ~/.ssh/id_rsa.pub however it didn’t work for me.
So instead of that , I used $ cat ~/.ssh/id_rsa.pub command on windows machine to print out on the terminal then copy it.
If you have indeed copied the content of your id_rsa.pub key (in one continuous line), the result should look like (from The GitHub ssh help page):

The OP louism confirms a copy-paste issue:
- For a very obscure reason, copy-pasting from emacs removed the
nafter ssh-rsa, and that was causing the problem.- Copy-pasting from vi solved the problem.
Recommended by GitHub
Copying the SSH-KEY :
I worked with xclip to copy the id_rsa.pub key, like so:
1. Install xclip
sudo apt-get install xclip
2. Copy with xclip
xclip -sel clip < ~/.ssh/id_rsa.pub
Good Luck.
In windows,
Just Copy the naked key data from key file and remove new lines.
Write this below things in dialogue box to solve your problem.
ssh-rsa Key
NOTE : There is space between ssh-rsa and key
And you are done.
Just for those looking in the future, another common issue is that word-wrapping. For example, if you run cat ~/.ssh/id_rsa.pub it could wrap lines, thus adding extra characters at each line break. Remove these and your key should work fine.
I was having the same issue, despite copying the public key from cat output directly from the terminal (Cmder/ConEmu). It seems that the method that you use to copy the public key seems to make a difference. Here is a way to check:
$ ssh-keygen -l -f ~/.ssh/id_rsa.pub
4096 SHA256:...
Then paste the key that fails into a new file, and try to verify that:
$ ssh-keygen -l -f test.pub
test.pub is not a public key file.
In my case I had been copying the key from terminal output using cat; instead getting the key from vim worked. Here is way to open the key in vim with word wrap enabled:
$ vim "+set wrap" ~/.ssh/id_rsa.pub
I suspect that the terminal emulator may have something to do with it as I haven’t had this issue with Terminal.app.
If you use putty (puttygen), copy this!!!!

If you using Sublime you can see ssh-key correctly.
Check if there is any id_rsa.pub
ls -al ~/.ssh
If it is in place open it with sublime text
sudo subl /home/user_name/.ssh/id_rsa.pub
Then copy and paste your public ssh key.
In my case, I had to add an extra white rule after my e-mail (after the entire key string) before it got accepted. I found this out by accident, after trying to copy my ssh key as entered on Gitlab.
pbcopy from my pub key straight form the command line didn’t work. The copy from gitlab with the extra white rule at the end, did the trick.
I just had this issue. Super frustrating. I figured my situation might have affected the casue of the problem. I am using a tablet, trying to setup the key on githubs site through my tablet browser (Chrome) and I am copying the key from an ssh app connected to my remote linux server.
What ended up happening is that somehow when I copied the key to the browser, it introduced a number of line breaks. Not only that, but it also removed a character from each point where a new line was inserted.
So to get it to work, I had to manually find each new line break, then hunt for that part of the key to find the missing character. I then added the character and removed the new line. After I hunted down each and every change, the key worked fine.
By the way, I did not add any new line breaks myself, such as the one mentioned by others after the ssh-rsa.
Hopefully this helps others. I have no idea why it happened. Silly that copying to the clipboard would alter the text copied. Oh, I also copied it right out of Vim.
If you are using bash for windows as your terminal and you are copying via shift + highlighting + ctrl-c, then this solution might work for you:
- After copying the key and pasting it into notepad:

- Now go to Edit > Select All or Ctrl-A

- The large amounts of blue areas are whitespace. You need to delete them with either the backspace or the delete key. Leave the whitespace that in the green circles.

- You should now be able to copy and paste this edited version into github.
It’s common issue we face while generating the key. While the SSH generating, we will get two diff files one is id_rsa and id_rsa.pub. here the file with pub extension is the public key holder file. You must copy the content from this file and add to the Github.
NOTES:
1. public key file content starts with ‘SSH-RSA’
2. end with your Github email id. ex: if you registered Github with @gmail.com then the pub file has the specified email id at the last
if using vs code
code ~/.ssh/id_rsa.pub
will open .pub file copy it to github
To Copy the entire content of id_rsa.pub to clipboard:
Run > pbcopy ~/.ssh/id_rsa.pub
I was trying to upload my public key and was getting «Invalid Key» message.My format was not proper as there was extra spaces at the end of the key. It should be in format : ssh-rsa <public-key>
If you are on linux or mac, just do the following:
$ cat ~/.ssh/id_rsa.pub
The output should be in the form like below:
ssh-rsa somerandomcharacters [email protected]
Final step is to copy the contents and paste it in your destination
Copying the ssh public key into clipboard is mainly the trick here and the best way to do it is right from terminal. You must output this key onto the terminal by following command cat ~/.ssh/id_rsa.public and press enter. The ssh public will be displayed on the GitBash terminal screen and then you just need to copy it carefully by selecting from last charachter of your email to the begining of key i.e ssh rsa…
I spent days and then came to this solution in end.
My laptop is on macOS Big Sur version 11.3.1 and the ssh-keygen -t rsa generated a very long key with [email protected] at the beginning.
ssh-keygen -t rsa -b 4096 worked; it created a key with ssh-rsa algorithm.
Just try installing wps2019 and open the .pub on wps2019 and copy the code and paste it :