package sm2m

import (
	"fmt"
	"testing"

	"xdx.jelly/xgcl/grand"
	"xdx.jelly/xgcl/sm/sm2"
)

func TestAuditSign(t *testing.T) {

	rnd := make([]byte, 32)
	clientKey, clientTempKey, _ := ClientGenSignKey_one(nil)
	_, _ = grand.GenerateRandom(rnd)
	serverKey, serverTempKey, publicKey, _ := ServerGenSignKey(clientTempKey, rnd)
	err := ClientGenSignKey_two(clientKey, serverTempKey, publicKey)
	if err != nil {
		t.Fatal("client's public key and server's public key are not equal.")
	}

	d := realPrivateKey(serverKey, clientKey)
	if !publicKey.Equals(&d.PublicKey) {
		t.Fatal("client's public key and server's public key are not equal.")
	}
	fmt.Printf("客户端密钥分量: %x\n", clientKey.Bytes())
	fmt.Printf("服务端密钥分量: %x\n", serverKey.Bytes())
	fmt.Printf("公钥: %x\n", publicKey.Bytes())

	c := new(ClientSignContext)
	e := make([]byte, 32)
	grand.GenerateRandom(e)
	fmt.Printf("签名数据e: %x\n", e)
	out, err := c.Initial(e)
	if err != nil {
		t.Fatal(err)
	}
	out, err = ServerSign(serverKey, out, grand.Reader)
	if err != nil {
		t.Fatal(err)
	}

	sig, err := c.Final(clientKey, out)
	if err != nil {
		t.Fatal(err)
	}
	fmt.Printf("签名结果: %x\n", sig.Bytes())

	if !sm2.Verify(e, publicKey, sig) {
		t.Fatal("verify failed")
	}
}

func TestAuditDec(t *testing.T) {

	rnd := make([]byte, 32)
	grand.ReaderOne.Read(rnd)
	clientKey, clientTempKey, _ := ClientGenSignKey_one(rnd)
	// _, _ = grand.GenerateRandom(rnd)
	grand.ReaderTwo.Read(rnd)
	serverKey, serverTempKey, publicKey, _ := ServerGenSignKey(clientTempKey, rnd)
	err := ClientGenSignKey_two(clientKey, serverTempKey, publicKey)
	if err != nil {
		t.Fatal("client's public key and server's public key are not equal.")
	}

	d := realPrivateKey(serverKey, clientKey)
	if !publicKey.Equals(&d.PublicKey) {
		t.Fatal("client's public key and server's public key are not equal.")
	}
	fmt.Printf("客户端密钥分量: %x\n", clientKey.Bytes())
	fmt.Printf("服务端密钥分量: %x\n", serverKey.Bytes())
	fmt.Printf("公钥: %x\n", publicKey.Bytes())

	msg := []byte("1234567890123456")
	fmt.Printf("明文数据: %x\n", msg)

	grand.ReaderOne.Read(rnd)
	c, _ := sm2.Encrypt(publicKey, msg, rnd)
	fmt.Printf("密文数据: %x\n", c.Bytes())

	clientCTX := NewClientDecContext()
	out, _ := clientCTX.Initial(c)
	out, _ = ServerImportKey(serverKey, out)
	plain, _ := clientCTX.Final(clientKey, out)
	fmt.Printf("解密数据: %x\n", plain)

}
