github.phpd.cn/hashicorp/packer@v1.3.2/builder/azure/arm/openssh_key_pair.go (about)

     1  package arm
     2  
     3  import (
     4  	"crypto/rand"
     5  	"crypto/rsa"
     6  	"crypto/x509"
     7  	"encoding/base64"
     8  	"encoding/pem"
     9  	"fmt"
    10  	"time"
    11  
    12  	"golang.org/x/crypto/ssh"
    13  )
    14  
    15  const (
    16  	KeySize = 2048
    17  )
    18  
    19  type OpenSshKeyPair struct {
    20  	privateKey *rsa.PrivateKey
    21  	publicKey  ssh.PublicKey
    22  }
    23  
    24  func NewOpenSshKeyPair() (*OpenSshKeyPair, error) {
    25  	return NewOpenSshKeyPairWithSize(KeySize)
    26  }
    27  
    28  func NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) {
    29  	privateKey, err := rsa.GenerateKey(rand.Reader, keySize)
    30  	if err != nil {
    31  		return nil, err
    32  	}
    33  
    34  	publicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)
    35  	if err != nil {
    36  		return nil, err
    37  	}
    38  
    39  	return &OpenSshKeyPair{
    40  		privateKey: privateKey,
    41  		publicKey:  publicKey,
    42  	}, nil
    43  }
    44  
    45  func (s *OpenSshKeyPair) AuthorizedKey() string {
    46  	return fmt.Sprintf("%s %s packer Azure Deployment%s",
    47  		s.publicKey.Type(),
    48  		base64.StdEncoding.EncodeToString(s.publicKey.Marshal()),
    49  		time.Now().Format(time.RFC3339))
    50  }
    51  
    52  func (s *OpenSshKeyPair) PrivateKey() []byte {
    53  	privateKey := pem.EncodeToMemory(&pem.Block{
    54  		Type:  "RSA PRIVATE KEY",
    55  		Bytes: x509.MarshalPKCS1PrivateKey(s.privateKey),
    56  	})
    57  
    58  	return privateKey
    59  }