package cryptoutil

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/rsa"
	"testing"
)

func TestGenerateSubjectKeyID(t *testing.T) {
	t.Parallel()

	rsaKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		t.Fatal(err)
	}

	ecdsaKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	for _, test := range []struct {
		testName string
		pub      crypto.PublicKey
	}{
		{"RSA", rsaKey.Public()},
		{"ECDSA", &ecdsaKey.PublicKey},
	} {
		test := test
		t.Run(test.testName, func(t *testing.T) {
			t.Parallel()

			ski, err := GenerateSubjectKeyID(test.pub)
			if err != nil {
				t.Fatal(err)
			}
			if len(ski) != 20 {
				t.Fatalf("unexpected subject public key identifier length: %d", len(ski))
			}
			ski2, err := GenerateSubjectKeyID(test.pub)
			if err != nil {
				t.Fatal(err)
			}
			if !testSKIEq(ski, ski2) {
				t.Fatal("subject key identifier generation is not deterministic")
			}
		})
	}
}

func testSKIEq(a, b []byte) bool {
	if len(a) != len(b) {
		return false
	}

	for i := range a {
		if a[i] != b[i] {
			return false
		}
	}

	return true
}
