Last active
March 26, 2023 20:52
-
-
Save Kunde21/3633e1e9ef0db82698b9ee1305a60cba to your computer and use it in GitHub Desktop.
Helper to generate ssh keys
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/x509" | |
"encoding/pem" | |
"flag" | |
"io/ioutil" | |
"log" | |
"path/filepath" | |
"golang.org/x/crypto/ssh" | |
) | |
func main() { | |
strength := flag.Int("bits", 2048, "key bit size to generate") | |
name := flag.String("name", "id_rsa", "file name for generated keys") | |
dir := flag.String("dir", ".", "destination directory for generated keys") | |
// Generate keys | |
pub, priv, err := GenerateSSHKeyPair(*strength) | |
if err != nil { | |
log.Fatal(err) | |
} | |
// Write keys to destination | |
keyFile := filepath.Join(*dir, *name) | |
err = ioutil.WriteFile(keyFile, priv, 0600) | |
if err != nil { | |
log.Fatal(err) | |
} | |
err = ioutil.WriteFile(keyFile+".pub", pub, 0644) | |
if err != nil { | |
log.Fatal(err) | |
} | |
log.Println(keyFile, "created.") | |
} | |
// GenerateSSHKeyPair creates a pair of keys (public + private) for SSH auth. | |
func GenerateSSHKeyPair(strength int) (pub, priv []byte, err error) { | |
privKey, err := rsa.GenerateKey(rand.Reader, strength) | |
if err != nil { | |
return nil, nil, err | |
} | |
privKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privKey)} | |
pubKey, err := ssh.NewPublicKey(&privKey.PublicKey) | |
if err != nil { | |
return nil, nil, err | |
} | |
return ssh.MarshalAuthorizedKey(pubKey), pem.EncodeToMemory(privKeyPEM), nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment