github.com/rahart/packer@v0.12.2-0.20161229105310-282bb6ad370f/builder/googlecompute/private_key.go (about)

     1  package googlecompute
     2  
     3  import (
     4  	"crypto/x509"
     5  	"encoding/pem"
     6  	"errors"
     7  	"fmt"
     8  	"io/ioutil"
     9  )
    10  
    11  // processPrivateKeyFile takes a private key file and an optional passphrase
    12  // and decodes it to a byte slice.
    13  func processPrivateKeyFile(privateKeyFile, passphrase string) ([]byte, error) {
    14  	rawPrivateKeyBytes, err := ioutil.ReadFile(privateKeyFile)
    15  	if err != nil {
    16  		return nil, fmt.Errorf("Failed loading private key file: %s", err)
    17  	}
    18  
    19  	PEMBlock, _ := pem.Decode(rawPrivateKeyBytes)
    20  	if PEMBlock == nil {
    21  		return nil, fmt.Errorf(
    22  			"%s does not contain a vaild private key", privateKeyFile)
    23  	}
    24  
    25  	if x509.IsEncryptedPEMBlock(PEMBlock) {
    26  		if passphrase == "" {
    27  			return nil, errors.New("a passphrase must be specified when using an encrypted private key")
    28  		}
    29  
    30  		decryptedPrivateKeyBytes, err := x509.DecryptPEMBlock(PEMBlock, []byte(passphrase))
    31  		if err != nil {
    32  			return nil, fmt.Errorf("Failed decrypting private key: %s", err)
    33  		}
    34  
    35  		b := &pem.Block{
    36  			Type:  "RSA PRIVATE KEY",
    37  			Bytes: decryptedPrivateKeyBytes,
    38  		}
    39  		return pem.EncodeToMemory(b), nil
    40  	}
    41  
    42  	return rawPrivateKeyBytes, nil
    43  }