github.com/Hashicorp/terraform@v0.11.12-beta1/helper/encryption/encryption.go (about)

     1  package encryption
     2  
     3  import (
     4  	"encoding/base64"
     5  	"fmt"
     6  	"strings"
     7  
     8  	"github.com/hashicorp/errwrap"
     9  	"github.com/hashicorp/vault/helper/pgpkeys"
    10  )
    11  
    12  // RetrieveGPGKey returns the PGP key specified as the pgpKey parameter, or queries
    13  // the public key from the keybase service if the parameter is a keybase username
    14  // prefixed with the phrase "keybase:"
    15  func RetrieveGPGKey(pgpKey string) (string, error) {
    16  	const keybasePrefix = "keybase:"
    17  
    18  	encryptionKey := pgpKey
    19  	if strings.HasPrefix(pgpKey, keybasePrefix) {
    20  		publicKeys, err := pgpkeys.FetchKeybasePubkeys([]string{pgpKey})
    21  		if err != nil {
    22  			return "", errwrap.Wrapf(fmt.Sprintf("Error retrieving Public Key for %s: {{err}}", pgpKey), err)
    23  		}
    24  		encryptionKey = publicKeys[pgpKey]
    25  	}
    26  
    27  	return encryptionKey, nil
    28  }
    29  
    30  // EncryptValue encrypts the given value with the given encryption key. Description
    31  // should be set such that errors return a meaningful user-facing response.
    32  func EncryptValue(encryptionKey, value, description string) (string, string, error) {
    33  	fingerprints, encryptedValue, err :=
    34  		pgpkeys.EncryptShares([][]byte{[]byte(value)}, []string{encryptionKey})
    35  	if err != nil {
    36  		return "", "", errwrap.Wrapf(fmt.Sprintf("Error encrypting %s: {{err}}", description), err)
    37  	}
    38  
    39  	return fingerprints[0], base64.StdEncoding.EncodeToString(encryptedValue[0]), nil
    40  }