github.com/opentofu/opentofu@v1.7.1/internal/encryption/keyprovider/pbkdf2/example_decrypt_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  	"fmt"
    10  
    11  	"github.com/hashicorp/hcl/v2/gohcl"
    12  	"github.com/opentofu/opentofu/internal/encryption/keyprovider/pbkdf2"
    13  
    14  	"github.com/opentofu/opentofu/internal/encryption/config"
    15  )
    16  
    17  var configuration = `key_provider "pbkdf2" "foo" {
    18    passphrase = "correct-horse-battery-staple"
    19  }
    20  `
    21  
    22  // This example is a bare-bones configuration for a static key provider.
    23  // It is mainly intended to demonstrate how you can use parse configuration
    24  // and construct a static key provider from it.
    25  func Example_decrypt() {
    26  	configStruct := pbkdf2.New().ConfigStruct()
    27  
    28  	// Parse the config:
    29  	parsedConfig, diags := config.LoadConfigFromString("config.hcl", configuration)
    30  	if diags.HasErrors() {
    31  		panic(diags)
    32  	}
    33  
    34  	// Use gohcl to parse the hcl block from parsedConfig into the static configuration struct:
    35  	if err := gohcl.DecodeBody(
    36  		parsedConfig.KeyProviderConfigs[0].Body,
    37  		nil,
    38  		configStruct,
    39  	); err != nil {
    40  		panic(err)
    41  	}
    42  
    43  	// Create the actual key provider.
    44  	keyProvider, keyMeta, err := configStruct.Build()
    45  	if err != nil {
    46  		panic(err)
    47  	}
    48  
    49  	// Fill in the metadata stored with the encrypted form:
    50  	meta := keyMeta.(*pbkdf2.Metadata)
    51  	meta.Salt = []byte{0x10, 0xec, 0x3d, 0x3f, 0xe0, 0x2a, 0xd2, 0xbe, 0xe6, 0xf1, 0xf5, 0x54, 0xf, 0x8e, 0x6b, 0xbe, 0x3b, 0x8b, 0x29, 0x44, 0x5c, 0xf5, 0x2, 0xd2, 0x7d, 0x47, 0xad, 0x55, 0x4a, 0xa8, 0x97, 0x1f}
    52  	meta.Iterations = 600000
    53  	meta.HashFunction = "sha512"
    54  	meta.KeyLength = 32
    55  
    56  	// Get decryption key from the provider.
    57  	keys, _, err := keyProvider.Provide(meta)
    58  	if err != nil {
    59  		panic(err)
    60  	}
    61  
    62  	fmt.Printf("%x", keys.DecryptionKey)
    63  	// Output: 225872367198760137e0a18580433447bbf578fbe2b87ff36aef3c175fe5709c
    64  }