package main import ( "crypto/ecdsa" "crypto/rand" "crypto/x509/pkix" "fmt" "github.com/tjfoc/gmsm/sm2" "github.com/tjfoc/gmsm/x509" "math/big" "time" ) func ecdsaToSM2PublicKey(ecdsaPublicKey *ecdsa.PublicKey) (*sm2.PublicKey, error) { // 获取ECDSA公钥的X和Y坐标 x := ecdsaPublicKey.X y := ecdsaPublicKey.Y // 创建SM2公钥对象 sm2PublicKey := &sm2.PublicKey{ Curve: sm2.P256Sm2(), X: new(big.Int).Set(x), Y: new(big.Int).Set(y), } return sm2PublicKey, nil } func main() { // 生成CA密钥对 caPrivateKey, err := sm2.GenerateKey(nil) if err != nil { panic(err) } caTemplate := x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{ CommonName: "CA", }, NotBefore: time.Now(), NotAfter: time.Now().AddDate(10, 0, 0), KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, BasicConstraintsValid: true, IsCA: true, } caCertBytes, err := x509.CreateCertificate(&caTemplate, &caTemplate, &caPrivateKey.PublicKey, caPrivateKey) if err != nil { panic(err) } //caCertBlock, _ := pem.Decode(caCertBytes) caCert, _ := x509.ParseCertificate(caCertBytes) // 生成用户密钥对和证书请求 userPrivateKey, err := sm2.GenerateKey(nil) if err != nil { panic(err) } userSubject := pkix.Name{ CommonName: "user.example.com", } userTemplate := x509.CertificateRequest{ Subject: userSubject, } userCsrBytes, err := x509.CreateCertificateRequest(rand.Reader, &userTemplate, userPrivateKey) if err != nil { panic(err) } userCsr, err := x509.ParseCertificateRequest(userCsrBytes) if err != nil { panic(err) } // 签发用户证书 userCertTemplate := x509.Certificate{ SerialNumber: big.NewInt(2), Subject: userSubject, NotBefore: time.Now(), NotAfter: time.Now().AddDate(1, 0, 0), KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, } //a := sm2.PublicKey{} //println("a", a) pk, _ := ecdsaToSM2PublicKey(userCsr.PublicKey.(*ecdsa.PublicKey)) userCertBytes, err := x509.CreateCertificate(&userCertTemplate, caCert, pk, caPrivateKey) if err != nil { panic(err) } fmt.Println("用户证书:", userCertBytes) }
标签:err,nil,x509,sm2,PublicKey,panic From: https://www.cnblogs.com/exmyth/p/18599625