github.com/opentofu/opentofu@v1.7.1/internal/encryption/keyprovider/pbkdf2/example_metadata_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 pbkdf2_test
     7  
     8  import (
     9  	"bytes"
    10  	"fmt"
    11  
    12  	"github.com/hashicorp/hcl/v2/gohcl"
    13  	"github.com/opentofu/opentofu/internal/encryption/config"
    14  	"github.com/opentofu/opentofu/internal/encryption/keyprovider/pbkdf2"
    15  )
    16  
    17  var metadataExampleConfiguration = `key_provider "pbkdf2" "foo" {
    18    passphrase = "correct-horse-battery-staple"
    19  }
    20  `
    21  
    22  func ExampleMetadata() {
    23  	configStruct := pbkdf2.New().ConfigStruct()
    24  
    25  	// Parse the config:
    26  	parsedConfig, diags := config.LoadConfigFromString("config.hcl", metadataExampleConfiguration)
    27  	if diags.HasErrors() {
    28  		panic(diags)
    29  	}
    30  
    31  	// Use gohcl to parse the hcl block from parsedConfig into the static configuration struct:
    32  	if err := gohcl.DecodeBody(
    33  		parsedConfig.KeyProviderConfigs[0].Body,
    34  		nil,
    35  		configStruct,
    36  	); err != nil {
    37  		panic(err)
    38  	}
    39  
    40  	// Create the actual key provider.
    41  	keyProvider, keyMeta, err := configStruct.Build()
    42  	if err != nil {
    43  		panic(err)
    44  	}
    45  
    46  	// The first time around, let's get an encryption key:
    47  	oldKeys, oldMeta, err := keyProvider.Provide(keyMeta)
    48  	if err != nil {
    49  		panic(err)
    50  	}
    51  
    52  	// The second time, you can pass in the metadata from the previous encryption:
    53  	newKeys, _, err := keyProvider.Provide(oldMeta)
    54  	if err != nil {
    55  		panic(err)
    56  	}
    57  
    58  	// The old encryption and new decryption key will be the same:
    59  	if bytes.Equal(oldKeys.EncryptionKey, newKeys.DecryptionKey) {
    60  		fmt.Println("The keys match!")
    61  	}
    62  	//Output: The keys match!
    63  }