|
8 | 8 | package utils |
9 | 9 |
|
10 | 10 | import ( |
| 11 | + "crypto/md5" |
11 | 12 | "errors" |
12 | 13 | "fmt" |
13 | 14 | "io" |
14 | | - "io/ioutil" |
15 | 15 | "net" |
16 | 16 | "os" |
17 | 17 | "os/exec" |
18 | 18 | "path" |
19 | 19 | "path/filepath" |
| 20 | + "reflect" |
20 | 21 | "regexp" |
21 | 22 | "strings" |
22 | 23 | "time" |
23 | 24 |
|
| 25 | + "golang.org/x/crypto/ssh" |
| 26 | + |
24 | 27 | "github.com/scaleway/scaleway-cli/pkg/sshcommand" |
25 | 28 | "github.com/scaleway/scaleway-cli/vendor/github.com/Sirupsen/logrus" |
26 | 29 | log "github.com/scaleway/scaleway-cli/vendor/github.com/Sirupsen/logrus" |
@@ -213,25 +216,29 @@ func AttachToSerial(serverID string, apiToken string) (*gottyclient.Client, chan |
213 | 216 | return gottycli, done, nil |
214 | 217 | } |
215 | 218 |
|
216 | | -// SSHGetFingerprint returns the fingerprint of an SSH key |
217 | | -func SSHGetFingerprint(key string) (string, error) { |
218 | | - tmp, err := ioutil.TempFile("", ".tmp") |
219 | | - if err != nil { |
220 | | - return "", fmt.Errorf("Unable to create a tempory file: %v", err) |
221 | | - } |
222 | | - defer os.Remove(tmp.Name()) |
223 | | - buff := []byte(key) |
224 | | - bytesWritten := 0 |
225 | | - for bytesWritten < len(buff) { |
226 | | - nb, err := tmp.Write(buff[bytesWritten:]) |
227 | | - if err != nil { |
228 | | - return "", fmt.Errorf("Unable to write: %v", err) |
| 219 | +func rfc4716hex(data []byte) string { |
| 220 | + fingerprint := "" |
| 221 | + |
| 222 | + for i := 0; i < len(data); i++ { |
| 223 | + fingerprint = fmt.Sprintf("%s%0.2x", fingerprint, data[i]) |
| 224 | + if i != len(data)-1 { |
| 225 | + fingerprint = fingerprint + ":" |
229 | 226 | } |
230 | | - bytesWritten += nb |
231 | 227 | } |
232 | | - ret, err := exec.Command("ssh-keygen", "-l", "-f", tmp.Name()).Output() |
| 228 | + return fingerprint |
| 229 | +} |
| 230 | + |
| 231 | +// SSHGetFingerprint returns the fingerprint of an SSH key |
| 232 | +func SSHGetFingerprint(key []byte) (string, error) { |
| 233 | + publicKey, comment, _, _, err := ssh.ParseAuthorizedKey(key) |
233 | 234 | if err != nil { |
234 | | - return "", fmt.Errorf("Unable to run ssh-keygen: %v", err) |
| 235 | + return "", err |
| 236 | + } |
| 237 | + switch reflect.TypeOf(publicKey).String() { |
| 238 | + case "*ssh.rsaPublicKey", "*ssh.dsaPublicKey", "*ssh.ecdsaPublicKey": |
| 239 | + md5sum := md5.Sum(publicKey.Marshal()) |
| 240 | + return publicKey.Type() + " " + rfc4716hex(md5sum[:]) + " " + comment, nil |
| 241 | + default: |
| 242 | + return "", errors.New("Can't handle this key") |
235 | 243 | } |
236 | | - return string(ret), nil |
237 | 244 | } |
0 commit comments