github.com/opentofu/opentofu@v1.7.1/internal/encryption/method/aesgcm/config.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 aesgcm
     7  
     8  import (
     9  	"fmt"
    10  
    11  	"github.com/opentofu/opentofu/internal/encryption/keyprovider"
    12  
    13  	"github.com/opentofu/opentofu/internal/collections"
    14  
    15  	"github.com/opentofu/opentofu/internal/encryption/method"
    16  )
    17  
    18  // validKeyLengths holds the valid key lengths supported by this method.
    19  var validKeyLengths = collections.NewSet[int](16, 24, 32)
    20  
    21  // Config is the configuration for the AES-GCM method.
    22  type Config struct {
    23  	// Key is the encryption key for the AES-GCM encryption. It has to be 16, 24, or 32 bytes long for AES-128, 192, or
    24  	// 256, respectively.
    25  	Keys keyprovider.Output `hcl:"keys" json:"keys" yaml:"keys"`
    26  
    27  	// AAD is the Additional Authenticated Data that is authenticated, but not encrypted. In the Go implementation, this
    28  	// data serves as a canary value against replay attacks. The AAD value on decryption must match this setting,
    29  	// otherwise the decryption will fail. (Note: this is Go-specific and differs from the NIST SP 800-38D description
    30  	// of the AAD.)
    31  	AAD []byte `hcl:"aad,optional" json:"aad,omitempty" yaml:"aad,omitempty"`
    32  }
    33  
    34  // Build checks the validity of the configuration and returns a ready-to-use AES-GCM implementation.
    35  func (c *Config) Build() (method.Method, error) {
    36  	encryptionKey := c.Keys.EncryptionKey
    37  	decryptionKey := c.Keys.DecryptionKey
    38  
    39  	if !validKeyLengths.Has(len(encryptionKey)) {
    40  		return nil, &method.ErrInvalidConfiguration{
    41  			Cause: fmt.Errorf(
    42  				"AES-GCM requires the key length to be one of: %s, received %d bytes in the encryption key",
    43  				validKeyLengths.String(),
    44  				len(encryptionKey),
    45  			),
    46  		}
    47  	}
    48  
    49  	if len(decryptionKey) > 0 {
    50  		if !validKeyLengths.Has(len(decryptionKey)) {
    51  			return nil, &method.ErrInvalidConfiguration{
    52  				Cause: fmt.Errorf(
    53  					"AES-GCM requires the key length to be one of: %s, received %d bytes in the decryption key",
    54  					validKeyLengths.String(),
    55  					len(decryptionKey),
    56  				),
    57  			}
    58  		}
    59  	}
    60  
    61  	return &aesgcm{
    62  		encryptionKey,
    63  		decryptionKey,
    64  		c.AAD,
    65  	}, nil
    66  }