package cryptokit

import (
	"crypto/ed25519"
	"crypto/rand"
	"encoding/base64"
	"testing"
)

func TestEd25519SignVerifyAcceptsSeedEncoding(t *testing.T) {
	public, private, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	message := []byte("Aegis cryptographic test")
	signature, err := SignEd25519(message, base64.StdEncoding.EncodeToString(private.Seed()))
	if err != nil {
		t.Fatal(err)
	}
	if err := VerifyEd25519(message, signature, base64.StdEncoding.EncodeToString(public)); err != nil {
		t.Fatal(err)
	}
	if err := VerifyEd25519([]byte("tampered"), signature, base64.StdEncoding.EncodeToString(public)); err == nil {
		t.Fatal("tampered message verified")
	}
}

func TestEd25519PublicKeyAndFingerprint(t *testing.T) {
	public, private, err := ed25519.GenerateKey(rand.Reader)
	if err != nil {
		t.Fatal(err)
	}
	derived, err := Ed25519PublicKey(base64.StdEncoding.EncodeToString(private.Seed()))
	if err != nil {
		t.Fatal(err)
	}
	if derived != base64.StdEncoding.EncodeToString(public) {
		t.Fatalf("derived public key = %q, want %q", derived, base64.StdEncoding.EncodeToString(public))
	}
	fingerprint, err := Ed25519PublicKeyFingerprint(derived)
	if err != nil {
		t.Fatal(err)
	}
	if len(fingerprint) != len("sha256:")+64 || fingerprint[:len("sha256:")] != "sha256:" {
		t.Fatalf("unexpected fingerprint %q", fingerprint)
	}
}
