-
Notifications
You must be signed in to change notification settings - Fork 64
/
keys.go
83 lines (69 loc) 路 1.95 KB
/
keys.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package charm
import (
"crypto/sha256"
"encoding/base64"
"errors"
"fmt"
"strings"
"time"
"github.com/calmh/randomart"
"github.com/charmbracelet/charm/ui/common"
)
// ErrMalformedKey parsing error for bad ssh key.
var ErrMalformedKey = errors.New("malformed key; is it missing the algorithm type at the beginning?")
// Fingerprint is the fingerprint of an SSH key.
type Fingerprint struct {
Algorithm string
Type string
Value string
}
// String outputs a string representation of the fingerprint.
func (f Fingerprint) String() string {
return fmt.Sprintf(
"%s %s",
common.SubtleIndigoFg(strings.ToUpper(f.Algorithm)),
common.IndigoFg(f.Type+":"+f.Value),
)
}
// Key contains data and metadata for an SSH key.
type Key struct {
Key string `json:"key"`
CreatedAt *time.Time `json:"created_at,omitempty"`
}
// FingerprintSHA256 returns the algorithm and SHA256 fingerprint for the given
// key.
func (k Key) FingerprintSHA256() (Fingerprint, error) {
keyParts := strings.Split(k.Key, " ")
if len(keyParts) != 2 {
return Fingerprint{}, ErrMalformedKey
}
b, err := base64.StdEncoding.DecodeString(keyParts[1])
if err != nil {
return Fingerprint{}, err
}
algo := strings.Replace(keyParts[0], "ssh-", "", -1)
sha256sum := sha256.Sum256(b)
hash := base64.RawStdEncoding.EncodeToString(sha256sum[:])
return Fingerprint{
Algorithm: algo,
Type: "SHA256",
Value: hash,
}, nil
}
// RandomArt returns the randomart for the given key.
func (k Key) RandomArt() (string, error) {
keyParts := strings.Split(k.Key, " ")
if len(keyParts) != 2 {
return "", ErrMalformedKey
}
b, err := base64.StdEncoding.DecodeString(keyParts[1])
if err != nil {
return "", err
}
algo := strings.ToUpper(strings.Replace(keyParts[0], "ssh-", "", -1))
// TODO: also add bit size of key
h := sha256.New()
_, _ = h.Write(b)
board := randomart.GenerateSubtitled(h.Sum(nil), algo, "SHA256").String()
return strings.TrimSpace(board), nil
}