package provider

import (
	"encoding/base64"
	"testing"
)

func TestCredentialCipherRoundTripAndAuthentication(t *testing.T) {
	key := base64.StdEncoding.EncodeToString(make([]byte, 32))
	cipher, err := NewCredentialCipher(key, 7)
	if err != nil {
		t.Fatal(err)
	}
	encrypted, version, err := cipher.Encrypt([]byte(`{"api_key":"secret"}`))
	if err != nil {
		t.Fatal(err)
	}
	plaintext, err := cipher.Decrypt(encrypted, version)
	if err != nil || string(plaintext) != `{"api_key":"secret"}` {
		t.Fatalf("unexpected decrypt result %q: %v", plaintext, err)
	}
	encrypted[len(encrypted)-1] ^= 1
	if _, err := cipher.Decrypt(encrypted, version); err == nil {
		t.Fatal("tampered ciphertext must fail authentication")
	}
}
