package main

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"encoding/pem"
	"fmt"
	"math/big"
	"os"
	"time"
)

func main() {
	// 生成私钥
	privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
	if err != nil {
		fmt.Println("Failed to generate private key:", err)
		return
	}

	// 创建根证书模板
	ca := &x509.Certificate{
		SerialNumber: big.NewInt(2023),
		Subject:      pkix.Name{CommonName: "Root CA"},
		NotBefore:    time.Now(),
		//NotAfter:              time.Now().AddDate(10, 0, 0), // 有效期为10年
		NotAfter:              time.Now().AddDate(0, 0, 1), // 有效期为10年
		KeyUsage:              x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
		BasicConstraintsValid: true,
		IsCA:                  true,
	}

	// 使用私钥对根证书进行签名
	caBytes, err := x509.CreateCertificate(rand.Reader, ca, ca, &privateKey.PublicKey, privateKey)
	if err != nil {
		fmt.Println("Failed to create CA certificate:", err)
		return
	}

	// 将根证书保存到文件
	caFile, err := os.Create("ca_cert.pem")
	if err != nil {
		fmt.Println("Failed to create CA certificate file:", err)
		return
	}
	defer caFile.Close()

	err = pem.Encode(caFile, &pem.Block{
		Type:  "CERTIFICATE",
		Bytes: caBytes,
	})
	if err != nil {
		fmt.Println("Failed to write CA certificate to file:", err)
		return
	}

	fmt.Println("Root CA certificate generated successfully.")

	// 将公钥保存到文件
	publicKeyBytes := x509.MarshalPKCS1PublicKey(&privateKey.PublicKey)
	publicKeyFile, err := os.Create("public_key.pem")
	if err != nil {
		fmt.Println("Failed to create public key file:", err)
		return
	}
	defer publicKeyFile.Close()

	err = pem.Encode(publicKeyFile, &pem.Block{
		Type:  "RSA PUBLIC KEY",
		Bytes: publicKeyBytes,
	})
	if err != nil {
		fmt.Println("Failed to write public key to file:", err)
		return
	}

	fmt.Println("Public key generated successfully.")

	// 将私钥保存到文件
	privateKeyBytes := x509.MarshalPKCS1PrivateKey(privateKey)
	privateKeyFile, err := os.Create("private_key.pem")
	if err != nil {
		fmt.Println("Failed to create private key file:", err)
		return
	}
	defer privateKeyFile.Close()

	err = pem.Encode(privateKeyFile, &pem.Block{
		Type:  "RSA PRIVATE KEY",
		Bytes: privateKeyBytes,
	})
	if err != nil {
		fmt.Println("Failed to write private key to file:", err)
		return
	}

	fmt.Println("Private key generated successfully.")
}
