github.com/opentofu/opentofu@v1.7.1/internal/encryption/keyprovider/static/example_test.go (about)

     1  // Copyright (c) The OpenTofu Authors
     2  // SPDX-License-Identifier: MPL-2.0
     3  // Copyright (c) 2023 HashiCorp, Inc.
     4  // SPDX-License-Identifier: MPL-2.0
     5  
     6  package static_test
     7  
     8  import (
     9  	"fmt"
    10  	"strings"
    11  
    12  	"github.com/opentofu/opentofu/internal/encryption"
    13  	"github.com/opentofu/opentofu/internal/encryption/config"
    14  	"github.com/opentofu/opentofu/internal/encryption/keyprovider/static"
    15  	"github.com/opentofu/opentofu/internal/encryption/method/aesgcm"
    16  	"github.com/opentofu/opentofu/internal/encryption/registry/lockingencryptionregistry"
    17  )
    18  
    19  var hclConfig = `key_provider "static" "foo" {
    20    key = "6f6f706830656f67686f6834616872756f3751756165686565796f6f72653169"
    21  }
    22  
    23  method "aes_gcm" "bar" {
    24    keys = key_provider.static.foo
    25  }
    26  
    27  plan {
    28    method = method.aes_gcm.bar
    29  }
    30  `
    31  
    32  // Example is a full end-to-end example of encrypting and decrypting a plan file.
    33  func Example() {
    34  	registry := lockingencryptionregistry.New()
    35  	if err := registry.RegisterKeyProvider(static.New()); err != nil {
    36  		panic(err)
    37  	}
    38  	if err := registry.RegisterMethod(aesgcm.New()); err != nil {
    39  		panic(err)
    40  	}
    41  
    42  	cfg, diags := config.LoadConfigFromString("test.hcl", hclConfig)
    43  	if diags.HasErrors() {
    44  		panic(diags)
    45  	}
    46  
    47  	enc, diags := encryption.New(registry, cfg)
    48  	if diags.HasErrors() {
    49  		panic(diags)
    50  	}
    51  
    52  	encryptor := enc.Plan()
    53  
    54  	encryptedPlan, err := encryptor.EncryptPlan([]byte("Hello world!"))
    55  	if err != nil {
    56  		panic(err)
    57  	}
    58  	if strings.Contains(string(encryptedPlan), "Hello world!") {
    59  		panic("The plan was not encrypted!")
    60  	}
    61  	decryptedPlan, err := encryptor.DecryptPlan(encryptedPlan)
    62  	if err != nil {
    63  		panic(err)
    64  	}
    65  	fmt.Printf("%s", decryptedPlan)
    66  	// Output: Hello world!
    67  }