Skip to content

Instantly share code, notes, and snippets.

@nickvanw
Created October 21, 2015 20:49
Show Gist options
  • Save nickvanw/252d025cb04624002e85 to your computer and use it in GitHub Desktop.
Save nickvanw/252d025cb04624002e85 to your computer and use it in GitHub Desktop.
Generate SSH Keys
package whatever
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"fmt"
"golang.org/x/crypto/ssh"
)
type SSHKey struct {
RawKey *rsa.PrivateKey
PubKey string
PrivKey []byte
}
// NewSSHKey creates a new 2048-bit RSA key
func NewSSHKey() (*SSHKey, error) {
key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, err
}
pubKey, err := getPublicKey(key)
if err != nil {
return nil, err
}
privKey := getPrivateKey(key)
return &SSHKey{
RawKey: key,
PubKey: pubKey,
PrivKey: privKey,
}, nil
}
func getPublicKey(key *rsa.PrivateKey) (string, error) {
pubkey := key.Public()
pkey, err := ssh.NewPublicKey(pubkey)
if err != nil {
return "", err
}
d := string(base64.StdEncoding.EncodeToString(pkey.Marshal()))
fullkey := fmt.Sprintf("%s %s", pkey.Type(), d)
return fullkey, nil
}
func getPrivateKey(key *rsa.PrivateKey) []byte {
privateKeyDer := x509.MarshalPKCS1PrivateKey(key)
privateKeyBlock := pem.Block{
Type: "RSA PRIVATE KEY",
Headers: nil,
Bytes: privateKeyDer,
}
return pem.EncodeToMemory(&privateKeyBlock)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment