-
Notifications
You must be signed in to change notification settings - Fork 7
/
keyring.go
58 lines (50 loc) · 1.01 KB
/
keyring.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
package main
import (
"crypto/rand"
"crypto/rsa"
"errors"
"io"
"golang.org/x/crypto/ssh"
)
func MakeKey() (ssh.Signer, error) {
key, err := rsa.GenerateKey(rand.Reader, 2014)
if err != nil {
return nil, err
}
return ssh.NewSignerFromKey(key)
}
type Keyring struct {
keys []ssh.Signer
}
func (r *Keyring) Key(i int) (ssh.PublicKey, error) {
if i >= len(r.keys) {
return nil, nil
}
return r.keys[i].PublicKey(), nil
}
func (r *Keyring) Sign(i int, rand io.Reader, data []byte) ([]byte, error) {
if i >= len(r.keys) {
return nil, errors.New("Keyring: Invalid key index")
}
sig, err := r.keys[i].Sign(rand, data)
if err != nil {
return nil, err
}
return sig.Blob, nil
}
func (r *Keyring) Add(key ssh.Signer) {
r.keys = append(r.keys, key)
}
// Make keyring with num random keys in it.
func NewKeyring(num int) *Keyring {
r := Keyring{}
for i := 0; i < num; i++ {
key, err := MakeKey()
if err != nil {
logger.Errorf("Failed to make key: %s", err)
return &r
}
r.Add(key)
}
return &r
}