package main

import (
	"crypto/elliptic"
	"fmt"
)

func main() {

	// 创建 P256 曲线
	curve := elliptic.P256()

	//初始化用户id 和消息
	ID := []byte("1234567890111213141516171819202122232425")
	msg := []byte("DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD")

	//生成KGC公私钥
	PKx, PKy, msk := genKGCKey(curve)

	//用户生成秘密值,后经过运算返回点
	Xx, Xy, x := genSecret(curve)

	//KGC生成用户的部分私钥d和全部公钥Q
	d, Qx, Qy := genPartialKey(curve, ID, msk, Xx, Xy, PKx, PKy)

	//用户验证生成的部分私钥和全部公钥是否有效
	err := VerifyEquation(curve, ID, d, Qx, Qy, Xx, Xy, PKx, PKy)
	if err != nil {
		fmt.Println("KGC生成的私钥无效！！！")
		return
	}
	fmt.Println("生成的私钥有效！")

	//用户生成全部私钥
	s := genPriKey(curve, ID, x, d, Xx, Xy)

	//用户对消息签名
	Ux, Uy, v := SignThumb(curve, ID, msg, s, Qx, Qy, PKx, PKy)

	//接收方对消息进行验证
	err = VerifyThumb(curve, ID, msg, Qx, Qy, PKx, PKy, Ux, Uy, v)
	if err != nil {
		fmt.Println("签名验证失败！")
	}

	//fmt.Printf("KGC基点为：\nP_x:%s\nP_y:%s\n", curve.Params().Gx, curve.Params().Gy)
	//fmt.Printf("用户的公钥为：\nPK_pub_s:%x\nPK_pub_s:%x\n", PKx, PKy)

	//fmt.Println(append([]byte(PKx.Text(16)), []byte(PKy.Text(16))...))

	pubdata := mergeBigInts(Qx, Qy)
	kgcpub := mergeBigInts(PKx, PKy)
	pridata := mergeBigInts(s)

	fmt.Printf("KGC公钥为：%s\n", kgcpub)
	fmt.Printf("用户公钥为：%s\n", pubdata)
	fmt.Printf("用户私钥为：%s\n", pridata)
	//fmt.Printf("用户ID为：\nID:%s\n", ID)
	writeToFolder("./cert", "pkpub.txt", kgcpub)
	writeToFolder("./cert", "prikey.txt", pridata)
	writeToFolder("./cert", "pubkey.txt", pubdata)

	data, _ := readFileFromDirectory("./cert", "pubkey.txt")
	fmt.Println(data)
	dax, day := bytes_halve(data)

	Dx := BytesToBig(dax)
	Dy := BytesToBig(day)
	fmt.Println(Dx, Dy)
	onCurve := curve.IsOnCurve(Dx, Dy)

	if onCurve {
		fmt.Println("点在椭圆曲线上")
	} else {
		fmt.Println("点不在椭圆曲线上")
	}

	//return
}
