github.com/opentofu/opentofu@v1.7.1/internal/encryption/method/aesgcm/aesgcm_internal_test.go (about)

     1  package aesgcm
     2  
     3  import (
     4  	"testing"
     5  )
     6  
     7  type testCase struct {
     8  	aes   *aesgcm
     9  	error bool
    10  }
    11  
    12  func TestInternalErrorHandling(t *testing.T) {
    13  	testCases := map[string]testCase{
    14  		"ok": {
    15  			&aesgcm{
    16  				encryptionKey: []byte("aeshi1quahb2Rua0ooquaiwahbonedoh"),
    17  				decryptionKey: []byte("aeshi1quahb2Rua0ooquaiwahbonedoh"),
    18  			},
    19  			false,
    20  		},
    21  		"no-key": {
    22  			&aesgcm{},
    23  			true,
    24  		},
    25  		"bad-key-length": {
    26  			&aesgcm{
    27  				encryptionKey: []byte("Hello world!"),
    28  				decryptionKey: []byte("Hello world!"),
    29  			},
    30  			true,
    31  		},
    32  	}
    33  	for name, tc := range testCases {
    34  		t.Run(name, func(t *testing.T) {
    35  			encrypted, err := tc.aes.Encrypt([]byte("Hello world!"))
    36  			if tc.error && err == nil {
    37  				t.Fatalf("Expected error, none returned.")
    38  			} else if !tc.error && err != nil {
    39  				t.Fatalf("Unexpected error: %v", err)
    40  			}
    41  			if !tc.error {
    42  				decrypted, err := tc.aes.Decrypt(encrypted)
    43  				if err != nil {
    44  					t.Fatalf("Unexpected error: %v", err)
    45  				}
    46  				if string(decrypted) != "Hello world!" {
    47  					t.Fatalf("Incorrect decrypted string: %s", decrypted)
    48  				}
    49  			} else {
    50  				// Test error handling on the decrypt side as best as we can:
    51  				_, err := tc.aes.Decrypt([]byte("Hello world!"))
    52  				if err == nil {
    53  					t.Fatalf("Expected error, none returned.")
    54  				}
    55  			}
    56  		})
    57  	}
    58  }