diff --git a/aead/kms_envelope_aead_key_manager_test.go b/aead/kms_envelope_aead_key_manager_test.go index 848afc8..0006879 100644 --- a/aead/kms_envelope_aead_key_manager_test.go +++ b/aead/kms_envelope_aead_key_manager_test.go @@ -17,11 +17,13 @@ package aead_test import ( + "bytes" "testing" "google.golang.org/protobuf/proto" "github.com/tink-crypto/tink-go/v2/aead" "github.com/tink-crypto/tink-go/v2/core/registry" + "github.com/tink-crypto/tink-go/v2/insecurecleartextkeyset" "github.com/tink-crypto/tink-go/v2/keyset" "github.com/tink-crypto/tink-go/v2/mac" "github.com/tink-crypto/tink-go/v2/testing/fakekms" @@ -127,3 +129,54 @@ func TestNewKMSEnvelopeAEADKeyWithInvalidSerializedKeyFormat(t *testing.T) { t.Errorf("a.Encrypt() err = nil, want error") } } + +func TestKMSEnvelopeAEADWithTinkPrefix(t *testing.T) { + keyURI := "fake-kms://CM2b3_MDElQKSAowdHlwZS5nb29nbGVhcGlzLmNvbS9nb29nbGUuY3J5cHRvLnRpbmsuQWVzR2NtS2V5EhIaEIK75t5L-adlUwVhWvRuWUwYARABGM2b3_MDIAE" + client, err := fakekms.NewClient(keyURI) + if err != nil { + t.Fatal(err) + } + registry.RegisterKMSClient(client) + defer registry.ClearKMSClients() + + // Keyset that was created with + // aead.CreateKMSEnvelopeAEADKeyTemplate(keyURI, aead.AES256GCMKeyTemplate()), and then serialized + // with Tink's JSON keyset witer. Then, the output prefix type was changed from "RAW" to "TINK". + jsonKeysetWithTinkPrefix := `{"primaryKeyId":3980895889, "key":[{"keyData":{"typeUrl":"type.googleapis.com/google.crypto.tink.KmsEnvelopeAeadKey", "value":"EsMBCoYBZmFrZS1rbXM6Ly9DTTJiM19NREVsUUtTQW93ZEhsd1pTNW5iMjluYkdWaGNHbHpMbU52YlM5bmIyOW5iR1V1WTNKNWNIUnZMblJwYm1zdVFXVnpSMk50UzJWNUVoSWFFSUs3NXQ1TC1hZGxVd1ZoV3ZSdVdVd1lBUkFCR00yYjNfTURJQUUSOAowdHlwZS5nb29nbGVhcGlzLmNvbS9nb29nbGUuY3J5cHRvLnRpbmsuQWVzR2NtS2V5EgIQIBgB", "keyMaterialType":"REMOTE"}, "status":"ENABLED", "keyId":3980895889, "outputPrefixType":"TINK"}]}` + + parsedHandle, err := insecurecleartextkeyset.Read( + keyset.NewJSONReader(bytes.NewBuffer([]byte(jsonKeysetWithTinkPrefix)))) + if err != nil { + t.Fatalf("insecurecleartextkeyset.Read() err = %v, want nil", err) + } + + primitive, err := aead.New(parsedHandle) + if err != nil { + t.Fatal(err) + } + + plaintext := []byte("message") + associatedData := []byte("example KMS envelope AEAD encryption") + + ciphertext, err := primitive.Encrypt(plaintext, associatedData) + if err != nil { + t.Fatal(err) + } + gotPlaintext, err := primitive.Decrypt(ciphertext, associatedData) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(gotPlaintext, plaintext) { + t.Fatalf("got plaintext %q, want %q", gotPlaintext, plaintext) + } + + // Also verify that the ciphertext has a TINK prefix + gotPrefix := ciphertext[:5] + // The Tink prefix is 0x01 followed by the 4 bytes key ID. The key ID is 3980895889, which is + // equal to 0xed47a691. + wantPrefix := []byte{0x01, 0xed, 0x47, 0xa6, 0x91} + if !bytes.Equal(gotPrefix, wantPrefix) { + t.Fatalf("ciphertext[:5] = %q, want %q", gotPrefix, wantPrefix) + } + +}