1//
2// Copyright (c) 2018, Joyent, Inc. All rights reserved.
3//
4// This Source Code Form is subject to the terms of the Mozilla Public
5// License, v. 2.0. If a copy of the MPL was not distributed with this
6// file, You can obtain one at http://mozilla.org/MPL/2.0/.
7//
8
9package authentication
10
11import (
12	"crypto/md5"
13	"fmt"
14	"strings"
15
16	"golang.org/x/crypto/ssh"
17)
18
19// formatPublicKeyFingerprint produces the MD5 fingerprint of the given SSH
20// public key. If display is true, the fingerprint is formatted with colons
21// between each byte, as per the output of OpenSSL.
22func formatPublicKeyFingerprint(key ssh.PublicKey, display bool) string {
23	publicKeyFingerprint := md5.New()
24	publicKeyFingerprint.Write(key.Marshal())
25	publicKeyFingerprintString := fmt.Sprintf("%x", publicKeyFingerprint.Sum(nil))
26
27	if !display {
28		return publicKeyFingerprintString
29	}
30
31	formatted := ""
32	for i := 0; i < len(publicKeyFingerprintString); i = i + 2 {
33		formatted = fmt.Sprintf("%s%s:", formatted, publicKeyFingerprintString[i:i+2])
34	}
35
36	return strings.TrimSuffix(formatted, ":")
37}
38