-
Notifications
You must be signed in to change notification settings - Fork 1
/
key.go
51 lines (48 loc) · 1.15 KB
/
key.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
package sshtest
import (
"bytes"
"encoding/base64"
"io/ioutil"
"golang.org/x/crypto/ssh"
)
// KeyFromFile reads a private key and optionally a certificate file in
// OpenSSH format and returns an ssh.Signer. If crtfile is not the empty
// string, the Signer will be using the SSH certificate from it.
func KeyFromFile(keyfile, crtfile string) ssh.Signer {
b, err := ioutil.ReadFile(keyfile)
if err != nil {
panic(err)
}
key, err := ssh.ParsePrivateKey(b)
if err != nil {
panic(err)
}
// If a certificate is provided as well, extend the ssh.Signer with a it
if crtfile != "" {
b, err := ioutil.ReadFile(crtfile)
if err != nil {
panic(err)
}
parts := bytes.SplitN(b, []byte(" "), 3)
if len(parts) < 2 {
panic("public key or certificate not in OpenSSH format")
}
decoded, err := base64.StdEncoding.DecodeString(string(parts[1]))
if err != nil {
panic(err)
}
pub, err := ssh.ParsePublicKey(decoded)
if err != nil {
panic(err)
}
crt, ok := pub.(*ssh.Certificate)
if !ok {
panic("public key file is not a certificate")
}
key, err = ssh.NewCertSigner(crt, key)
if err != nil {
panic(err)
}
}
return key
}