github.com/kikitux/packer@v0.10.1-0.20160322154024-6237df566f9f/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 "time" 14 15 "golang.org/x/crypto/ssh" 16 ) 17 18 const ( 19 KeySize = 2048 20 ) 21 22 type OpenSshKeyPair struct { 23 privateKey *rsa.PrivateKey 24 publicKey ssh.PublicKey 25 } 26 27 func NewOpenSshKeyPair() (*OpenSshKeyPair, error) { 28 return NewOpenSshKeyPairWithSize(KeySize) 29 } 30 31 func NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) { 32 privateKey, err := rsa.GenerateKey(rand.Reader, keySize) 33 if err != nil { 34 return nil, err 35 } 36 37 publicKey, err := ssh.NewPublicKey(&privateKey.PublicKey) 38 if err != nil { 39 return nil, err 40 } 41 42 return &OpenSshKeyPair{ 43 privateKey: privateKey, 44 publicKey: publicKey, 45 }, nil 46 } 47 48 func (s *OpenSshKeyPair) AuthorizedKey() string { 49 return fmt.Sprintf("%s %s packer Azure Deployment%s", 50 s.publicKey.Type(), 51 base64.StdEncoding.EncodeToString(s.publicKey.Marshal()), 52 time.Now().Format(time.RFC3339)) 53 } 54 55 func (s *OpenSshKeyPair) PrivateKey() string { 56 privateKey := string(pem.EncodeToMemory(&pem.Block{ 57 Type: "RSA PRIVATE KEY", 58 Bytes: x509.MarshalPKCS1PrivateKey(s.privateKey), 59 })) 60 61 return privateKey 62 }