github.com/rahart/packer@v0.12.2-0.20161229105310-282bb6ad370f/builder/azure/arm/openssh_key_pair.go (about)

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