55package ssh
66
77import (
8+ "crypto/rand"
9+ "crypto/rsa"
10+ "crypto/x509"
11+ "encoding/pem"
812 "io"
913 "io/ioutil"
1014 "net"
@@ -176,9 +180,9 @@ func Listen(host string, port int, ciphers []string, keyExchanges []string, macs
176180 log .Error (4 , "Failed to create dir %s: %v" , filePath , err )
177181 }
178182
179- _ , stderr , err := com . ExecCmd ( "ssh-keygen" , "-f" , keyPath , "-t" , "rsa" , "-N" , "" )
183+ err := GenKeyPair ( keyPath )
180184 if err != nil {
181- log .Fatal (4 , "Failed to generate private key: %v - %s " , err , stderr )
185+ log .Fatal (4 , "Failed to generate private key: %v" , err )
182186 }
183187 log .Trace ("SSH: New private key is generateed: %s" , keyPath )
184188 }
@@ -195,3 +199,39 @@ func Listen(host string, port int, ciphers []string, keyExchanges []string, macs
195199
196200 go listen (config , host , port )
197201}
202+
203+ // GenKeyPair make a pair of public and private keys for SSH access.
204+ // Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
205+ // Private Key generated is PEM encoded
206+ func GenKeyPair (keyPath string ) error {
207+ privateKey , err := rsa .GenerateKey (rand .Reader , 2048 )
208+ if err != nil {
209+ return err
210+ }
211+
212+ privateKeyPEM := & pem.Block {Type : "RSA PRIVATE KEY" , Bytes : x509 .MarshalPKCS1PrivateKey (privateKey )}
213+ f , err := os .Create (keyPath )
214+ if err != nil {
215+ return err
216+ }
217+ defer f .Close ()
218+
219+ if err := pem .Encode (f , privateKeyPEM ); err != nil {
220+ return err
221+ }
222+
223+ // generate public key
224+ pub , err := ssh .NewPublicKey (& privateKey .PublicKey )
225+ if err != nil {
226+ return err
227+ }
228+
229+ public := ssh .MarshalAuthorizedKey (pub )
230+ p , err := os .Create (keyPath + ".pub" )
231+ if err != nil {
232+ return err
233+ }
234+ defer p .Close ()
235+ _ , err = p .Write (public )
236+ return err
237+ }
0 commit comments