Skip to content

Add automatically ssh_keyGen #3

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 42 additions & 2 deletions examples/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ import (
"io/ioutil"
"net"

"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"

"github.com/Unknwon/com"
"github.com/dutchcoders/sshproxy"
"golang.org/x/crypto/ssh"
)
Expand All @@ -17,9 +23,10 @@ func main() {
key := flag.String("key", "conf/id_rsa", "rsa key to use")
flag.Parse()

privateBytes, err := ioutil.ReadFile(*key)
path := *key
privateBytes, err := ssh_keyGen(path)
if err != nil {
panic("Failed to load private key")
panic(err)
}

private, err := ssh.ParsePrivateKey(privateBytes)
Expand Down Expand Up @@ -70,3 +77,36 @@ func main() {
return nil
})
}

func ssh_keyGen(keyPath string) ([]byte, error) {
var privateBytes []byte
var err error
if !com.IsExist(keyPath) {
priv, err := rsa.GenerateKey(rand.Reader, 2014)
if err != nil {
fmt.Println(err)
return privateBytes, err
}
err = priv.Validate()
if err != nil {
fmt.Println("Validation failed.", err)
return privateBytes, err
}

priv_der := x509.MarshalPKCS1PrivateKey(priv)

priv_blk := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: priv_der,
}

privateBytes = pem.EncodeToMemory(&priv_blk)
return privateBytes, err
}

if privateBytes, err = ioutil.ReadFile(keyPath); err != nil {
panic("Failed to load private key")
}
return privateBytes, err
}