github.com/cloudfoundry-attic/ltc@v0.0.0-20151123212628-098adc7919fc/ssh/keygen/keygen.go (about)

     1  package keygen
     2  
     3  import (
     4  	"crypto/rsa"
     5  	"crypto/x509"
     6  	"encoding/pem"
     7  	"io"
     8  
     9  	"golang.org/x/crypto/ssh"
    10  )
    11  
    12  type KeyGenerator struct {
    13  	RandReader io.Reader
    14  }
    15  
    16  func (k *KeyGenerator) GenerateRSAPrivateKey(bits int) (string, error) {
    17  	pk, err := rsa.GenerateKey(k.RandReader, bits)
    18  	if err != nil {
    19  		return "", err
    20  	}
    21  
    22  	return string(pem.EncodeToMemory(&pem.Block{
    23  		Type:  "RSA PRIVATE KEY",
    24  		Bytes: x509.MarshalPKCS1PrivateKey(pk),
    25  	})), nil
    26  }
    27  
    28  func (k *KeyGenerator) GenerateRSAKeyPair(bits int) (pemEncodedPrivateKey string, authorizedKey string, err error) {
    29  	privateKey, err := rsa.GenerateKey(k.RandReader, bits)
    30  	if err != nil {
    31  		return "", "", err
    32  	}
    33  
    34  	privateKeyBlock := &pem.Block{
    35  		Type:  "RSA PRIVATE KEY",
    36  		Bytes: x509.MarshalPKCS1PrivateKey(privateKey),
    37  	}
    38  
    39  	privatePEM := pem.EncodeToMemory(privateKeyBlock)
    40  
    41  	publicKey, err := ssh.NewPublicKey(privateKey.Public())
    42  	if err != nil {
    43  		return "", "", err
    44  	}
    45  
    46  	publicKeyBytes := ssh.MarshalAuthorizedKey(publicKey)
    47  	return string(privatePEM), string(publicKeyBytes[:len(publicKeyBytes)-1]), nil
    48  }