87

Is there a command I can use to verify the public key (id_rsa.pub), just the format only.

Sometimes I have added a new linebreak, sometimes the file missed the ssh-rsa prefix, so is there a command to validate with?

Peter Mortensen
  • 2,319
  • 5
  • 23
  • 24
Ryan
  • 5,341
  • 21
  • 71
  • 87

1 Answers1

126

You can use ssh-keygen for this. Despite its name it can do many more things than generating keys:

dennis@lightning:~$ ssh-keygen -l -f .ssh/id_rsa.pub 
2048 68:df:b2:22:d8:43:5d:36:75:c1:d8:59:c0:8c:22:e8  Dennis Kaarsemaker (RSA)
dennis@lightning:~$ ssh-keygen -l -f foo.txt
foo.txt is not a public key file.
Dennis Kaarsemaker
  • 18,793
  • 2
  • 43
  • 69
  • So I have to have the fingerprint beforehand to validate the public key? – Quazi Irfan Jan 16 '17 at 05:13
  • 1
    @QuaziIrfan no, you do not need the fingerprint beforehand. The returncode of `ssh-keygen` will tell you whether it's valid or not. – vidstige Oct 06 '17 at 08:33
  • 2
    Does not work for keys with passwords :-( – vidstige Oct 06 '17 at 08:33
  • 3
    Note that this also works on a file containing multiple keys, such as `~/.ssh/authorized_keys`. – slhck Nov 20 '18 at 09:53
  • @QuaziIrfan the fingerprint is the output of the "ssh-keygen -l" output, which is to show fingerprint of the given pub/pri key file – Devy Apr 18 '19 at 18:10
  • Note that ssh-keygen will also accept options before ssh-xxx (as in authorized_keys), which can potentially be dangerous: command="xxx", ... – Jacopo Jun 19 '20 at 19:11
  • The `[-E fingerprint_hash]` option is also useful if you want something other than the default, e.g. `-E md5` or `-E sha512` – Amory Sep 19 '20 at 20:23