github.com/opentofu/opentofu@v1.7.1/internal/encryption/keyprovider/pbkdf2/provider_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 7 8 import ( 9 "bytes" 10 "crypto/rand" 11 "io" 12 "testing" 13 ) 14 15 func TestPbkdf2KeyProvider_generateMetadata(t *testing.T) { 16 provider := pbkdf2KeyProvider{ 17 Config{ 18 randomSource: testRandomSource{t}, 19 Passphrase: "Hello world!", 20 KeyLength: 32, 21 Iterations: MinimumIterations, 22 HashFunction: SHA256HashFunctionName, 23 SaltLength: 12, 24 }, 25 } 26 metadata, err := provider.generateMetadata() 27 if err != nil { 28 t.Fatalf("%v", err) 29 } 30 31 if len(metadata.Salt) != 12 { 32 t.Fatalf("Invalid generated salt length: %d", len(metadata.Salt)) 33 } 34 // This is read from the random source, which is the test function name in this case. 35 // Note: this relies on the internal behavior of generateMetadata, but it's a non-exported 36 // function, so in this case that's acceptable. 37 if !bytes.Equal(metadata.Salt, []byte("TestPbkdf2Ke")) { 38 t.Fatalf("Invalid generated salt: %s", metadata.Salt) 39 } 40 41 if metadata.KeyLength != 32 { 42 t.Fatalf("Invalid key length: %d", metadata.KeyLength) 43 } 44 if metadata.Iterations != MinimumIterations { 45 t.Fatalf("Invalid iterations: %d", metadata.Iterations) 46 } 47 if metadata.HashFunction != SHA256HashFunctionName { 48 t.Fatalf("Invalid hash function name: %s", SHA256HashFunctionName) 49 } 50 } 51 52 type badReader struct{} 53 54 func (b badReader) Read(target []byte) (int, error) { 55 return 0, io.EOF 56 } 57 58 func TestBadReader(t *testing.T) { 59 provider := pbkdf2KeyProvider{ 60 Config{ 61 randomSource: badReader{}, 62 Passphrase: "Hello world!", 63 KeyLength: 32, 64 Iterations: MinimumIterations, 65 HashFunction: SHA256HashFunctionName, 66 SaltLength: 12, 67 }, 68 } 69 70 if _, err := provider.generateMetadata(); err == nil { 71 t.Fatalf("expected error") 72 } 73 74 if _, _, err := provider.Provide(&Metadata{}); err == nil { 75 t.Fatalf("expected error") 76 } 77 } 78 79 func TestKeyLength(t *testing.T) { 80 provider := pbkdf2KeyProvider{ 81 Config{ 82 randomSource: rand.Reader, 83 Passphrase: "Hello world!", 84 KeyLength: 128, 85 Iterations: MinimumIterations, 86 HashFunction: SHA256HashFunctionName, 87 SaltLength: 12, 88 }, 89 } 90 keys, _, err := provider.Provide(&Metadata{}) 91 if err != nil { 92 t.Fatalf("%v", err) 93 } 94 if length := len(keys.EncryptionKey); length != 128 { 95 t.Fatalf("incorrect key length: %d", length) 96 } 97 }