package winpwn

import (
	"bytes"
	"testing"
)

func TestFindXORKeyAvoidsBadChars(t *testing.T) {
	data := []byte{0x00, 0x0A, 0x0D, 0x41, 0x42}
	badChars := []byte{0x00, 0x0A, 0x0D}

	key, err := FindXORKey(data, badChars)
	if err != nil {
		t.Fatal(err)
	}

	encoded := Xor(data, []byte{key})
	if HasBadChars(encoded, badChars) {
		t.Errorf("encoded output %x still contains a bad char (key=0x%02x)", encoded, key)
	}
}

func TestEncodeXORRoundTrip(t *testing.T) {
	data := []byte("the quick brown fox")
	badChars := []byte{0x00, 0x0A, 0x0D, 0x20} // also avoid spaces, for fun

	encoded, key, err := EncodeXOR(data, badChars)
	if err != nil {
		t.Fatal(err)
	}
	if HasBadChars(encoded, badChars) {
		t.Errorf("encoded output still has bad chars")
	}

	decoded := Xor(encoded, []byte{key})
	if !bytes.Equal(decoded, data) {
		t.Errorf("decoded = %q, want %q", decoded, data)
	}
}

func TestFindXORKeyImpossible(t *testing.T) {
	// Every byte 0..255 appears in data, so no key can avoid every byte
	// being a bad char if badChars also covers every value the key could
	// produce -- construct a case that's provably impossible: data
	// contains every byte value, and badChars also contains every byte
	// value, so any key XORed against some data byte lands on a bad byte.
	data := make([]byte, 256)
	for i := range data {
		data[i] = byte(i)
	}
	badChars := data // all 256 values are "bad"

	if _, err := FindXORKey(data, badChars); err == nil {
		t.Error("expected an error when every byte value is both present and forbidden")
	}
}
