-
Notifications
You must be signed in to change notification settings - Fork 1
/
crypto.go
67 lines (51 loc) · 1.5 KB
/
crypto.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
package befehl
import (
"crypto/x509"
"encoding/pem"
"fmt"
"golang.org/x/crypto/ssh"
"github.com/howeyc/gopass"
"github.com/sgsullivan/befehl/helpers/filesystem"
)
func (instance *Instance) populateSshKeyEncrypted(privKeyBytes *pem.Block) error {
fmt.Printf("enter private key password: ")
password, err := gopass.GetPasswd()
if err != nil {
return fmt.Errorf("error when reading input: %v", err)
}
pwBuf, err := x509.DecryptPEMBlock(privKeyBytes, []byte(password))
if err != nil {
return fmt.Errorf("x509.DecryptPEMBlock failed: %v", err)
}
pk, err := x509.ParsePKCS1PrivateKey(pwBuf)
if err != nil {
return fmt.Errorf("x509.ParsePKCS1PrivateKey failed: %v", err)
}
signer, err := ssh.NewSignerFromKey(pk)
if err != nil {
return fmt.Errorf("ssh.NewSignerFromKey failed: %v", err)
}
instance.sshKey = signer
return nil
}
func (instance *Instance) populateSshKeyUnencrypted(rawKey []byte) error {
signer, err := ssh.ParsePrivateKey(rawKey)
if err != nil {
return fmt.Errorf("unable to parse private key: %v", err)
}
instance.sshKey = signer
return nil
}
func (instance *Instance) populateSshKey() error {
privKeyFile := instance.getPrivKeyFile()
if rawKey, readFileError := filesystem.ReadFile(privKeyFile); readFileError == nil {
privKeyBytes, _ := pem.Decode(rawKey)
if x509.IsEncryptedPEMBlock(privKeyBytes) {
return instance.populateSshKeyEncrypted(privKeyBytes)
} else {
return instance.populateSshKeyUnencrypted(rawKey)
}
} else {
return readFileError
}
}