-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathssh.go
81 lines (64 loc) · 1.45 KB
/
ssh.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
package ssh
import (
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
"encoding/pem"
"github.com/alexfalkowski/go-service/crypto/algo"
"github.com/alexfalkowski/go-service/crypto/errors"
"golang.org/x/crypto/ssh"
)
// Generate key pair with ssh.
func Generate() (string, string, error) {
pu, pr, err := ed25519.GenerateKey(rand.Reader)
if err != nil {
return "", "", err
}
ppr, err := ssh.MarshalPrivateKey(pr, "")
if err != nil {
return "", "", err
}
pub, err := ssh.NewPublicKey(pu)
if err != nil {
return "", "", err
}
return string(ssh.MarshalAuthorizedKey(pub)), string(pem.EncodeToMemory(ppr)), nil
}
// Algo for ssh.
type Algo interface {
algo.Signer
}
// NewAlgo for ssh.
func NewAlgo(cfg *Config) (Algo, error) {
if !IsEnabled(cfg) {
return &algo.NoSigner{}, nil
}
pub, err := cfg.PublicKey()
if err != nil {
return nil, err
}
pri, err := cfg.PrivateKey()
if err != nil {
return nil, err
}
return &sshAlgo{publicKey: pub, privateKey: pri}, nil
}
type sshAlgo struct {
publicKey ed25519.PublicKey
privateKey ed25519.PrivateKey
}
func (a *sshAlgo) Sign(msg string) (string, error) {
m := ed25519.Sign(a.privateKey, []byte(msg))
return base64.StdEncoding.EncodeToString(m), nil
}
func (a *sshAlgo) Verify(sig, msg string) error {
d, err := base64.StdEncoding.DecodeString(sig)
if err != nil {
return err
}
ok := ed25519.Verify(a.publicKey, []byte(msg), d)
if !ok {
return errors.ErrMismatch
}
return nil
}