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