package main

import (
	"crypto/x509"
	"encoding/base64"
	"fmt"
	"os"

	"ems.agt/tools/cmca/config"
)

// func init() {
// 	roots := x509.NewCertPool()
// 	rootCert, err := LoadCert(config.CaConfig.CA.RootCert)
// 	if err != nil {
// 		os.Exit(1)
// 	}
// 	roots.AddCert(rootCert)
// 	rootCertPool = roots
// }

func main() {
	// 初始化
	//config.CaConfig.CA.RootCert = "./certs/cacert.pem"

	//Init()
	fmt.Println("CaConfig:", config.CaConfig)

	roots := x509.NewCertPool()
	rootCert, err := LoadCert(config.CaConfig.CA.RootCert)
	if err != nil {
		os.Exit(1)
	}
	roots.AddCert(rootCert)
	rootCertPool = roots

	//证书验证：
	cert, err := LoadCert(config.CaConfig.CA.Cert)
	if err != nil {
		fmt.Println("LoadCert:", err)
		return
	}

	err = VerifyCert(cert)
	fmt.Println("VerifyCert:", err)

	//签名
	fmt.Println("RSA签名认证:")
	pri, err := LoadPriKey(config.CaConfig.CA.PrivateKey)
	if err != nil {
		fmt.Println("LoadPriKey:", err)
		return
	}
	username := config.UserName
	rsaSign, err := SignRSA([]byte(*username), pri)
	if err != nil {
		fmt.Println("SignRSA:", err)
		return
	}
	rsaSign64 := base64.StdEncoding.EncodeToString(rsaSign)
	fmt.Println("rsaSign64:", rsaSign64)

	//签证验证
	cert, err = LoadCert(config.CaConfig.CA.Cert)
	if err != nil {
		fmt.Println("LoadCert:", err)
		return
	}
	err = VerifyRSA([]byte(*username), rsaSign, cert)
	fmt.Println("VerifyRSA sign:", err)
}
