Skip to content

Commit 0c9c357

Browse files
belakprogrium
authored andcommitted
Switch to using gossh.ParsePrivateKey when reading PrivateKeys (#61)
Refs #56
1 parent 3eeacb7 commit 0c9c357

File tree

2 files changed

+18
-51
lines changed

2 files changed

+18
-51
lines changed

options.go

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
11
package ssh
22

3-
import "io/ioutil"
3+
import (
4+
"io/ioutil"
5+
6+
gossh "golang.org/x/crypto/ssh"
7+
)
48

59
// PasswordAuth returns a functional option that sets PasswordHandler on the server.
610
func PasswordAuth(fn PasswordHandler) Option {
@@ -26,13 +30,14 @@ func HostKeyFile(filepath string) Option {
2630
if err != nil {
2731
return err
2832
}
29-
for _, block := range decodePemBlocks(pemBytes) {
30-
signer, err := signerFromBlock(block)
31-
if err != nil {
32-
return err
33-
}
34-
srv.AddHostKey(signer)
33+
34+
signer, err := gossh.ParsePrivateKey(pemBytes)
35+
if err != nil {
36+
return err
3537
}
38+
39+
srv.AddHostKey(signer)
40+
3641
return nil
3742
}
3843
}
@@ -41,13 +46,13 @@ func HostKeyFile(filepath string) Option {
4146
// from a PEM file as bytes.
4247
func HostKeyPEM(bytes []byte) Option {
4348
return func(srv *Server) error {
44-
for _, block := range decodePemBlocks(bytes) {
45-
signer, err := signerFromBlock(block)
46-
if err != nil {
47-
return err
48-
}
49-
srv.AddHostKey(signer)
49+
signer, err := gossh.ParsePrivateKey(bytes)
50+
if err != nil {
51+
return err
5052
}
53+
54+
srv.AddHostKey(signer)
55+
5156
return nil
5257
}
5358
}

util.go

Lines changed: 0 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -3,49 +3,11 @@ package ssh
33
import (
44
"crypto/rand"
55
"crypto/rsa"
6-
"crypto/x509"
76
"encoding/binary"
8-
"encoding/pem"
9-
"fmt"
107

118
"golang.org/x/crypto/ssh"
129
)
1310

14-
func signerFromBlock(block *pem.Block) (ssh.Signer, error) {
15-
var key interface{}
16-
var err error
17-
switch block.Type {
18-
case "RSA PRIVATE KEY":
19-
key, err = x509.ParsePKCS1PrivateKey(block.Bytes)
20-
case "EC PRIVATE KEY":
21-
key, err = x509.ParseECPrivateKey(block.Bytes)
22-
case "DSA PRIVATE KEY":
23-
key, err = ssh.ParseDSAPrivateKey(block.Bytes)
24-
default:
25-
return nil, fmt.Errorf("unsupported key type %q", block.Type)
26-
}
27-
if err != nil {
28-
return nil, err
29-
}
30-
signer, err := ssh.NewSignerFromKey(key)
31-
if err != nil {
32-
return nil, err
33-
}
34-
return signer, nil
35-
}
36-
37-
func decodePemBlocks(pemData []byte) []*pem.Block {
38-
var blocks []*pem.Block
39-
var block *pem.Block
40-
for {
41-
block, pemData = pem.Decode(pemData)
42-
if block == nil {
43-
return blocks
44-
}
45-
blocks = append(blocks, block)
46-
}
47-
}
48-
4911
func generateSigner() (ssh.Signer, error) {
5012
key, err := rsa.GenerateKey(rand.Reader, 768)
5113
if err != nil {

0 commit comments

Comments
 (0)