The ssh key golang package does not match, although the key is correct

Hello, could you help me figure out what is the reason for the key mismatch, I use the package, when executing the code, it displays
ssh: handshake failed: ssh: host key mismatch
rechecked the key files of the host and the ssh server and also connects through the terminal without problems.

I checked what the getHostKey () function returns to me, as it turned out, converting from byte to string


it displayed to me:
ecdsa-sha2-nistp25nistp256A- “T�.��2l�IR�” �mDĄ���F���7dɇ� # a��: ���YP�9��
��-I ^ �c�
possibly due to the fact that the key is not displayed in the correct encoding and therefore does not match, if so how to fix it

here is the full code:

func getHostKey(host string) ssh.PublicKey {
// parse OpenSSH known_hosts file
// ssh or use ssh-keyscan to get initial key
file, err := os.Open(filepath.Join(os.Getenv("HOME"), ".ssh", "known_hosts"))
if err != nil {
defer file.Close()

scanner := bufio.NewScanner(file)
var hostKey ssh.PublicKey
for scanner.Scan() {
	fields := strings.Split(scanner.Text(), " ")
	if len(fields) != 3 {
	if strings.Contains(fields[0], host) {

		var err error

		hostKey, _, _, _, err = ssh.ParseAuthorizedKey(scanner.Bytes())
		if err != nil {
			log.Fatalf("error parsing %q: %v", fields[2], err)

if hostKey == nil {
	log.Fatalf("no hostkey found for %s", host)

return hostKey

func main() {
host := ""
port := "22"
user := "n0kk"
pass := "password"
cmd := "ps"

// get host public key
hostKey := getHostKey(host)


// ssh client config
config := &ssh.ClientConfig{
	User: user,
	Auth: []ssh.AuthMethod{
	// allow any host key to be used (non-prod)
	// HostKeyCallback: ssh.InsecureIgnoreHostKey(),

	// verify host public key
	HostKeyCallback: ssh.FixedHostKey(hostKey),
	// optional host key algo list
	HostKeyAlgorithms: []string{
	// optional tcp connect timeout
	Timeout: 5 * time.Second,

// connect
client, err := ssh.Dial("tcp", host+":"+port, config)
if err != nil {
defer client.Close()

// start session
sess, err := client.NewSession()
if err != nil {
defer sess.Close()

// setup standard out and error
// uses writer interface
sess.Stdout = os.Stdout
sess.Stderr = os.Stderr

// run single command
err = sess.Run(cmd)
if err != nil {

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.