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