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 golang.org/x/crypto/ssh 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

fmt.Println(string(hostKey.Marshal()))

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 {
	log.Fatal(err)
}
defer file.Close()

scanner := bufio.NewScanner(file)
var hostKey ssh.PublicKey
for scanner.Scan() {
	fields := strings.Split(scanner.Text(), " ")
	if len(fields) != 3 {
		continue
	}
	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)
		}
		break
	}
}

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

return hostKey
}

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

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

fmt.Println(string(hostKey.Marshal()))

// ssh client config
config := &ssh.ClientConfig{
	User: user,
	Auth: []ssh.AuthMethod{
		ssh.Password(pass),
	},
	// 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{
		ssh.KeyAlgoRSA,
		ssh.KeyAlgoDSA,
		ssh.KeyAlgoECDSA256,
		ssh.KeyAlgoECDSA384,
		ssh.KeyAlgoECDSA521,
		ssh.KeyAlgoED25519,
	},
	// optional tcp connect timeout
	Timeout: 5 * time.Second,
}

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

// start session
sess, err := client.NewSession()
if err != nil {
	log.Fatal(err)
}
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 {
	log.Fatal(err)
}
}

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