Ssh – How to decrypt hostnames of a crypted .ssh/known_hosts with a list of the hostnames

encryptionhostnamesshssh-keygen

I try to find a script to decrypt (unhash) the ssh hostnames in the known_hosts file by passing a list of the hostnamses.

So, to do exactly the reverse of:

ssh-keygen -H -f known_hosts

Or also, to do the same as this if the ssh config HashKnownHosts is set to No:

ssh-keygen -R know-host.com -f known_hosts
ssh-keyscan -H know-host.com >> known_hosts

But without re-downloading the host key (caused by ssh-keyscan).

Something like:

ssh-keygen --decrypt -f known_hosts --hostnames hostnames.txt

Where hostnames.txt contains a list of hostnames.

Best Answer

Lines in the known_hosts file are not encrypted, they are hashed. You can't decrypt them, because they're not encrypted. You can't “unhash” them, because that what a hash is all about — given the hash, it's impossible¹ to discover the original string. The only way to “unhash” is to guess the original string and verify your guess.

If you have a list of host names, you can pass them to ssh-keygen -F and replace them by the host name.

while read host comment; do
  found=$(ssh-keygen -F "$host" | grep -v '^#' | sed "s/^[^ ]*/$host/")
  if [ -n "$found" ]; then
    ssh-keygen -R "$host"
    echo "$found" >>~/.ssh/known_hosts
  fi
done <hostnames.txt

¹ In a practical sense, i.e. it would take all the computers existing today longer than the present age of the universe to do it.