2016-03-04 05:14:55 -05:00
|
|
|
// Copyright (c) Microsoft Corporation. All rights reserved.
|
2016-04-21 19:50:03 -04:00
|
|
|
// Licensed under the MIT License. See the LICENSE file in the project root for license information.
|
2016-03-04 05:14:55 -05:00
|
|
|
|
|
|
|
package arm
|
|
|
|
|
|
|
|
import (
|
|
|
|
"crypto/rand"
|
|
|
|
"crypto/rsa"
|
|
|
|
"crypto/x509"
|
|
|
|
"encoding/base64"
|
|
|
|
"encoding/pem"
|
|
|
|
"fmt"
|
2016-03-10 20:46:22 -05:00
|
|
|
"golang.org/x/crypto/ssh"
|
2016-04-21 19:50:03 -04:00
|
|
|
"time"
|
2016-03-04 05:14:55 -05:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
KeySize = 2048
|
|
|
|
)
|
|
|
|
|
|
|
|
type OpenSshKeyPair struct {
|
|
|
|
privateKey *rsa.PrivateKey
|
|
|
|
publicKey ssh.PublicKey
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewOpenSshKeyPair() (*OpenSshKeyPair, error) {
|
|
|
|
return NewOpenSshKeyPairWithSize(KeySize)
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewOpenSshKeyPairWithSize(keySize int) (*OpenSshKeyPair, error) {
|
|
|
|
privateKey, err := rsa.GenerateKey(rand.Reader, keySize)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
publicKey, err := ssh.NewPublicKey(&privateKey.PublicKey)
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &OpenSshKeyPair{
|
|
|
|
privateKey: privateKey,
|
|
|
|
publicKey: publicKey,
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *OpenSshKeyPair) AuthorizedKey() string {
|
|
|
|
return fmt.Sprintf("%s %s packer Azure Deployment%s",
|
|
|
|
s.publicKey.Type(),
|
|
|
|
base64.StdEncoding.EncodeToString(s.publicKey.Marshal()),
|
|
|
|
time.Now().Format(time.RFC3339))
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *OpenSshKeyPair) PrivateKey() string {
|
|
|
|
privateKey := string(pem.EncodeToMemory(&pem.Block{
|
|
|
|
Type: "RSA PRIVATE KEY",
|
|
|
|
Bytes: x509.MarshalPKCS1PrivateKey(s.privateKey),
|
|
|
|
}))
|
|
|
|
|
|
|
|
return privateKey
|
|
|
|
}
|