gitee.com/ks-custle/core-gm@v0.0.0-20230922171213-b83bdd97b62c/x509/x509.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package x509 parses X.509-encoded keys and certificates.
     6  package x509
     7  
     8  /*
     9  x509/x509.go 实现gmx509证书的相关操作:
    10  ParsePKIXPublicKey : 将一个PKIX, ASN.1 DER格式字节数组转为对应的公钥
    11  MarshalPKIXPublicKey : 将公钥转为PKIX, ASN.1 DER格式字节数组
    12  Certificate : gmx509证书结构体
    13   c.CheckSignatureFrom : 检查对c做的签名是否是父证书拥有者的有效签名(使用父证书中的公钥验签)
    14   c.CheckSignature : 使用c的公钥检查签名是否有效
    15   c.ToX509Certificate : gmx509转x509
    16   c.FromX509Certificate : x509转gmx509
    17   c.CheckCRLSignature : 检查证书撤销列表CRL是否由c签名
    18   c.CreateCRL : 创建一个CRL
    19  CreateCertificate : 根据证书模板生成gmx509证书(v3)的DER字节数组
    20  ParseCRL : 将给定的字节数组(PEM/DER)转为CRL
    21  ParseDERCRL : 将DER字节数组转为CRL
    22  CertificateRequest : 证书申请结构体
    23  CreateCertificateRequest : 基于证书申请模板生成一个新的证书申请
    24  ParseCertificateRequest : 将DER字节数组转为单个证书申请
    25   csr.CheckSignature : 检查证书申请c的签名是否有效
    26  */
    27  
    28  import (
    29  	"bytes"
    30  	"crypto"
    31  	"crypto/ecdsa"
    32  	"crypto/ed25519"
    33  	"crypto/elliptic"
    34  	"crypto/md5"
    35  	"crypto/rsa"
    36  	"crypto/sha1"
    37  	"crypto/sha256"
    38  	"crypto/sha512"
    39  	"crypto/x509"
    40  	"crypto/x509/pkix"
    41  	"encoding/asn1"
    42  	"encoding/base64"
    43  	"encoding/binary"
    44  	"encoding/hex"
    45  	"encoding/pem"
    46  	"errors"
    47  	"fmt"
    48  	"gitee.com/ks-custle/core-gm/ecbase"
    49  	"gitee.com/ks-custle/core-gm/ecdsa_ext"
    50  	"gitee.com/ks-custle/core-gm/x509ca"
    51  	"io"
    52  	"log"
    53  	"math/big"
    54  	"net"
    55  	"net/url"
    56  	"strconv"
    57  	"time"
    58  	"unicode"
    59  
    60  	"gitee.com/ks-custle/core-gm/sm2"
    61  	"gitee.com/ks-custle/core-gm/sm3"
    62  
    63  	// Explicitly import these for their crypto.RegisterHash init side-effects.
    64  	// Keep these as blank imports, even if they're imported above.
    65  	_ "crypto/sha1"
    66  	_ "crypto/sha256"
    67  	_ "crypto/sha512"
    68  
    69  	"golang.org/x/crypto/cryptobyte"
    70  	cryptobyteasn1 "golang.org/x/crypto/cryptobyte/asn1"
    71  	"golang.org/x/crypto/sha3"
    72  )
    73  
    74  // PKIX格式公钥结构体,用于x509证书中的公钥部分。
    75  // pkixPublicKey reflects a PKIX public key structure.
    76  // See SubjectPublicKeyInfo in RFC 3280.
    77  type pkixPublicKey struct {
    78  	Algo      pkix.AlgorithmIdentifier
    79  	BitString asn1.BitString
    80  }
    81  
    82  // ParsePKIXPublicKey 将一个PKIX, ASN.1 DER格式字节数组转为对应的公钥。
    83  // 公钥支持 *sm2.PublicKey, *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey ,
    84  // 这些公钥的pem类型是"PUBLIC KEY"。
    85  //
    86  // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
    87  // The encoded public key is a SubjectPublicKeyInfo structure
    88  // (see RFC 5280, Section 4.1).
    89  //
    90  // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
    91  // ed25519.PublicKey. More types might be supported in the future.
    92  //
    93  // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
    94  func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
    95  	var pki publicKeyInfo
    96  	if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
    97  		if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
    98  			return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
    99  		}
   100  		return nil, err
   101  	} else if len(rest) != 0 {
   102  		return nil, errors.New("x509: trailing data after ASN.1 of public-key")
   103  	}
   104  	// 根据pki中的算法oid获取对应的算法
   105  	algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
   106  	if algo == UnknownPublicKeyAlgorithm {
   107  		return nil, errors.New("x509: unknown public key algorithm")
   108  	}
   109  	return parsePublicKey(algo, &pki)
   110  }
   111  
   112  // 将公钥转为字节数组,同时返回对应的pkix算法标识符
   113  func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
   114  	switch pub := pub.(type) {
   115  	case *sm2.PublicKey:
   116  		// 将椭圆曲线、公钥座标转换为字节数组
   117  		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
   118  		// 获取椭圆曲线oid,注意,国标目前没有给出sm2椭圆曲线的oid,这里使用SM2算法的oid代替
   119  		oid, ok := oidFromNamedCurve(pub.Curve)
   120  		if !ok {
   121  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported SM2 curve")
   122  		}
   123  		// 设定公钥算法的oid为sm2算法oid
   124  		publicKeyAlgorithm.Algorithm = oidPublicKeySM2
   125  		var paramBytes []byte
   126  		// 将椭圆曲线oid转为字节数组
   127  		paramBytes, err = asn1.Marshal(oid)
   128  		if err != nil {
   129  			return
   130  		}
   131  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
   132  	case *rsa.PublicKey:
   133  		publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
   134  			N: pub.N,
   135  			E: pub.E,
   136  		})
   137  		if err != nil {
   138  			return nil, pkix.AlgorithmIdentifier{}, err
   139  		}
   140  		publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
   141  		// This is a NULL parameters value which is required by
   142  		// RFC 3279, Section 2.3.1.
   143  		publicKeyAlgorithm.Parameters = asn1.NullRawValue
   144  	case *ecdsa.PublicKey:
   145  		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
   146  		oid, ok := oidFromNamedCurve(pub.Curve)
   147  		if !ok {
   148  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
   149  		}
   150  		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
   151  		var paramBytes []byte
   152  		paramBytes, err = asn1.Marshal(oid)
   153  		if err != nil {
   154  			return
   155  		}
   156  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
   157  	case *ecdsa_ext.PublicKey:
   158  		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
   159  		oid, ok := oidFromNamedCurve(pub.Curve)
   160  		if !ok {
   161  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
   162  		}
   163  		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSAEXT
   164  		var paramBytes []byte
   165  		paramBytes, err = asn1.Marshal(oid)
   166  		if err != nil {
   167  			return
   168  		}
   169  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
   170  	case ed25519.PublicKey:
   171  		publicKeyBytes = pub
   172  		publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
   173  	default:
   174  		return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
   175  	}
   176  
   177  	return publicKeyBytes, publicKeyAlgorithm, nil
   178  }
   179  
   180  // MarshalPKIXPublicKey 将公钥转为PKIX, ASN.1 DER格式字节数组。
   181  // 公钥支持 *sm2.PublicKey, *rsa.PublicKey, *ecdsa.PublicKey, ed25519.PublicKey ,
   182  // 这些公钥的pem类型是"PUBLIC KEY"。
   183  //
   184  // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
   185  // The encoded public key is a SubjectPublicKeyInfo structure
   186  // (see RFC 5280, Section 4.1).
   187  //
   188  // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
   189  // and ed25519.PublicKey. Unsupported key types result in an error.
   190  //
   191  // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
   192  func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
   193  	var publicKeyBytes []byte
   194  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
   195  	var err error
   196  
   197  	if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
   198  		return nil, err
   199  	}
   200  	// 生成PKIX公钥
   201  	pkixPk := pkixPublicKey{
   202  		Algo: publicKeyAlgorithm,
   203  		BitString: asn1.BitString{
   204  			Bytes:     publicKeyBytes,
   205  			BitLength: 8 * len(publicKeyBytes),
   206  		},
   207  	}
   208  	// PKIX公钥字节数组,用于x509证书的公钥部分。
   209  	ret, _ := asn1.Marshal(pkixPk)
   210  	return ret, nil
   211  }
   212  
   213  // These structures reflect the ASN.1 structure of X.509 certificates.:
   214  
   215  type certificate struct {
   216  	Raw                asn1.RawContent
   217  	TBSCertificate     tbsCertificate
   218  	SignatureAlgorithm pkix.AlgorithmIdentifier
   219  	SignatureValue     asn1.BitString
   220  }
   221  
   222  // 证书主体,签名内容
   223  // tbs即"To be signed"
   224  type tbsCertificate struct {
   225  	Raw                asn1.RawContent
   226  	Version            int `asn1:"optional,explicit,default:0,tag:0"`
   227  	SerialNumber       *big.Int
   228  	SignatureAlgorithm pkix.AlgorithmIdentifier
   229  	Issuer             asn1.RawValue
   230  	Validity           validity
   231  	Subject            asn1.RawValue
   232  	PublicKey          publicKeyInfo
   233  	UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
   234  	SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
   235  	Extensions         []pkix.Extension `asn1:"optional,explicit,tag:3"`
   236  }
   237  
   238  //goland:noinspection GoUnusedType
   239  type dsaAlgorithmParameters struct {
   240  	P, Q, G *big.Int
   241  }
   242  
   243  type validity struct {
   244  	NotBefore, NotAfter time.Time
   245  }
   246  
   247  type publicKeyInfo struct {
   248  	Raw       asn1.RawContent
   249  	Algorithm pkix.AlgorithmIdentifier
   250  	PublicKey asn1.BitString
   251  }
   252  
   253  // RFC 5280,  4.2.1.1
   254  type authKeyId struct {
   255  	Id []byte `asn1:"optional,tag:0"`
   256  }
   257  
   258  // 初始化加载所有支持的散列组件
   259  func init() {
   260  	RegisterHash(MD4, nil)
   261  	RegisterHash(MD5, md5.New)
   262  	RegisterHash(SHA1, sha1.New)
   263  	RegisterHash(SHA224, sha256.New224)
   264  	RegisterHash(SHA256, sha256.New)
   265  	RegisterHash(SHA384, sha512.New384)
   266  	RegisterHash(SHA512, sha512.New)
   267  	RegisterHash(MD5SHA1, nil)
   268  	// RegisterHash(RIPEMD160, ripemd160.New)
   269  	RegisterHash(SHA3_224, sha3.New224)
   270  	RegisterHash(SHA3_256, sha3.New256)
   271  	RegisterHash(SHA3_384, sha3.New384)
   272  	RegisterHash(SHA3_512, sha3.New512)
   273  	RegisterHash(SHA512_224, sha512.New512_224)
   274  	RegisterHash(SHA512_256, sha512.New512_256)
   275  	RegisterHash(SM3, sm3.New)
   276  }
   277  
   278  // SignatureAlgorithm 签名算法
   279  type SignatureAlgorithm int
   280  
   281  const (
   282  	UnknownSignatureAlgorithm SignatureAlgorithm = iota
   283  
   284  	MD2WithRSA // Unsupported.
   285  	MD5WithRSA // Only supported for signing, not verification.
   286  	SHA1WithRSA
   287  	SHA256WithRSA
   288  	SHA384WithRSA
   289  	SHA512WithRSA
   290  	DSAWithSHA1   // Unsupported.
   291  	DSAWithSHA256 // Unsupported.
   292  	ECDSAWithSHA1
   293  	ECDSAWithSHA256
   294  	ECDSAWithSHA384
   295  	ECDSAWithSHA512
   296  	SHA256WithRSAPSS
   297  	SHA384WithRSAPSS
   298  	SHA512WithRSAPSS
   299  	PureEd25519
   300  	SM2WithSM3         // 签名算法添加国密算法: SM2WithSM3
   301  	ECDSAEXTWithSHA256 // ecdsa_ext 扩展的ECDSA签名算法(支持low-s处理)
   302  	ECDSAEXTWithSHA384 // ecdsa_ext 扩展的ECDSA签名算法(支持low-s处理)
   303  	ECDSAEXTWithSHA512 // ecdsa_ext 扩展的ECDSA签名算法(支持low-s处理)
   304  )
   305  
   306  func (algo SignatureAlgorithm) IsECDSAEXT() bool {
   307  	switch algo {
   308  	case ECDSAEXTWithSHA256, ECDSAEXTWithSHA384, ECDSAEXTWithSHA512:
   309  		return true
   310  	default:
   311  		return false
   312  	}
   313  }
   314  
   315  func (algo SignatureAlgorithm) isRSAPSS() bool {
   316  	switch algo {
   317  	case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
   318  		return true
   319  	default:
   320  		return false
   321  	}
   322  }
   323  
   324  func (algo SignatureAlgorithm) String() string {
   325  	for _, details := range signatureAlgorithmDetails {
   326  		if details.algo == algo {
   327  			return details.name
   328  		}
   329  	}
   330  	return strconv.Itoa(int(algo))
   331  }
   332  
   333  // PublicKeyAlgorithm 公钥算法
   334  type PublicKeyAlgorithm int
   335  
   336  const (
   337  	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
   338  	RSA
   339  	DSA // Unsupported.
   340  	ECDSA
   341  	Ed25519
   342  	SM2      // 公钥算法添加SM2
   343  	ECDSAEXT // ecdsa_ext 扩展的ecdsa公钥算法
   344  )
   345  
   346  var publicKeyAlgoName = [...]string{
   347  	RSA:      "RSA",
   348  	DSA:      "DSA",
   349  	ECDSA:    "ECDSA",
   350  	Ed25519:  "Ed25519",
   351  	SM2:      "SM2",      // 公钥算法名称定义添加SM2
   352  	ECDSAEXT: "ECDSAEXT", // ecdsa_ext 扩展的ecdsa公钥算法
   353  }
   354  
   355  func (algo PublicKeyAlgorithm) String() string {
   356  	if 0 < algo && int(algo) < len(publicKeyAlgoName) {
   357  		return publicKeyAlgoName[algo]
   358  	}
   359  	return strconv.Itoa(int(algo))
   360  }
   361  
   362  // OIDs for signature algorithms
   363  //
   364  // pkcs-1 OBJECT IDENTIFIER ::= {
   365  //    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
   366  //
   367  //
   368  // RFC 3279 2.2.1 RSA Signature Algorithms
   369  //
   370  // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
   371  //
   372  // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
   373  //
   374  // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
   375  //
   376  // dsaWithSha1 OBJECT IDENTIFIER ::= {
   377  //    iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
   378  //
   379  // RFC 3279 2.2.3 ECDSA Signature Algorithm
   380  //
   381  // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
   382  // 	  iso(1) member-body(2) us(840) ansi-x962(10045)
   383  //    signatures(4) ecdsa-with-SHA1(1)}
   384  //
   385  //
   386  // RFC 4055 5 PKCS #1 Version 1.5
   387  //
   388  // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
   389  //
   390  // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
   391  //
   392  // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
   393  //
   394  //
   395  // RFC 5758 3.1 DSA Signature Algorithms
   396  //
   397  // dsaWithSha256 OBJECT IDENTIFIER ::= {
   398  //    joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
   399  //    csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
   400  //
   401  // RFC 5758 3.2 ECDSA Signature Algorithm
   402  //
   403  // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   404  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
   405  //
   406  // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   407  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
   408  //
   409  // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   410  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
   411  //
   412  //
   413  // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
   414  //
   415  // id-Ed25519   OBJECT IDENTIFIER ::= { 1 3 101 112 }
   416  
   417  //goland:noinspection GoUnusedGlobalVariable
   418  var (
   419  	oidSignatureMD2WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
   420  	oidSignatureMD5WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
   421  	oidSignatureSHA1WithRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
   422  	oidSignatureSHA256WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
   423  	oidSignatureSHA384WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
   424  	oidSignatureSHA512WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
   425  	oidSignatureRSAPSS          = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
   426  	oidSignatureDSAWithSHA1     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
   427  	oidSignatureDSAWithSHA256   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
   428  	oidSignatureECDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
   429  	oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
   430  	oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
   431  	oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
   432  	oidSignatureEd25519         = asn1.ObjectIdentifier{1, 3, 101, 112}
   433  
   434  	oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
   435  	oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
   436  	oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
   437  
   438  	oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
   439  
   440  	// oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
   441  	// but it's specified by ISO. Microsoft's makecert.exe has been known
   442  	// to produce certificates with this OID.
   443  	oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
   444  
   445  	// 国密相关算法标识定义,参考国密标准`GMT 0006-2012 密码应用标识规范.pdf`
   446  	oidSignatureSM2WithSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 501}
   447  	// oidSM3                 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 401, 1}
   448  	oidSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 401}
   449  
   450  	//oidSignatureECDSAEXTWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 5, 3, 2}
   451  	//oidSignatureECDSAEXTWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 5, 3, 3}
   452  	//oidSignatureECDSAEXTWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 5, 3, 4}
   453  )
   454  
   455  // 定义支持的签名算法细节
   456  var signatureAlgorithmDetails = []struct {
   457  	algo       SignatureAlgorithm
   458  	name       string
   459  	oid        asn1.ObjectIdentifier
   460  	pubKeyAlgo PublicKeyAlgorithm
   461  	hash       Hash
   462  	opts       crypto.SignerOpts
   463  }{
   464  	{MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, Hash(0), Hash(0) /* no value for MD2 */},
   465  	{MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, MD5, MD5},
   466  	{SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, SHA1, SHA1},
   467  	{SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, SHA1, SHA1},
   468  	{SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, SHA256, SHA256},
   469  	{SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, SHA384, SHA384},
   470  	{SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, SHA512, SHA512},
   471  	{SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, SHA256, &rsa.PSSOptions{
   472  		SaltLength: rsa.PSSSaltLengthEqualsHash,
   473  		Hash:       SHA256.HashFunc(),
   474  	}},
   475  	{SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, SHA384, &rsa.PSSOptions{
   476  		SaltLength: rsa.PSSSaltLengthEqualsHash,
   477  		Hash:       SHA384.HashFunc(),
   478  	}},
   479  	{SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, SHA512, &rsa.PSSOptions{
   480  		SaltLength: rsa.PSSSaltLengthEqualsHash,
   481  		Hash:       SHA512.HashFunc(),
   482  	}},
   483  	{DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, SHA1, SHA1},
   484  	{DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, SHA256, SHA256},
   485  	{ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, SHA1, ecbase.CreateEcSignerOpts(SHA1.HashFunc(), false)},
   486  	{ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, SHA256, ecbase.CreateEcSignerOpts(SHA256.HashFunc(), false)},
   487  	{ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, SHA384, ecbase.CreateEcSignerOpts(SHA384.HashFunc(), false)},
   488  	{ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, SHA512, ecbase.CreateEcSignerOpts(SHA512.HashFunc(), false)},
   489  	{PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, Hash(0), Hash(0) /* no pre-hashing */},
   490  	// 添加SM2相关签名算法定义, sm2签名算法既可以在内部做散列,也可以在外部做散列,但gmx509固定为在sm2签名算法内部做ZA散列计算,这里的散列算法设置为Hash(0)。
   491  	{SM2WithSM3, "SM2-with-SM3", oidSignatureSM2WithSM3, SM2, Hash(0), sm2.DefaultSM2SignerOption()},
   492  	// 添加ecdsa_ext扩展的ecdsa签名算法定义, 支持low-s处理
   493  	{ECDSAEXTWithSHA256, "ECDSA-EXT-SHA256", oidSignatureECDSAWithSHA256, ECDSAEXT, SHA256, ecbase.CreateEcSignerOpts(SHA256.HashFunc(), true)},
   494  	{ECDSAEXTWithSHA384, "ECDSA-EXT-SHA384", oidSignatureECDSAWithSHA384, ECDSAEXT, SHA384, ecbase.CreateEcSignerOpts(SHA384.HashFunc(), true)},
   495  	{ECDSAEXTWithSHA512, "ECDSA-EXT-SHA512", oidSignatureECDSAWithSHA512, ECDSAEXT, SHA512, ecbase.CreateEcSignerOpts(SHA512.HashFunc(), true)},
   496  }
   497  
   498  // hashToPSSParameters contains the DER encoded RSA PSS parameters for the
   499  // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
   500  // The parameters contain the following values:
   501  //   - hashAlgorithm contains the associated hash identifier with NULL parameters
   502  //   - maskGenAlgorithm always contains the default mgf1SHA1 identifier
   503  //   - saltLength contains the length of the associated hash
   504  //   - trailerField always contains the default trailerFieldBC value
   505  var hashToPSSParameters = map[Hash]asn1.RawValue{
   506  	SHA256: {FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 162, 3, 2, 1, 32}},
   507  	SHA384: {FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 162, 3, 2, 1, 48}},
   508  	SHA512: {FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 162, 3, 2, 1, 64}},
   509  }
   510  
   511  // pssParameters reflects the parameters in an AlgorithmIdentifier that
   512  // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
   513  type pssParameters struct {
   514  	// The following three fields are not marked as
   515  	// optional because the default values specify SHA-1,
   516  	// which is no longer suitable for use in signatures.
   517  	Hash         pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
   518  	MGF          pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
   519  	SaltLength   int                      `asn1:"explicit,tag:2"`
   520  	TrailerField int                      `asn1:"optional,explicit,tag:3,default:1"`
   521  }
   522  
   523  // 根据pkix.AlgorithmIdentifier获取签名算法
   524  func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
   525  	if ai.Algorithm.Equal(oidSignatureEd25519) {
   526  		// RFC 8410, Section 3
   527  		// > For all of the OIDs, the parameters MUST be absent.
   528  		if len(ai.Parameters.FullBytes) != 0 {
   529  			return UnknownSignatureAlgorithm
   530  		}
   531  	}
   532  
   533  	if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
   534  		// 国密签名算法走该分支
   535  		for _, details := range signatureAlgorithmDetails {
   536  			// TODO ecdsa与ecdsa+ext共用相同的oid,这里取哪一个?
   537  			if ai.Algorithm.Equal(details.oid) {
   538  				return details.algo
   539  			}
   540  		}
   541  		return UnknownSignatureAlgorithm
   542  	}
   543  
   544  	// RSA PSS is special because it encodes important parameters
   545  	// in the Parameters.
   546  
   547  	var params pssParameters
   548  	if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, &params); err != nil {
   549  		return UnknownSignatureAlgorithm
   550  	}
   551  
   552  	var mgf1HashFunc pkix.AlgorithmIdentifier
   553  	if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
   554  		return UnknownSignatureAlgorithm
   555  	}
   556  
   557  	// PSS is greatly overburdened with options. This code forces them into
   558  	// three buckets by requiring that the MGF1 hash function always match the
   559  	// message hash function (as recommended in RFC 3447, Section 8.1), that the
   560  	// salt length matches the hash length, and that the trailer field has the
   561  	// default value.
   562  	if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
   563  		!params.MGF.Algorithm.Equal(oidMGF1) ||
   564  		!mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
   565  		(len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
   566  		params.TrailerField != 1 {
   567  		return UnknownSignatureAlgorithm
   568  	}
   569  
   570  	switch {
   571  	case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
   572  		return SHA256WithRSAPSS
   573  	case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
   574  		return SHA384WithRSAPSS
   575  	case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
   576  		return SHA512WithRSAPSS
   577  	}
   578  
   579  	return UnknownSignatureAlgorithm
   580  }
   581  
   582  // RFC 3279, 2.3 Public Key Algorithms
   583  //
   584  // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   585  //
   586  //	rsadsi(113549) pkcs(1) 1 }
   587  //
   588  // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
   589  //
   590  // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   591  //
   592  //	x9-57(10040) x9cm(4) 1 }
   593  //
   594  // # RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
   595  //
   596  //	id-ecPublicKey OBJECT IDENTIFIER ::= {
   597  //	      iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
   598  var (
   599  	oidPublicKeyRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
   600  	oidPublicKeyDSA   = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
   601  	oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
   602  	// 自定义ecdsa_ext算法标识,`1.3.6.1.4.1`是ISO分配给私人企业的节点,`60387`是向IANA申请到的企业ID(zhaochuninhefei),`1`是该企业在该节点下的子节点,`2`是该子节点下的ecdsa_ext算法标识
   603  	oidPublicKeyECDSAEXT = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 60387, 1, 2}
   604  	oidPublicKeyEd25519  = oidSignatureEd25519
   605  	// SM2算法标识 参考`GMT 0006-2012 密码应用标识规范.pdf`的`附录A 商用密码领域中的相关oID定义`
   606  	oidPublicKeySM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301}
   607  	// // 通过asn1.Marshal(asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301})计算得出
   608  	// sm2OidFullBytes = []byte{6, 8, 42, 129, 28, 207, 85, 1, 130, 45}
   609  )
   610  
   611  // 根据OID获取公钥算法
   612  func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
   613  	switch {
   614  	case oid.Equal(oidPublicKeySM2):
   615  		return SM2
   616  	case oid.Equal(oidPublicKeyRSA):
   617  		return RSA
   618  	case oid.Equal(oidPublicKeyDSA):
   619  		return DSA
   620  	case oid.Equal(oidPublicKeyECDSA):
   621  		return ECDSA
   622  	case oid.Equal(oidPublicKeyECDSAEXT):
   623  		return ECDSAEXT
   624  	case oid.Equal(oidPublicKeyEd25519):
   625  		return Ed25519
   626  	}
   627  	return UnknownPublicKeyAlgorithm
   628  }
   629  
   630  // RFC 5480, 2.1.1.1. Named Curve
   631  //
   632  //	secp224r1 OBJECT IDENTIFIER ::= {
   633  //	  iso(1) identified-organization(3) certicom(132) curve(0) 33 }
   634  //
   635  //	secp256r1 OBJECT IDENTIFIER ::= {
   636  //	  iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
   637  //	  prime(1) 7 }
   638  //
   639  //	secp384r1 OBJECT IDENTIFIER ::= {
   640  //	  iso(1) identified-organization(3) certicom(132) curve(0) 34 }
   641  //
   642  //	secp521r1 OBJECT IDENTIFIER ::= {
   643  //	  iso(1) identified-organization(3) certicom(132) curve(0) 35 }
   644  //
   645  // NB: secp256r1 is equivalent to prime256v1
   646  var (
   647  	oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
   648  	oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
   649  	oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
   650  	oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
   651  	// SM2椭圆曲线参数标识 没有查到,用SM2算法标识代替
   652  	oidNamedCurveP256SM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301}
   653  )
   654  
   655  // 根据oid获取对应的椭圆曲线参数
   656  func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
   657  	switch {
   658  	case oid.Equal(oidNamedCurveP256SM2):
   659  		return sm2.P256Sm2()
   660  	case oid.Equal(oidNamedCurveP224):
   661  		return elliptic.P224()
   662  	case oid.Equal(oidNamedCurveP256):
   663  		return elliptic.P256()
   664  	case oid.Equal(oidNamedCurveP384):
   665  		return elliptic.P384()
   666  	case oid.Equal(oidNamedCurveP521):
   667  		return elliptic.P521()
   668  	}
   669  	return nil
   670  }
   671  
   672  // 根据椭圆曲线参数获取对应的oid
   673  func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
   674  	switch curve {
   675  	case sm2.P256Sm2():
   676  		return oidNamedCurveP256SM2, true
   677  	case elliptic.P224():
   678  		return oidNamedCurveP224, true
   679  	case elliptic.P256():
   680  		return oidNamedCurveP256, true
   681  	case elliptic.P384():
   682  		return oidNamedCurveP384, true
   683  	case elliptic.P521():
   684  		return oidNamedCurveP521, true
   685  	}
   686  
   687  	return nil, false
   688  }
   689  
   690  // KeyUsage 公钥用途,即证书用途。
   691  // KeyUsage represents the set of actions that are valid for a given key. It's
   692  // a bitmap of the KeyUsage* constants.
   693  type KeyUsage int
   694  
   695  const (
   696  	KeyUsageDigitalSignature  KeyUsage = 1 << iota // Digital Signature
   697  	KeyUsageContentCommitment                      // Non Repudiation
   698  	KeyUsageKeyEncipherment                        // Key Encipherment
   699  	KeyUsageDataEncipherment                       // Data Encipherment
   700  	KeyUsageKeyAgreement                           // Key Agreement
   701  	KeyUsageCertSign                               // Certificate Sign
   702  	KeyUsageCRLSign                                // CRL Sign
   703  	KeyUsageEncipherOnly                           // Encipher Only
   704  	KeyUsageDecipherOnly                           // Decipher Only
   705  )
   706  
   707  // RFC 5280, 4.2.1.12  Extended Key Usage
   708  //
   709  // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
   710  //
   711  // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
   712  //
   713  // id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
   714  // id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
   715  // id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
   716  // id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
   717  // id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
   718  // id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
   719  var (
   720  	oidExtKeyUsageAny                            = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
   721  	oidExtKeyUsageServerAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
   722  	oidExtKeyUsageClientAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
   723  	oidExtKeyUsageCodeSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
   724  	oidExtKeyUsageEmailProtection                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
   725  	oidExtKeyUsageIPSECEndSystem                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
   726  	oidExtKeyUsageIPSECTunnel                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
   727  	oidExtKeyUsageIPSECUser                      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
   728  	oidExtKeyUsageTimeStamping                   = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
   729  	oidExtKeyUsageOCSPSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
   730  	oidExtKeyUsageMicrosoftServerGatedCrypto     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
   731  	oidExtKeyUsageNetscapeServerGatedCrypto      = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
   732  	oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
   733  	oidExtKeyUsageMicrosoftKernelCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
   734  )
   735  
   736  // ExtKeyUsage 公钥(证书)扩展用途
   737  // ExtKeyUsage represents an extended set of actions that are valid for a given key.
   738  // Each of the ExtKeyUsage* constants define a unique action.
   739  type ExtKeyUsage int
   740  
   741  const (
   742  	ExtKeyUsageAny                        ExtKeyUsage = iota // Any Extended Key Usage
   743  	ExtKeyUsageServerAuth                                    // TLS Web Server Authentication
   744  	ExtKeyUsageClientAuth                                    // TLS Web Client Authentication
   745  	ExtKeyUsageCodeSigning                                   // Code Signing
   746  	ExtKeyUsageEmailProtection                               // E-mail Protection
   747  	ExtKeyUsageIPSECEndSystem                                // IPSec End System
   748  	ExtKeyUsageIPSECTunnel                                   // IPSec Tunnel
   749  	ExtKeyUsageIPSECUser                                     // IPSec User
   750  	ExtKeyUsageTimeStamping                                  // Time Stamping
   751  	ExtKeyUsageOCSPSigning                                   // OCSP Signing
   752  	ExtKeyUsageMicrosoftServerGatedCrypto                    // Microsoft Server Gated Crypto
   753  	ExtKeyUsageNetscapeServerGatedCrypto                     // Netscape Server Gated Crypto
   754  	ExtKeyUsageMicrosoftCommercialCodeSigning
   755  	ExtKeyUsageMicrosoftKernelCodeSigning
   756  )
   757  
   758  // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
   759  var extKeyUsageOIDs = []struct {
   760  	extKeyUsage ExtKeyUsage
   761  	oid         asn1.ObjectIdentifier
   762  }{
   763  	{ExtKeyUsageAny, oidExtKeyUsageAny},
   764  	{ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
   765  	{ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
   766  	{ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
   767  	{ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
   768  	{ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
   769  	{ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
   770  	{ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
   771  	{ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
   772  	{ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
   773  	{ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
   774  	{ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
   775  	{ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
   776  	{ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
   777  }
   778  
   779  func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
   780  	for _, pair := range extKeyUsageOIDs {
   781  		if oid.Equal(pair.oid) {
   782  			return pair.extKeyUsage, true
   783  		}
   784  	}
   785  	return
   786  }
   787  
   788  func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
   789  	for _, pair := range extKeyUsageOIDs {
   790  		if eku == pair.extKeyUsage {
   791  			return pair.oid, true
   792  		}
   793  	}
   794  	return
   795  }
   796  
   797  // Certificate gmx509证书结构体
   798  //
   799  //	A Certificate represents an X.509 certificate.
   800  type Certificate struct {
   801  	// 完整的 ASN1 DER 证书字节数组(证书+签名算法+签名)
   802  	// Complete ASN.1 DER content (certificate, signature algorithm and signature).
   803  	Raw []byte
   804  	// 签名内容的原始 ASN.1 DER字节数组
   805  	// Certificate part of raw ASN.1 DER content.
   806  	RawTBSCertificate []byte
   807  	// SubjectPublicKeyInfo的DER字节数组
   808  	// DER encoded SubjectPublicKeyInfo.
   809  	RawSubjectPublicKeyInfo []byte
   810  	// 证书拥有者的DER字节数组
   811  	// DER encoded Subject
   812  	RawSubject []byte
   813  	// 证书签署者的DER字节数组
   814  	// DER encoded Issuer
   815  	RawIssuer []byte
   816  
   817  	// 签名DER字节数组
   818  	Signature []byte
   819  	// 签名算法
   820  	SignatureAlgorithm SignatureAlgorithm
   821  
   822  	// 证书拥有者的公钥算法
   823  	PublicKeyAlgorithm PublicKeyAlgorithm
   824  	// 证书拥有者的公钥(证书的核心内容)
   825  	PublicKey interface{}
   826  
   827  	// 证书版本
   828  	Version int
   829  	// 证书序列号
   830  	SerialNumber *big.Int
   831  	// 证书签署者(提供私钥对RawTBSCertificate进行签名)
   832  	Issuer pkix.Name
   833  	// 证书拥有者(该证书的核心公钥的拥有者)
   834  	Subject pkix.Name
   835  	// 证书有效期间
   836  	// Validity bounds.
   837  	NotBefore, NotAfter time.Time
   838  	// 证书公钥的用途
   839  	KeyUsage KeyUsage
   840  
   841  	// Extensions contains raw X.509 extensions. When parsing certificates,
   842  	// this can be used to extract non-critical extensions that are not
   843  	// parsed by this package. When marshaling certificates, the Extensions
   844  	// field is ignored, see ExtraExtensions.
   845  	Extensions []pkix.Extension
   846  
   847  	// ExtraExtensions contains extensions to be copied, raw, into any
   848  	// marshaled certificates. Values override any extensions that would
   849  	// otherwise be produced based on the other fields. The ExtraExtensions
   850  	// field is not populated when parsing certificates, see Extensions.
   851  	ExtraExtensions []pkix.Extension
   852  
   853  	// UnhandledCriticalExtensions contains a list of extension IDs that
   854  	// were not (fully) processed when parsing. Verify will fail if this
   855  	// slice is non-empty, unless verification is delegated to an OS
   856  	// library which understands all the critical extensions.
   857  	//
   858  	// Users can access these extensions using Extensions and can remove
   859  	// elements from this slice if they believe that they have been
   860  	// handled.
   861  	UnhandledCriticalExtensions []asn1.ObjectIdentifier
   862  
   863  	// 公钥扩展用途
   864  	// Sequence of extended key usages.
   865  	ExtKeyUsage []ExtKeyUsage
   866  	// 未知的公钥扩展用途
   867  	// Encountered extended key usages unknown to this package.
   868  	UnknownExtKeyUsage []asn1.ObjectIdentifier
   869  
   870  	// 基础约束是否有效,控制 IsCA 与 MaxPathLen 是否有效
   871  	// BasicConstraintsValid indicates whether IsCA, MaxPathLen,
   872  	// and MaxPathLenZero are valid.
   873  	BasicConstraintsValid bool
   874  	// 是否CA证书
   875  	//  IsCA为false时,表示该证书不是CA证书,MaxPathLen无效。
   876  	//  IsCA为true时,表示该证书是CA证书,此时MaxPathLen表示该证书所属证书信任链中的中间CA证书的数量上限。
   877  	IsCA bool
   878  	// MaxPathLen and MaxPathLenZero indicate the presence and
   879  	// value of the BasicConstraints' "pathLenConstraint".
   880  	//
   881  	// When parsing a certificate, a positive non-zero MaxPathLen
   882  	// means that the field was specified, -1 means it was unset,
   883  	// and MaxPathLenZero being true mean that the field was
   884  	// explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
   885  	// should be treated equivalent to -1 (unset).
   886  	//
   887  	// When generating a certificate, an unset pathLenConstraint
   888  	// can be requested with either MaxPathLen == -1 or using the
   889  	// zero value for both MaxPathLen and MaxPathLenZero.
   890  	MaxPathLen int
   891  	// MaxPathLenZero indicates that BasicConstraintsValid==true
   892  	// and MaxPathLen==0 should be interpreted as an actual
   893  	// maximum path length of zero. Otherwise, that combination is
   894  	// interpreted as MaxPathLen not being set.
   895  	MaxPathLenZero bool
   896  
   897  	// 证书拥有者密钥ID
   898  	// 以sm2公钥为例,计算方式为 将椭圆曲线上的公钥座标转换为字节数组再做sm3散列
   899  	SubjectKeyId []byte
   900  	// 证书签署者密钥ID(自签名时,AuthorityKeyId就是自己的SubjectKeyId;由父证书签名时,就是父证书的SubjectKeyId)
   901  	AuthorityKeyId []byte
   902  
   903  	// RFC 5280, 4.2.2.1 (Authority Information Access)
   904  	OCSPServer            []string
   905  	IssuingCertificateURL []string
   906  
   907  	// Subject Alternate Name values. (Note that these values may not be valid
   908  	// if invalid values were contained within a parsed certificate. For
   909  	// example, an element of DNSNames may not be a valid DNS domain name.)
   910  	// go1.15开始废弃CommonName,使用SAN扩展信息。
   911  	// SAN扩展信息由下面四个字段组成。
   912  	DNSNames       []string
   913  	EmailAddresses []string
   914  	IPAddresses    []net.IP
   915  	URIs           []*url.URL
   916  
   917  	// Name constraints
   918  	PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
   919  	PermittedDNSDomains         []string
   920  	ExcludedDNSDomains          []string
   921  	PermittedIPRanges           []*net.IPNet
   922  	ExcludedIPRanges            []*net.IPNet
   923  	PermittedEmailAddresses     []string
   924  	ExcludedEmailAddresses      []string
   925  	PermittedURIDomains         []string
   926  	ExcludedURIDomains          []string
   927  
   928  	// CRL Distribution Points
   929  	CRLDistributionPoints []string
   930  
   931  	PolicyIdentifiers []asn1.ObjectIdentifier
   932  }
   933  
   934  // ErrUnsupportedAlgorithm results from attempting to perform an operation that
   935  // involves algorithms that are not currently implemented.
   936  var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
   937  
   938  // An InsecureAlgorithmError
   939  type InsecureAlgorithmError SignatureAlgorithm
   940  
   941  func (e InsecureAlgorithmError) Error() string {
   942  	return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
   943  }
   944  
   945  // ConstraintViolationError results when a requested usage is not permitted by
   946  // a certificate. For example: checking a signature when the public key isn't a
   947  // certificate signing key.
   948  type ConstraintViolationError struct{}
   949  
   950  func (ConstraintViolationError) Error() string {
   951  	return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
   952  }
   953  
   954  func (c *Certificate) Equal(other *Certificate) bool {
   955  	if c == nil || other == nil {
   956  		return c == other
   957  	}
   958  	return bytes.Equal(c.Raw, other.Raw)
   959  }
   960  
   961  func (c *Certificate) hasSANExtension() bool {
   962  	return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
   963  }
   964  
   965  // CheckSignatureFrom 检查对c做的签名是否是父证书拥有者的有效签名(使用父证书中的公钥验签)
   966  // CheckSignatureFrom verifies that the signature on c is a valid signature
   967  // from parent.
   968  func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
   969  	// RFC 5280, 4.2.1.9:
   970  	// "If the basic constraints extension is not present in a version 3
   971  	// certificate, or the extension is present but the cA boolean is not
   972  	// asserted, then the certified public key MUST NOT be used to verify
   973  	// certificate signatures."
   974  	if parent.Version == 3 && !parent.BasicConstraintsValid ||
   975  		parent.BasicConstraintsValid && !parent.IsCA {
   976  		return ConstraintViolationError{}
   977  	}
   978  
   979  	if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
   980  		return ConstraintViolationError{}
   981  	}
   982  
   983  	if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
   984  		return ErrUnsupportedAlgorithm
   985  	}
   986  
   987  	// TODO(agl): don't ignore the path length constraint.
   988  
   989  	return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
   990  }
   991  
   992  // CheckSignature 使用c的公钥检查签名是否有效
   993  //   - algo : 签名算法
   994  //   - signed : 签名内容
   995  //   - signature : 签名DER字节数组
   996  //
   997  // CheckSignature verifies that signature is a valid signature over signed from
   998  // c's public key.
   999  func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
  1000  	return checkSignature(algo, signed, signature, c.PublicKey)
  1001  }
  1002  
  1003  func (c *Certificate) hasNameConstraints() bool {
  1004  	return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
  1005  }
  1006  
  1007  func (c *Certificate) getSANExtension() []byte {
  1008  	for _, e := range c.Extensions {
  1009  		if e.Id.Equal(oidExtensionSubjectAltName) {
  1010  			return e.Value
  1011  		}
  1012  	}
  1013  	return nil
  1014  }
  1015  
  1016  func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
  1017  	return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
  1018  }
  1019  
  1020  // checkSignature检查签名是否有效
  1021  // algo : 签名算法
  1022  // signed : 签名内容
  1023  // signature : 签名DER字节数组
  1024  // publicKey : 签名者公钥
  1025  //
  1026  // CheckSignature verifies that signature is a valid signature over signed from
  1027  // a crypto.PublicKey.
  1028  func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
  1029  	var hashType Hash
  1030  	var pubKeyAlgo PublicKeyAlgorithm
  1031  	var opts crypto.SignerOpts
  1032  
  1033  	for _, details := range signatureAlgorithmDetails {
  1034  		if details.algo == algo {
  1035  			hashType = details.hash
  1036  			pubKeyAlgo = details.pubKeyAlgo
  1037  			opts = details.opts
  1038  			break
  1039  		}
  1040  	}
  1041  
  1042  	// 关于ecdsa_ext的特殊处理
  1043  	if pubKeyAlgo == ECDSAEXT {
  1044  		if pubKey, ok := publicKey.(*ecdsa.PublicKey); ok {
  1045  			publicKey = ecdsa_ext.ConvPubKeyFromOrigin(pubKey)
  1046  		}
  1047  	}
  1048  
  1049  	switch hashType {
  1050  	case Hash(0):
  1051  		// ed25519与sm2不需要对消息做摘要计算
  1052  		if pubKeyAlgo != Ed25519 && pubKeyAlgo != SM2 {
  1053  			return ErrUnsupportedAlgorithm
  1054  		}
  1055  	case MD5:
  1056  		return InsecureAlgorithmError(algo)
  1057  	default:
  1058  		if !hashType.Available() {
  1059  			return ErrUnsupportedAlgorithm
  1060  		}
  1061  		h := hashType.New()
  1062  		h.Write(signed)
  1063  		signed = h.Sum(nil)
  1064  	}
  1065  
  1066  	switch pub := publicKey.(type) {
  1067  	case *sm2.PublicKey:
  1068  		if pubKeyAlgo != SM2 {
  1069  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
  1070  		}
  1071  		if sm2Opts, ok := opts.(*sm2.SM2SignerOption); ok {
  1072  			_, err = pub.EcVerify(signed, signature, sm2Opts)
  1073  			if err != nil {
  1074  				fmt.Println("sm2 checkSignature 失败, 调用栈如下:")
  1075  				return errors.New("x509: SM2 verification failure")
  1076  			}
  1077  		} else {
  1078  			return errors.New("x509: 内建签名算法列表中sm2的opts类型不正确")
  1079  		}
  1080  		return nil
  1081  	case *rsa.PublicKey:
  1082  		if pubKeyAlgo != RSA {
  1083  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
  1084  		}
  1085  		if algo.isRSAPSS() {
  1086  			return rsa.VerifyPSS(pub, hashType.HashFunc(), signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
  1087  		} else {
  1088  			return rsa.VerifyPKCS1v15(pub, hashType.HashFunc(), signed, signature)
  1089  		}
  1090  	case *ecdsa.PublicKey:
  1091  		if pubKeyAlgo != ECDSA && pubKeyAlgo != ECDSAEXT {
  1092  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
  1093  		}
  1094  		if ecOpts, ok := opts.(ecbase.EcSignerOpts); ok {
  1095  			if ecOpts.NeedLowS() {
  1096  				// 检查签名s值是否low-s
  1097  				isLow, err := ecdsa_ext.IsSigLowS(pub, signature)
  1098  				if err != nil {
  1099  					return err
  1100  				}
  1101  				if !isLow {
  1102  					return errors.New("ecdsa验签失败, 签名s值不是low-s值")
  1103  				}
  1104  			}
  1105  			if !ecdsa.VerifyASN1(pub, signed, signature) {
  1106  				fmt.Println("ecdsa checkSignature 失败, 调用栈如下:")
  1107  				log.Fatal("x509: ECDSA verification failure, 公钥SKI: , 签名主体:, 签名: ", CreateEllipticSKI(pub.Curve, pub.X, pub.Y), hex.EncodeToString(signed), hex.EncodeToString(signature))
  1108  				return errors.New("x509: ECDSA verification failure")
  1109  			}
  1110  		} else {
  1111  			return errors.New("x509: 内建签名算法列表中ecdsa的opts类型不正确")
  1112  		}
  1113  		return nil
  1114  	case *ecdsa_ext.PublicKey:
  1115  		if pubKeyAlgo != ECDSA && pubKeyAlgo != ECDSAEXT {
  1116  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
  1117  		}
  1118  		if ecOpts, ok := opts.(ecbase.EcSignerOpts); ok {
  1119  			_, err = pub.EcVerify(signed, signature, ecOpts)
  1120  			if err != nil {
  1121  				fmt.Println("ecdsa_ext checkSignature 失败, 调用栈如下:")
  1122  				log.Fatal("x509: ECDSAEXT verification failure, 公钥SKI: , 签名主体: , 签名: ", CreateEllipticSKI(pub.Curve, pub.X, pub.Y), hex.EncodeToString(signed), hex.EncodeToString(signature))
  1123  				return fmt.Errorf("x509: ECDSAEXT verification failure: %s", err.Error())
  1124  			}
  1125  		} else {
  1126  			return errors.New("x509: 内建签名算法列表中ecdsa的opts类型不正确")
  1127  		}
  1128  		return nil
  1129  	case ed25519.PublicKey:
  1130  		if pubKeyAlgo != Ed25519 {
  1131  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
  1132  		}
  1133  		if !ed25519.Verify(pub, signed, signature) {
  1134  			return errors.New("x509: Ed25519 verification failure")
  1135  		}
  1136  		return nil
  1137  	}
  1138  	return ErrUnsupportedAlgorithm
  1139  }
  1140  
  1141  // CheckCRLSignature 检查证书撤销列表CRL是否由c签名。
  1142  // CheckCRLSignature checks that the signature in crl is from c.
  1143  func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
  1144  	algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
  1145  	return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
  1146  }
  1147  
  1148  type UnhandledCriticalExtension struct{}
  1149  
  1150  func (h UnhandledCriticalExtension) Error() string {
  1151  	return "x509: unhandled critical extension"
  1152  }
  1153  
  1154  type basicConstraints struct {
  1155  	IsCA       bool `asn1:"optional"`
  1156  	MaxPathLen int  `asn1:"optional,default:-1"`
  1157  }
  1158  
  1159  // RFC 5280 4.2.1.4
  1160  type policyInformation struct {
  1161  	Policy asn1.ObjectIdentifier
  1162  	// policyQualifiers omitted
  1163  }
  1164  
  1165  const (
  1166  	nameTypeEmail = 1
  1167  	nameTypeDNS   = 2
  1168  	nameTypeURI   = 6
  1169  	nameTypeIP    = 7
  1170  )
  1171  
  1172  // RFC 5280, 4.2.2.1
  1173  type authorityInfoAccess struct {
  1174  	Method   asn1.ObjectIdentifier
  1175  	Location asn1.RawValue
  1176  }
  1177  
  1178  // RFC 5280, 4.2.1.14
  1179  type distributionPoint struct {
  1180  	DistributionPoint distributionPointName `asn1:"optional,tag:0"`
  1181  	Reason            asn1.BitString        `asn1:"optional,tag:1"`
  1182  	CRLIssuer         asn1.RawValue         `asn1:"optional,tag:2"`
  1183  }
  1184  
  1185  type distributionPointName struct {
  1186  	FullName     []asn1.RawValue  `asn1:"optional,tag:0"`
  1187  	RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
  1188  }
  1189  
  1190  func reverseBitsInAByte(in byte) byte {
  1191  	b1 := in>>4 | in<<4
  1192  	b2 := b1>>2&0x33 | b1<<2&0xcc
  1193  	b3 := b2>>1&0x55 | b2<<1&0xaa
  1194  	return b3
  1195  }
  1196  
  1197  // asn1BitLength returns the bit-length of bitString by considering the
  1198  // most-significant bit in a byte to be the "first" bit. This convention
  1199  // matches ASN.1, but differs from almost everything else.
  1200  func asn1BitLength(bitString []byte) int {
  1201  	bitLen := len(bitString) * 8
  1202  
  1203  	for i := range bitString {
  1204  		b := bitString[len(bitString)-i-1]
  1205  
  1206  		for bit := uint(0); bit < 8; bit++ {
  1207  			if (b>>bit)&1 == 1 {
  1208  				return bitLen
  1209  			}
  1210  			bitLen--
  1211  		}
  1212  	}
  1213  
  1214  	return 0
  1215  }
  1216  
  1217  // x509证书扩展信息oid定义
  1218  var (
  1219  	oidExtensionSubjectKeyId          = []int{2, 5, 29, 14}
  1220  	oidExtensionKeyUsage              = []int{2, 5, 29, 15}
  1221  	oidExtensionExtendedKeyUsage      = []int{2, 5, 29, 37}
  1222  	oidExtensionAuthorityKeyId        = []int{2, 5, 29, 35}
  1223  	oidExtensionBasicConstraints      = []int{2, 5, 29, 19}
  1224  	oidExtensionSubjectAltName        = []int{2, 5, 29, 17}
  1225  	oidExtensionCertificatePolicies   = []int{2, 5, 29, 32}
  1226  	oidExtensionNameConstraints       = []int{2, 5, 29, 30}
  1227  	oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
  1228  	oidExtensionAuthorityInfoAccess   = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
  1229  	oidExtensionCRLNumber             = []int{2, 5, 29, 20}
  1230  
  1231  	// 扩展签名算法OID,`1.3.6.1.4.1`是ISO分配给私人企业的节点,`60387`是向IANA申请到的企业ID(zhaochuninhefei),`1`是该企业下的子节点,`1`是该子节点下的扩展签名算法OID
  1232  	oidExtensionSignatureAlgorithm = []int{1, 3, 6, 1, 4, 1, 60387, 1, 1}
  1233  )
  1234  
  1235  var (
  1236  	oidAuthorityInfoAccessOcsp    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
  1237  	oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
  1238  )
  1239  
  1240  // oidNotInExtensions reports whether an extension with the given oid exists in
  1241  // extensions.
  1242  func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
  1243  	for _, e := range extensions {
  1244  		if e.Id.Equal(oid) {
  1245  			return true
  1246  		}
  1247  	}
  1248  	return false
  1249  }
  1250  
  1251  // go1.15开始废弃CommonName,改为使用SAN(Subject Alternative Name)扩展。
  1252  // marshalSANs marshals a list of addresses into a the contents of an X.509
  1253  // SubjectAlternativeName extension.
  1254  func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
  1255  	var rawValues []asn1.RawValue
  1256  	for _, name := range dnsNames {
  1257  		if err := isIA5String(name); err != nil {
  1258  			return nil, err
  1259  		}
  1260  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
  1261  	}
  1262  	for _, email := range emailAddresses {
  1263  		if err := isIA5String(email); err != nil {
  1264  			return nil, err
  1265  		}
  1266  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
  1267  	}
  1268  	for _, rawIP := range ipAddresses {
  1269  		// If possible, we always want to encode IPv4 addresses in 4 bytes.
  1270  		ip := rawIP.To4()
  1271  		if ip == nil {
  1272  			ip = rawIP
  1273  		}
  1274  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
  1275  	}
  1276  	for _, uri := range uris {
  1277  		uriStr := uri.String()
  1278  		if err := isIA5String(uriStr); err != nil {
  1279  			return nil, err
  1280  		}
  1281  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
  1282  	}
  1283  	return asn1.Marshal(rawValues)
  1284  }
  1285  
  1286  func isIA5String(s string) error {
  1287  	for _, r := range s {
  1288  		// Per RFC5280 "IA5String is limited to the set of ASCII characters"
  1289  		if r > unicode.MaxASCII {
  1290  			return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
  1291  		}
  1292  	}
  1293  
  1294  	return nil
  1295  }
  1296  
  1297  // 构建证书扩展信息
  1298  func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
  1299  	// 扩展信息最大数量增加到11, 放置gmx509定义的签名算法
  1300  	ret = make([]pkix.Extension, 11 /* maximum number of elements. */)
  1301  	n := 0
  1302  
  1303  	// 添加KeyUsage
  1304  	if template.KeyUsage != 0 &&
  1305  		!oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
  1306  		ret[n], err = marshalKeyUsage(template.KeyUsage)
  1307  		if err != nil {
  1308  			return nil, err
  1309  		}
  1310  		n++
  1311  	}
  1312  
  1313  	// 添加ExtKeyUsage
  1314  	if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
  1315  		!oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
  1316  		ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
  1317  		if err != nil {
  1318  			return nil, err
  1319  		}
  1320  		n++
  1321  	}
  1322  
  1323  	// 添加BasicConstraints
  1324  	if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
  1325  		ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
  1326  		if err != nil {
  1327  			return nil, err
  1328  		}
  1329  		n++
  1330  	}
  1331  
  1332  	// 添加subjectKeyId
  1333  	if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
  1334  		ret[n].Id = oidExtensionSubjectKeyId
  1335  		ret[n].Value, err = asn1.Marshal(subjectKeyId)
  1336  		if err != nil {
  1337  			return
  1338  		}
  1339  		n++
  1340  	}
  1341  
  1342  	// 添加authorityKeyId
  1343  	if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
  1344  		ret[n].Id = oidExtensionAuthorityKeyId
  1345  		ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
  1346  		if err != nil {
  1347  			return
  1348  		}
  1349  		n++
  1350  	}
  1351  
  1352  	// 添加authorityInfoAccess
  1353  	if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
  1354  		!oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
  1355  		ret[n].Id = oidExtensionAuthorityInfoAccess
  1356  		var aiaValues []authorityInfoAccess
  1357  		for _, name := range template.OCSPServer {
  1358  			aiaValues = append(aiaValues, authorityInfoAccess{
  1359  				Method:   oidAuthorityInfoAccessOcsp,
  1360  				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1361  			})
  1362  		}
  1363  		for _, name := range template.IssuingCertificateURL {
  1364  			aiaValues = append(aiaValues, authorityInfoAccess{
  1365  				Method:   oidAuthorityInfoAccessIssuers,
  1366  				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1367  			})
  1368  		}
  1369  		ret[n].Value, err = asn1.Marshal(aiaValues)
  1370  		if err != nil {
  1371  			return
  1372  		}
  1373  		n++
  1374  	}
  1375  
  1376  	// 添加SAN
  1377  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
  1378  		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1379  		ret[n].Id = oidExtensionSubjectAltName
  1380  		// From RFC 5280, Section 4.2.1.6:
  1381  		// “If the subject field contains an empty sequence ... then
  1382  		// subjectAltName extension ... is marked as critical”
  1383  		ret[n].Critical = subjectIsEmpty
  1384  		ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
  1385  		if err != nil {
  1386  			return
  1387  		}
  1388  		n++
  1389  	}
  1390  
  1391  	// 添加PolicyIdentifiers
  1392  	if len(template.PolicyIdentifiers) > 0 &&
  1393  		!oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
  1394  		ret[n], err = marshalCertificatePolicies(template.PolicyIdentifiers)
  1395  		if err != nil {
  1396  			return nil, err
  1397  		}
  1398  		n++
  1399  	}
  1400  
  1401  	// 添加NameConstraints
  1402  	if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
  1403  		len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
  1404  		len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
  1405  		len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
  1406  		!oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
  1407  		ret[n].Id = oidExtensionNameConstraints
  1408  		ret[n].Critical = template.PermittedDNSDomainsCritical
  1409  
  1410  		ipAndMask := func(ipNet *net.IPNet) []byte {
  1411  			maskedIP := ipNet.IP.Mask(ipNet.Mask)
  1412  			ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
  1413  			ipAndMask = append(ipAndMask, maskedIP...)
  1414  			ipAndMask = append(ipAndMask, ipNet.Mask...)
  1415  			return ipAndMask
  1416  		}
  1417  
  1418  		serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
  1419  			var b cryptobyte.Builder
  1420  
  1421  			for _, name := range dns {
  1422  				if err = isIA5String(name); err != nil {
  1423  					return nil, err
  1424  				}
  1425  
  1426  				b.AddASN1(cryptobyteasn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1427  					b.AddASN1(cryptobyteasn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
  1428  						b.AddBytes([]byte(name))
  1429  					})
  1430  				})
  1431  			}
  1432  
  1433  			for _, ipNet := range ips {
  1434  				b.AddASN1(cryptobyteasn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1435  					b.AddASN1(cryptobyteasn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
  1436  						b.AddBytes(ipAndMask(ipNet))
  1437  					})
  1438  				})
  1439  			}
  1440  
  1441  			for _, email := range emails {
  1442  				if err = isIA5String(email); err != nil {
  1443  					return nil, err
  1444  				}
  1445  
  1446  				b.AddASN1(cryptobyteasn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1447  					b.AddASN1(cryptobyteasn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
  1448  						b.AddBytes([]byte(email))
  1449  					})
  1450  				})
  1451  			}
  1452  
  1453  			for _, uriDomain := range uriDomains {
  1454  				if err = isIA5String(uriDomain); err != nil {
  1455  					return nil, err
  1456  				}
  1457  
  1458  				b.AddASN1(cryptobyteasn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1459  					b.AddASN1(cryptobyteasn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
  1460  						b.AddBytes([]byte(uriDomain))
  1461  					})
  1462  				})
  1463  			}
  1464  
  1465  			return b.Bytes()
  1466  		}
  1467  
  1468  		permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
  1469  		if err != nil {
  1470  			return nil, err
  1471  		}
  1472  
  1473  		excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
  1474  		if err != nil {
  1475  			return nil, err
  1476  		}
  1477  
  1478  		var b cryptobyte.Builder
  1479  		b.AddASN1(cryptobyteasn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1480  			if len(permitted) > 0 {
  1481  				b.AddASN1(cryptobyteasn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
  1482  					b.AddBytes(permitted)
  1483  				})
  1484  			}
  1485  
  1486  			if len(excluded) > 0 {
  1487  				b.AddASN1(cryptobyteasn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
  1488  					b.AddBytes(excluded)
  1489  				})
  1490  			}
  1491  		})
  1492  
  1493  		ret[n].Value, err = b.Bytes()
  1494  		if err != nil {
  1495  			return nil, err
  1496  		}
  1497  		n++
  1498  	}
  1499  
  1500  	// 添加CRLDistributionPoints
  1501  	if len(template.CRLDistributionPoints) > 0 &&
  1502  		!oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
  1503  		ret[n].Id = oidExtensionCRLDistributionPoints
  1504  
  1505  		var crlDp []distributionPoint
  1506  		for _, name := range template.CRLDistributionPoints {
  1507  			dp := distributionPoint{
  1508  				DistributionPoint: distributionPointName{
  1509  					FullName: []asn1.RawValue{
  1510  						{Tag: 6, Class: 2, Bytes: []byte(name)},
  1511  					},
  1512  				},
  1513  			}
  1514  			crlDp = append(crlDp, dp)
  1515  		}
  1516  
  1517  		ret[n].Value, err = asn1.Marshal(crlDp)
  1518  		if err != nil {
  1519  			return
  1520  		}
  1521  		n++
  1522  	}
  1523  
  1524  	// Adding another extension here? Remember to update the maximum number
  1525  	// of elements in the make() at the top of the function and the list of
  1526  	// template fields used in CreateCertificate documentation.
  1527  
  1528  	// TODO 添加gmx509的签名算法 SignatureAlgorithm
  1529  	if template.SignatureAlgorithm > 0 && !oidInExtensions(oidExtensionSignatureAlgorithm, template.ExtraExtensions) {
  1530  		fmt.Println("x509证书签名算法: ", template.SignatureAlgorithm.String())
  1531  		ret[n] = marshalSignatureAlgorithm(template.SignatureAlgorithm)
  1532  		n++
  1533  	}
  1534  
  1535  	return append(ret[:n], template.ExtraExtensions...), nil
  1536  }
  1537  
  1538  func marshalSignatureAlgorithm(signAlg SignatureAlgorithm) pkix.Extension {
  1539  	val := make([]byte, 4)
  1540  	binary.BigEndian.PutUint32(val, uint32(signAlg))
  1541  	ext := pkix.Extension{
  1542  		Id:       oidExtensionSignatureAlgorithm,
  1543  		Critical: false,
  1544  		Value:    val,
  1545  	}
  1546  	return ext
  1547  }
  1548  
  1549  func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
  1550  	ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
  1551  
  1552  	var a [2]byte
  1553  	a[0] = reverseBitsInAByte(byte(ku))
  1554  	a[1] = reverseBitsInAByte(byte(ku >> 8))
  1555  
  1556  	l := 1
  1557  	if a[1] != 0 {
  1558  		l = 2
  1559  	}
  1560  
  1561  	bitString := a[:l]
  1562  	var err error
  1563  	ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
  1564  	if err != nil {
  1565  		return ext, err
  1566  	}
  1567  	return ext, nil
  1568  }
  1569  
  1570  func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
  1571  	ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
  1572  
  1573  	oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
  1574  	for i, u := range extUsages {
  1575  		if oid, ok := oidFromExtKeyUsage(u); ok {
  1576  			oids[i] = oid
  1577  		} else {
  1578  			return ext, errors.New("x509: unknown extended key usage")
  1579  		}
  1580  	}
  1581  
  1582  	copy(oids[len(extUsages):], unknownUsages)
  1583  
  1584  	var err error
  1585  	ext.Value, err = asn1.Marshal(oids)
  1586  	if err != nil {
  1587  		return ext, err
  1588  	}
  1589  	return ext, nil
  1590  }
  1591  
  1592  func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
  1593  	ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
  1594  	// Leaving MaxPathLen as zero indicates that no maximum path
  1595  	// length is desired, unless MaxPathLenZero is set. A value of
  1596  	// -1 causes encoding/asn1 to omit the value as desired.
  1597  	if maxPathLen == 0 && !maxPathLenZero {
  1598  		maxPathLen = -1
  1599  	}
  1600  	var err error
  1601  	ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
  1602  	if err != nil {
  1603  		return ext, nil
  1604  	}
  1605  	return ext, nil
  1606  }
  1607  
  1608  func marshalCertificatePolicies(policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
  1609  	ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
  1610  	policies := make([]policyInformation, len(policyIdentifiers))
  1611  	for i, policy := range policyIdentifiers {
  1612  		policies[i].Policy = policy
  1613  	}
  1614  	var err error
  1615  	ext.Value, err = asn1.Marshal(policies)
  1616  	if err != nil {
  1617  		return ext, err
  1618  	}
  1619  	return ext, nil
  1620  }
  1621  
  1622  func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
  1623  	var ret []pkix.Extension
  1624  
  1625  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
  1626  		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1627  		sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
  1628  		if err != nil {
  1629  			return nil, err
  1630  		}
  1631  
  1632  		ret = append(ret, pkix.Extension{
  1633  			Id:    oidExtensionSubjectAltName,
  1634  			Value: sanBytes,
  1635  		})
  1636  	}
  1637  
  1638  	// 添加 oidExtensionSignatureAlgorithm
  1639  	if template.SignatureAlgorithm > 0 && !oidInExtensions(oidExtensionSignatureAlgorithm, template.ExtraExtensions) {
  1640  		ret = append(ret, marshalSignatureAlgorithm(template.SignatureAlgorithm))
  1641  	}
  1642  
  1643  	return append(ret, template.ExtraExtensions...), nil
  1644  }
  1645  
  1646  // 获取证书主题subject(证书拥有者)的字节数组
  1647  func subjectBytes(cert *Certificate) ([]byte, error) {
  1648  	if len(cert.RawSubject) > 0 {
  1649  		return cert.RawSubject, nil
  1650  	}
  1651  
  1652  	return asn1.Marshal(cert.Subject.ToRDNSequence())
  1653  }
  1654  
  1655  // signingParamsForPublicKey 根据传入的公钥与签名算法获取签名参数(签名算法、散列算法与签名算法参数)
  1656  //
  1657  //	根据传入的公钥获取默认的签名参数,再根据传入的requestedSigAlgo从内建定义的签名算法列表中检查公钥类型是否匹配,并获取定义好的签名参数,覆盖之前的默认值。
  1658  //	当requestedSigAlgo传入0时,即只根据公钥获取默认的签名参数。
  1659  //	注意公钥必须是签署者使用的私钥对应的公钥,并不是证书拥有者的公钥。
  1660  func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (signOpts crypto.SignerOpts, hashFunc Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
  1661  	var pubType PublicKeyAlgorithm
  1662  
  1663  	// 根据pub的公钥类型选择签名算法参数的默认值
  1664  	switch pub := pub.(type) {
  1665  	case *sm2.PublicKey:
  1666  		pubType = SM2
  1667  		// 检查曲线是否是sm2曲线
  1668  		switch pub.Curve {
  1669  		case sm2.P256Sm2():
  1670  			// 摘要算法
  1671  			hashFunc = Hash(0)
  1672  			// 签名算法
  1673  			sigAlgo.Algorithm = oidSignatureSM2WithSM3
  1674  			// 签名参数 sm2默认做ZA混合散列,不需要low-s处理
  1675  			signOpts = sm2.DefaultSM2SignerOption()
  1676  		default:
  1677  			err = errors.New("x509: unknown SM2 curve")
  1678  		}
  1679  		// 公钥是sm2时,只有一种签名算法和散列算法可以选择,这里其实可以直接返回。
  1680  		// 但为了扩展性以及对内建签名算法列表的检查,还是在后续做一次根据requestedSigAlgo的算法匹配检查。
  1681  	case *rsa.PublicKey:
  1682  		pubType = RSA
  1683  		// 公钥是rsa时并不能确定具体的签名算法与散列算法,这里先准备默认值
  1684  		// 传入的requestedSigAlgo非0时,后续会根据签名算法覆盖具体的签名算法与散列算法
  1685  		hashFunc = SHA256
  1686  		sigAlgo.Algorithm = oidSignatureSHA256WithRSA
  1687  		sigAlgo.Parameters = asn1.NullRawValue
  1688  		signOpts = SHA256
  1689  	case *ecdsa.PublicKey:
  1690  		pubType = ECDSA
  1691  		// 公钥是ecdsa时并不能确定具体的签名算法与散列算法,这里先根据曲线准备默认值
  1692  		// 传入的requestedSigAlgo非0时,后续会根据签名算法覆盖具体的签名算法与散列算法
  1693  		switch pub.Curve {
  1694  		case elliptic.P224(), elliptic.P256():
  1695  			hashFunc = SHA256
  1696  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
  1697  		case elliptic.P384():
  1698  			hashFunc = SHA384
  1699  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
  1700  		case elliptic.P521():
  1701  			hashFunc = SHA512
  1702  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
  1703  		default:
  1704  			err = errors.New("x509: unknown elliptic curve")
  1705  		}
  1706  		// ecdsa签名默认不做low-s处理
  1707  		signOpts = ecbase.CreateEcSignerOpts(crypto.Hash(hashFunc), false)
  1708  	case *ecdsa_ext.PublicKey:
  1709  		pubType = ECDSAEXT
  1710  		// 公钥是ecdsa时并不能确定具体的签名算法与散列算法,这里先根据曲线准备默认值
  1711  		// 传入的requestedSigAlgo非0时,后续会根据签名算法覆盖具体的签名算法与散列算法
  1712  		switch pub.Curve {
  1713  		case elliptic.P224(), elliptic.P256():
  1714  			hashFunc = SHA256
  1715  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
  1716  		case elliptic.P384():
  1717  			hashFunc = SHA384
  1718  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
  1719  		case elliptic.P521():
  1720  			hashFunc = SHA512
  1721  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
  1722  		default:
  1723  			err = errors.New("x509: unknown elliptic curve")
  1724  		}
  1725  		// ecdsa_ext签名默认做low-s处理
  1726  		signOpts = ecbase.CreateEcSignerOpts(crypto.Hash(hashFunc), true)
  1727  
  1728  	case ed25519.PublicKey:
  1729  		pubType = Ed25519
  1730  		sigAlgo.Algorithm = oidSignatureEd25519
  1731  		// ed25519不需要事先散列消息
  1732  		hashFunc = Hash(0)
  1733  		signOpts = hashFunc
  1734  		// ed25519与sm2一样,其实到这里已经可以直接返回了。
  1735  		// 但为了扩展性以及对内建签名算法列表的检查,还是在后续做一次根据requestedSigAlgo的算法匹配检查。
  1736  
  1737  	default:
  1738  		err = errors.New("x509: only SM2, RSA, ECDSA and Ed25519 keys supported")
  1739  	}
  1740  
  1741  	if err != nil {
  1742  		// 公钥获取参数失败时直接返回错误
  1743  		return signOpts, hashFunc, sigAlgo, err
  1744  	}
  1745  	if requestedSigAlgo == 0 {
  1746  		// 如果请求签名算法requestedSigAlgo为0,则直接返回公钥获取到的默认的签名参数
  1747  		return signOpts, hashFunc, sigAlgo, err
  1748  	}
  1749  
  1750  	// 根据请求签名算法requestedSigAlgo匹配签名算法
  1751  	found := false
  1752  	for _, details := range signatureAlgorithmDetails {
  1753  		// 在内建的signatureAlgorithmDetails中匹配参数requestedSigAlgo
  1754  		if details.algo == requestedSigAlgo {
  1755  			// 检查匹配到的算法定义是否与传入的公钥类型匹配
  1756  			if details.pubKeyAlgo != pubType {
  1757  				err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
  1758  				return
  1759  			}
  1760  			// 根据匹配到的算法定义覆盖签名算法与散列算法
  1761  			sigAlgo.Algorithm, hashFunc, signOpts = details.oid, details.hash, details.opts
  1762  			// hashFunc定义为0时检查是不是Ed25519或SM2,只有这两个签名算法不需要事先散列
  1763  			if hashFunc == 0 && pubType != Ed25519 && pubType != SM2 {
  1764  				err = errors.New("x509: cannot sign with hash function requested")
  1765  				return
  1766  			}
  1767  			// RSAPSS系列算法的特殊处理
  1768  			if requestedSigAlgo.isRSAPSS() {
  1769  				sigAlgo.Parameters = hashToPSSParameters[hashFunc]
  1770  			}
  1771  			found = true
  1772  			break
  1773  		}
  1774  	}
  1775  
  1776  	if !found {
  1777  		err = errors.New("x509: unknown SignatureAlgorithm")
  1778  	}
  1779  
  1780  	return
  1781  }
  1782  
  1783  // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
  1784  // just an empty SEQUENCE.
  1785  var emptyASN1Subject = []byte{0x30, 0}
  1786  
  1787  // CreateCertificate 根据证书模板生成gmx509证书(v3)的DER字节数组
  1788  //   - template : 证书模板
  1789  //   - parent : 父证书(自签名时与template传入相同参数即可)
  1790  //   - pub : 证书拥有者的公钥
  1791  //   - priv : 签名者的私钥(有父证书的话,就是父证书拥有者的私钥)
  1792  //
  1793  // 当父证书中含有公钥时,必须确保签名者私钥中的公钥与其一致。
  1794  //
  1795  // CreateCertificate creates a new X.509 v3 certificate based on a template.
  1796  // The following members of template are currently used:
  1797  //
  1798  //   - AuthorityKeyId
  1799  //   - BasicConstraintsValid
  1800  //   - CRLDistributionPoints
  1801  //   - DNSNames
  1802  //   - EmailAddresses
  1803  //   - ExcludedDNSDomains
  1804  //   - ExcludedEmailAddresses
  1805  //   - ExcludedIPRanges
  1806  //   - ExcludedURIDomains
  1807  //   - ExtKeyUsage
  1808  //   - ExtraExtensions
  1809  //   - IPAddresses
  1810  //   - IsCA
  1811  //   - IssuingCertificateURL
  1812  //   - KeyUsage
  1813  //   - MaxPathLen
  1814  //   - MaxPathLenZero
  1815  //   - NotAfter
  1816  //   - NotBefore
  1817  //   - OCSPServer
  1818  //   - PermittedDNSDomains
  1819  //   - PermittedDNSDomainsCritical
  1820  //   - PermittedEmailAddresses
  1821  //   - PermittedIPRanges
  1822  //   - PermittedURIDomains
  1823  //   - PolicyIdentifiers
  1824  //   - SerialNumber
  1825  //   - SignatureAlgorithm
  1826  //   - Subject
  1827  //   - SubjectKeyId
  1828  //   - URIs
  1829  //   - UnknownExtKeyUsage
  1830  //
  1831  // The certificate is signed by parent. If parent is equal to template then the
  1832  // certificate is self-signed. The parameter pub is the public key of the
  1833  // certificate to be generated and priv is the private key of the signer.
  1834  //
  1835  // The returned slice is the certificate in DER encoding.
  1836  //
  1837  // The currently supported key types are *sm2.PublicKey, *rsa.PublicKey, *ecdsa.PublicKey and
  1838  // ed25519.PublicKey. pub must be a supported key type, and priv must be a
  1839  // crypto.Signer with a supported public key.
  1840  //
  1841  // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
  1842  // unless the resulting certificate is self-signed. Otherwise the value from
  1843  // template will be used.
  1844  //
  1845  // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
  1846  // will be generated from the hash of the public key.
  1847  func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) ([]byte, error) {
  1848  	// 检查签名者私钥是否实现了`crypto.Signer`接口
  1849  	key, ok := priv.(crypto.Signer)
  1850  	if !ok {
  1851  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1852  	}
  1853  	// 检查模板是否有SerialNumber
  1854  	if template.SerialNumber == nil {
  1855  		return nil, errors.New("x509: no SerialNumber given")
  1856  	}
  1857  	// 检查MaxPathLen,只有CA证书才允许设置MaxPathLen
  1858  	if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
  1859  		return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
  1860  	}
  1861  	// 根据签名者的公钥以及证书模板的签名算法配置推导本次新证书签名中使用的散列算法与签名算法
  1862  	signOpts, hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
  1863  	if err != nil {
  1864  		return nil, err
  1865  	}
  1866  	// 将新证书拥有者的公钥转为证书公钥字节数组与证书公钥算法 (新证书的核心内容)
  1867  	publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
  1868  	if err != nil {
  1869  		return nil, err
  1870  	}
  1871  	// 从父证书获取证书签署者字节数组
  1872  	asn1Issuer, err := subjectBytes(parent)
  1873  	if err != nil {
  1874  		return nil, err
  1875  	}
  1876  	// 从证书模板获取证书拥有者字节数组
  1877  	asn1Subject, err := subjectBytes(template)
  1878  	if err != nil {
  1879  		return nil, err
  1880  	}
  1881  	// 设置签署者密钥ID
  1882  	authorityKeyId := template.AuthorityKeyId
  1883  	// 非自签名且父证书的SubjectKeyId非空时,将父证书的 SubjectKeyId 设置为新证书的 AuthorityKeyId
  1884  	// 即新证书的签署者密钥ID就是父证书的拥有者密钥ID
  1885  	if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
  1886  		authorityKeyId = parent.SubjectKeyId
  1887  	}
  1888  	// 设置拥有者密钥ID
  1889  	subjectKeyId := template.SubjectKeyId
  1890  	// 当证书模板没有设置拥有者密钥ID,且本证书为CA证书时,自行计算拥有者密钥ID
  1891  	if len(subjectKeyId) == 0 && template.IsCA {
  1892  		// SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
  1893  		//   (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
  1894  		//   value of the BIT STRING subjectPublicKey (excluding the tag,
  1895  		//   length, and number of unused bits).
  1896  		// 国密改造:改为sm3散列
  1897  		// h := sha1.Sum(publicKeyBytes)
  1898  		h := sm3.Sm3Sum(publicKeyBytes)
  1899  		subjectKeyId = h[:]
  1900  	}
  1901  
  1902  	// 检查签署者私钥是否匹配父证书中的公钥
  1903  	// Check that the signer's public key matches the private key, if available.
  1904  	type publicKey interface {
  1905  		Equal(crypto.PublicKey) bool
  1906  	}
  1907  	if privPub, ok := key.Public().(publicKey); !ok {
  1908  		return nil, errors.New("x509: internal error: supported public key does not implement Equal")
  1909  	} else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
  1910  		return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
  1911  	}
  1912  	// 构建本证书的扩展信息
  1913  	extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
  1914  	if err != nil {
  1915  		return nil, err
  1916  	}
  1917  	// 构建证书主体,即签名的内容
  1918  	encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
  1919  	c := tbsCertificate{
  1920  		Version:            2,
  1921  		SerialNumber:       template.SerialNumber,
  1922  		SignatureAlgorithm: signatureAlgorithm,
  1923  		Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
  1924  		Validity:           validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
  1925  		Subject:            asn1.RawValue{FullBytes: asn1Subject},
  1926  		PublicKey:          publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
  1927  		Extensions:         extensions,
  1928  	}
  1929  	// 证书主体字节数组
  1930  	tbsCertContents, err := asn1.Marshal(c)
  1931  	if err != nil {
  1932  		return nil, err
  1933  	}
  1934  	c.Raw = tbsCertContents
  1935  	// 签名前对签名内容做一次散列
  1936  	signed := tbsCertContents
  1937  	// 签名算法为sm2withsm3时,在其内部做散列,对应的hashFunc为0
  1938  	if hashFunc != 0 {
  1939  		h := hashFunc.New()
  1940  		h.Write(signed)
  1941  		signed = h.Sum(nil)
  1942  		// TODO 打印散列算法
  1943  		//fmt.Println("x509.CreateCertificate 对签名内容做散列的算法是: %s", hashFunc.String())
  1944  	}
  1945  	//// 签名需要将散列函数作为signerOpts传入
  1946  	//var signerOpts crypto.SignerOpts = hashFunc
  1947  	//// rsa的特殊处理
  1948  	//if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
  1949  	//	signerOpts = &rsa.PSSOptions{
  1950  	//		SaltLength: rsa.PSSSaltLengthEqualsHash,
  1951  	//		Hash:       hashFunc.HashFunc(),
  1952  	//	}
  1953  	//}
  1954  	// 签名
  1955  	var signature []byte
  1956  	signature, err = key.Sign(rand, signed, signOpts)
  1957  	if err != nil {
  1958  		return nil, err
  1959  	}
  1960  	// ecdsa签名做low-s处理
  1961  	if ecSignOpts, ok := signOpts.(ecbase.EcSignerOpts); ok {
  1962  		if ecSignOpts.NeedLowS() {
  1963  			// 对于ecdsa签名算法,如果指定了要做 low-s处理,那么这里需要针对使用`*ecdsa.PrivateKey`的场景做补丁处理。
  1964  			// 而如果使用的是`*ecdsa_ext.PrivateKey`,其内部已经根据EcSignerOpts参数做过low-s了,这里不需要额外再做一次。
  1965  			if ecdsaPriv, ok := key.(*ecdsa.PrivateKey); ok {
  1966  				fmt.Println("x509证书签署后尝试low-s处理")
  1967  				doLow := false
  1968  				doLow, signature, err = ecdsa_ext.SignatureToLowS(&ecdsaPriv.PublicKey, signature)
  1969  				if err != nil {
  1970  					return nil, err
  1971  				}
  1972  				if doLow {
  1973  					fmt.Println("x509证书签署后完成low-s处理")
  1974  				}
  1975  			}
  1976  		}
  1977  	}
  1978  	//fmt.Println("x509签名内容: " + hex.EncodeToString(signed), hex.EncodeToString(signature))
  1979  	//fmt.Println("x509签名: "+hex.EncodeToString(signed), hex.EncodeToString(signature))
  1980  	// 构建证书(证书主体 + 签名算法 + 签名),并转为字节数组
  1981  	signedCert, err := asn1.Marshal(certificate{
  1982  		nil,
  1983  		c,
  1984  		signatureAlgorithm,
  1985  		asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1986  	})
  1987  	if err != nil {
  1988  		return nil, err
  1989  	}
  1990  
  1991  	// Check the signature to ensure the crypto.Signer behaved correctly.
  1992  	// We skip this check if the signature algorithm is MD5WithRSA as we
  1993  	// only support this algorithm for signing, and not verification.
  1994  	if sigAlg := getSignatureAlgorithmFromAI(signatureAlgorithm); sigAlg != MD5WithRSA {
  1995  		// 检查签名是否正确,注意此时使用签署者的公钥来验签
  1996  		if err := checkSignature(sigAlg, c.Raw, signature, key.Public()); err != nil {
  1997  			return nil, fmt.Errorf("x509: signature over certificate returned by signer is invalid: %w", err)
  1998  		}
  1999  	}
  2000  
  2001  	reqTemplate := CertificateRequest{
  2002  		Subject: pkix.Name{
  2003  			CommonName:   template.Subject.CommonName,
  2004  			Organization: template.Subject.Organization,
  2005  			Country:      template.Subject.Country,
  2006  		},
  2007  		SignatureAlgorithm: SM2WithSM3,
  2008  		DNSNames:           []string{"test.example.com"},
  2009  		EmailAddresses:     []string{"test@custle.org"},
  2010  	}
  2011  	sm2Priv, err := sm2.GenerateKey(rand)
  2012  	request, _ := CreateCertificateRequest(rand, &reqTemplate, sm2Priv)
  2013  	cc := x509ca.ApplySignCert(base64.StdEncoding.EncodeToString(request), "")
  2014  
  2015  	if "User1@org1.example.com" == template.Subject.CommonName {
  2016  		fmt.Println("通过CA签发证书:  " + cc)
  2017  	}
  2018  	if "User1@org2.example.com" == template.Subject.CommonName {
  2019  		fmt.Println("通过CA签发证书:  " + cc)
  2020  	}
  2021  
  2022  	return signedCert, nil
  2023  }
  2024  
  2025  func CreateCertificateExt(rand io.Reader, template, parent *Certificate, pub, priv interface{}) ([]byte, error) {
  2026  	reqTemplate := CertificateRequest{
  2027  		Subject: pkix.Name{
  2028  			CommonName:   template.Subject.CommonName,
  2029  			Organization: template.Subject.Organization,
  2030  			Country:      template.Subject.Country,
  2031  		},
  2032  		SignatureAlgorithm: SM2WithSM3,
  2033  		DNSNames:           []string{"test.example.com"},
  2034  		EmailAddresses:     []string{"test@custle.org"},
  2035  	}
  2036  	sm2Priv, _ := sm2.GenerateKey(rand)
  2037  	request, _ := CreateCertificateRequest(rand, &reqTemplate, sm2Priv)
  2038  	signedCert := x509ca.ApplySignCert(base64.StdEncoding.EncodeToString(request), "")
  2039  	return base64.StdEncoding.DecodeString(signedCert)
  2040  }
  2041  
  2042  // CRL 证书吊销列表(Certificate Revocation List) 相关操作
  2043  
  2044  // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
  2045  // CRL.
  2046  var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
  2047  
  2048  // pemType is the type of a PEM encoded CRL.
  2049  var pemType = "X509 CRL"
  2050  
  2051  // ParseCRL 将给定的字节数组(PEM/DER)转为CRL。
  2052  // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
  2053  // encoded CRLs will appear where they should be DER encoded, so this function
  2054  // will transparently handle PEM encoding as long as there isn't any leading
  2055  // garbage.
  2056  func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
  2057  	if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
  2058  		block, _ := pem.Decode(crlBytes)
  2059  		if block != nil && block.Type == pemType {
  2060  			crlBytes = block.Bytes
  2061  		}
  2062  	}
  2063  	return ParseDERCRL(crlBytes)
  2064  }
  2065  
  2066  // ParseDERCRL 将DER字节数组转为CRL。
  2067  // ParseDERCRL parses a DER encoded CRL from the given bytes.
  2068  func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
  2069  	certList := new(pkix.CertificateList)
  2070  	if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
  2071  		return nil, err
  2072  	} else if len(rest) != 0 {
  2073  		return nil, errors.New("x509: trailing data after CRL")
  2074  	}
  2075  	return certList, nil
  2076  }
  2077  
  2078  // CreateCRL 创建一个CRL
  2079  //   - priv : 撤销证书列表的签署者私钥, 如果是ecdsa私钥,那么这里并不支持low-s处理,验签时对应也不需要low-s检查。
  2080  //   - revokedCerts : 撤销证书列表
  2081  //
  2082  // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
  2083  // contains the given list of revoked certificates.
  2084  //
  2085  // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
  2086  // To generate a standards compliant CRL, use CreateRevocationList instead.
  2087  func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
  2088  	key, ok := priv.(crypto.Signer)
  2089  	if !ok {
  2090  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  2091  	}
  2092  	// 使用签署者的公钥获取签名参数: 散列函数与签名算法
  2093  	signOpts, hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
  2094  	if err != nil {
  2095  		return nil, err
  2096  	}
  2097  
  2098  	// Force revocation times to UTC per RFC 5280.
  2099  	revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
  2100  	for i, rc := range revokedCerts {
  2101  		rc.RevocationTime = rc.RevocationTime.UTC()
  2102  		revokedCertsUTC[i] = rc
  2103  	}
  2104  
  2105  	tbsCertList := pkix.TBSCertificateList{
  2106  		Version:             1,
  2107  		Signature:           signatureAlgorithm,
  2108  		Issuer:              c.Subject.ToRDNSequence(),
  2109  		ThisUpdate:          now.UTC(),
  2110  		NextUpdate:          expiry.UTC(),
  2111  		RevokedCertificates: revokedCertsUTC,
  2112  	}
  2113  
  2114  	// Authority Key Id
  2115  	if len(c.SubjectKeyId) > 0 {
  2116  		var aki pkix.Extension
  2117  		aki.Id = oidExtensionAuthorityKeyId
  2118  		aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
  2119  		if err != nil {
  2120  			return
  2121  		}
  2122  		tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
  2123  	}
  2124  
  2125  	tbsCertListContents, err := asn1.Marshal(tbsCertList)
  2126  	if err != nil {
  2127  		return
  2128  	}
  2129  
  2130  	signed := tbsCertListContents
  2131  	if hashFunc != 0 {
  2132  		h := hashFunc.New()
  2133  		h.Write(signed)
  2134  		signed = h.Sum(nil)
  2135  	}
  2136  
  2137  	var signature []byte
  2138  	signature, err = key.Sign(rand, signed, signOpts)
  2139  	if err != nil {
  2140  		return
  2141  	}
  2142  	//// ecdsa签名做low-s处理
  2143  	//if ecSignOpts, ok := signOpts.(ecbase.EcSignerOpts); ok {
  2144  	//	if ecSignOpts.NeedLowS() {
  2145  	//		// 对于ecdsa签名算法,如果指定了要做 low-s处理,那么这里需要针对使用`*ecdsa.PrivateKey`的场景做补丁处理。
  2146  	//		// 而如果使用的是`*ecdsa_ext.PrivateKey`,其内部已经根据EcSignerOpts参数做过low-s了,这里不需要额外再做一次。
  2147  	//		if ecdsaPriv, ok := key.(*ecdsa.PrivateKey); ok {
  2148  	//			fmt.Println("x509证书签署后尝试low-s处理")
  2149  	//			doLow := false
  2150  	//			doLow, signature, err = ecdsa_ext.SignatureToLowS(&ecdsaPriv.PublicKey, signature)
  2151  	//			if err != nil {
  2152  	//				return nil, err
  2153  	//			}
  2154  	//			if doLow {
  2155  	//				fmt.Println("x509证书签署后完成low-s处理")
  2156  	//			}
  2157  	//		}
  2158  	//	}
  2159  	//}
  2160  
  2161  	return asn1.Marshal(pkix.CertificateList{
  2162  		TBSCertList:        tbsCertList,
  2163  		SignatureAlgorithm: signatureAlgorithm,
  2164  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  2165  	})
  2166  }
  2167  
  2168  // CertificateRequest 证书申请
  2169  // CertificateRequest represents a PKCS #10, certificate signature request.
  2170  type CertificateRequest struct {
  2171  	Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
  2172  	RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
  2173  	RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
  2174  	RawSubject               []byte // DER encoded Subject.
  2175  
  2176  	Version            int
  2177  	Signature          []byte
  2178  	SignatureAlgorithm SignatureAlgorithm
  2179  
  2180  	PublicKeyAlgorithm PublicKeyAlgorithm
  2181  	PublicKey          interface{}
  2182  
  2183  	Subject pkix.Name
  2184  
  2185  	// Attributes contains the CSR attributes that can parse as
  2186  	// pkix.AttributeTypeAndValueSET.
  2187  	//
  2188  	// Deprecated: Use Extensions and ExtraExtensions instead for parsing and
  2189  	// generating the requestedExtensions attribute.
  2190  	Attributes []pkix.AttributeTypeAndValueSET
  2191  
  2192  	// Extensions contains all requested extensions, in raw form. When parsing
  2193  	// CSRs, this can be used to extract extensions that are not parsed by this
  2194  	// package.
  2195  	Extensions []pkix.Extension
  2196  
  2197  	// ExtraExtensions contains extensions to be copied, raw, into any CSR
  2198  	// marshaled by CreateCertificateRequest. Values override any extensions
  2199  	// that would otherwise be produced based on the other fields but are
  2200  	// overridden by any extensions specified in Attributes.
  2201  	//
  2202  	// The ExtraExtensions field is not populated by ParseCertificateRequest,
  2203  	// see Extensions instead.
  2204  	ExtraExtensions []pkix.Extension
  2205  
  2206  	// Subject Alternate Name values.
  2207  	// go1.15开始废弃CommonName,使用SAN扩展信息。
  2208  	// SAN扩展信息由下面四个字段组成。
  2209  	DNSNames       []string
  2210  	EmailAddresses []string
  2211  	IPAddresses    []net.IP
  2212  	URIs           []*url.URL
  2213  }
  2214  
  2215  // These structures reflect the ASN.1 structure of X.509 certificate
  2216  // signature requests (see RFC 2986):
  2217  
  2218  type tbsCertificateRequest struct {
  2219  	Raw           asn1.RawContent
  2220  	Version       int
  2221  	Subject       asn1.RawValue
  2222  	PublicKey     publicKeyInfo
  2223  	RawAttributes []asn1.RawValue `asn1:"tag:0"`
  2224  }
  2225  
  2226  type certificateRequest struct {
  2227  	Raw                asn1.RawContent
  2228  	TBSCSR             tbsCertificateRequest
  2229  	SignatureAlgorithm pkix.AlgorithmIdentifier
  2230  	SignatureValue     asn1.BitString
  2231  }
  2232  
  2233  // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
  2234  // extensions in a CSR.
  2235  var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
  2236  
  2237  // newRawAttributes converts AttributeTypeAndValueSETs from a template
  2238  // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
  2239  func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
  2240  	var rawAttributes []asn1.RawValue
  2241  	b, err := asn1.Marshal(attributes)
  2242  	if err != nil {
  2243  		return nil, err
  2244  	}
  2245  	rest, err := asn1.Unmarshal(b, &rawAttributes)
  2246  	if err != nil {
  2247  		return nil, err
  2248  	}
  2249  	if len(rest) != 0 {
  2250  		return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
  2251  	}
  2252  	return rawAttributes, nil
  2253  }
  2254  
  2255  // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
  2256  func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
  2257  	var attributes []pkix.AttributeTypeAndValueSET
  2258  	for _, rawAttr := range rawAttributes {
  2259  		var attr pkix.AttributeTypeAndValueSET
  2260  		rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
  2261  		// Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
  2262  		// (i.e.: challengePassword or unstructuredName).
  2263  		if err == nil && len(rest) == 0 {
  2264  			attributes = append(attributes, attr)
  2265  		}
  2266  	}
  2267  	return attributes
  2268  }
  2269  
  2270  // parseCSRExtensions parses the attributes from a CSR and extracts any
  2271  // requested extensions.
  2272  func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
  2273  	// pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
  2274  	type pkcs10Attribute struct {
  2275  		Id     asn1.ObjectIdentifier
  2276  		Values []asn1.RawValue `asn1:"set"`
  2277  	}
  2278  
  2279  	var ret []pkix.Extension
  2280  	for _, rawAttr := range rawAttributes {
  2281  		var attr pkcs10Attribute
  2282  		if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
  2283  			// Ignore attributes that don't parse.
  2284  			continue
  2285  		}
  2286  
  2287  		if !attr.Id.Equal(oidExtensionRequest) {
  2288  			continue
  2289  		}
  2290  
  2291  		var extensions []pkix.Extension
  2292  		if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
  2293  			return nil, err
  2294  		}
  2295  		ret = append(ret, extensions...)
  2296  	}
  2297  
  2298  	return ret, nil
  2299  }
  2300  
  2301  // CreateCertificateRequest 基于证书申请模板生成一个新的证书申请。
  2302  // 注意,证书申请内部的公钥信息就是签名者的公钥,即,证书申请是申请者自签名的。
  2303  //   - rand : 随机数获取用
  2304  //   - template : 证书申请模板
  2305  //   - priv : 申请者私钥
  2306  //
  2307  // CreateCertificateRequest creates a new certificate request based on a
  2308  // template. The following members of template are used:
  2309  //
  2310  //   - SignatureAlgorithm
  2311  //   - Subject
  2312  //   - DNSNames
  2313  //   - EmailAddresses
  2314  //   - IPAddresses
  2315  //   - URIs
  2316  //   - ExtraExtensions
  2317  //   - Attributes (deprecated)
  2318  //
  2319  // priv is the private key to sign the CSR with, and the corresponding public
  2320  // key will be included in the CSR. It must implement crypto.Signer and its
  2321  // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
  2322  // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
  2323  // ed25519.PrivateKey satisfies this.)
  2324  //
  2325  // The returned slice is the certificate request in DER encoding.
  2326  func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
  2327  	key, ok := priv.(crypto.Signer)
  2328  	if !ok {
  2329  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  2330  	}
  2331  	// 根据申请者的公钥与模板的签名算法获取散列函数与签名算法
  2332  	var signOpts crypto.SignerOpts
  2333  	var hashFunc Hash
  2334  	var sigAlgo pkix.AlgorithmIdentifier
  2335  	signOpts, hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
  2336  	if err != nil {
  2337  		return nil, err
  2338  	}
  2339  	// 根据申请者的公钥生成证书申请的核心内容:公钥字节数组与公钥算法
  2340  	var publicKeyBytes []byte
  2341  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
  2342  	publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
  2343  	if err != nil {
  2344  		return nil, err
  2345  	}
  2346  	// 构建证书申请扩展内容
  2347  	extensions, err := buildCSRExtensions(template)
  2348  	if err != nil {
  2349  		return nil, err
  2350  	}
  2351  	// Make a copy of template.Attributes because we may alter it below.
  2352  	//goland:noinspection GoDeprecation
  2353  	attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
  2354  	//goland:noinspection GoDeprecation
  2355  	for _, attr := range template.Attributes {
  2356  		values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
  2357  		copy(values, attr.Value)
  2358  		attributes = append(attributes, pkix.AttributeTypeAndValueSET{
  2359  			Type:  attr.Type,
  2360  			Value: values,
  2361  		})
  2362  	}
  2363  	extensionsAppended := false
  2364  	if len(extensions) > 0 {
  2365  		// Append the extensions to an existing attribute if possible.
  2366  		for _, atvSet := range attributes {
  2367  			if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
  2368  				continue
  2369  			}
  2370  			// specifiedExtensions contains all the extensions that we
  2371  			// found specified via template.Attributes.
  2372  			specifiedExtensions := make(map[string]bool)
  2373  			for _, atvs := range atvSet.Value {
  2374  				for _, atv := range atvs {
  2375  					specifiedExtensions[atv.Type.String()] = true
  2376  				}
  2377  			}
  2378  			newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
  2379  			newValue = append(newValue, atvSet.Value[0]...)
  2380  			for _, e := range extensions {
  2381  				if specifiedExtensions[e.Id.String()] {
  2382  					// Attributes already contained a value for
  2383  					// this extension and it takes priority.
  2384  					continue
  2385  				}
  2386  				newValue = append(newValue, pkix.AttributeTypeAndValue{
  2387  					// There is no place for the critical
  2388  					// flag in an AttributeTypeAndValue.
  2389  					Type:  e.Id,
  2390  					Value: e.Value,
  2391  				})
  2392  			}
  2393  			atvSet.Value[0] = newValue
  2394  			extensionsAppended = true
  2395  			break
  2396  		}
  2397  	}
  2398  	rawAttributes, err := newRawAttributes(attributes)
  2399  	if err != nil {
  2400  		return
  2401  	}
  2402  	// If not included in attributes, add a new attribute for the
  2403  	// extensions.
  2404  	if len(extensions) > 0 && !extensionsAppended {
  2405  		attr := struct {
  2406  			Type  asn1.ObjectIdentifier
  2407  			Value [][]pkix.Extension `asn1:"set"`
  2408  		}{
  2409  			Type:  oidExtensionRequest,
  2410  			Value: [][]pkix.Extension{extensions},
  2411  		}
  2412  		b, err := asn1.Marshal(attr)
  2413  		if err != nil {
  2414  			return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
  2415  		}
  2416  		var rawValue asn1.RawValue
  2417  		if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
  2418  			return nil, err
  2419  		}
  2420  		rawAttributes = append(rawAttributes, rawValue)
  2421  	}
  2422  	// 证书申请者信息
  2423  	asn1Subject := template.RawSubject
  2424  	if len(asn1Subject) == 0 {
  2425  		asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
  2426  		if err != nil {
  2427  			return nil, err
  2428  		}
  2429  	}
  2430  	// 签名内容
  2431  	tbsCSR := tbsCertificateRequest{
  2432  		Version: 0, // PKCS #10, RFC 2986
  2433  		Subject: asn1.RawValue{FullBytes: asn1Subject},
  2434  		PublicKey: publicKeyInfo{
  2435  			Algorithm: publicKeyAlgorithm,
  2436  			PublicKey: asn1.BitString{
  2437  				Bytes:     publicKeyBytes,
  2438  				BitLength: len(publicKeyBytes) * 8,
  2439  			},
  2440  		},
  2441  		RawAttributes: rawAttributes,
  2442  	}
  2443  	tbsCSRContents, err := asn1.Marshal(tbsCSR)
  2444  	if err != nil {
  2445  		return
  2446  	}
  2447  	tbsCSR.Raw = tbsCSRContents
  2448  	// 签名内容进行一次散列
  2449  	signed := tbsCSRContents
  2450  	if hashFunc != 0 {
  2451  		h := hashFunc.New()
  2452  		h.Write(signed)
  2453  		signed = h.Sum(nil)
  2454  	}
  2455  	// 签名,注意,证书申请都是申请者自签名。
  2456  	var signature []byte
  2457  	signature, err = key.Sign(rand, signed, signOpts)
  2458  	if err != nil {
  2459  		return
  2460  	}
  2461  	// ecdsa签名做low-s处理
  2462  	if ecSignOpts, ok := signOpts.(ecbase.EcSignerOpts); ok {
  2463  		if ecSignOpts.NeedLowS() {
  2464  			// 对于ecdsa签名算法,如果指定了要做 low-s处理,那么这里需要针对使用`*ecdsa.PrivateKey`的场景做补丁处理。
  2465  			// 而如果使用的是`*ecdsa_ext.PrivateKey`,其内部已经根据EcSignerOpts参数做过low-s了,这里不需要额外再做一次。
  2466  			if ecdsaPriv, ok := key.(*ecdsa.PrivateKey); ok {
  2467  				fmt.Println("x509证书签署后尝试low-s处理")
  2468  				doLow := false
  2469  				doLow, signature, err = ecdsa_ext.SignatureToLowS(&ecdsaPriv.PublicKey, signature)
  2470  				if err != nil {
  2471  					return nil, err
  2472  				}
  2473  				if doLow {
  2474  					fmt.Println("x509证书签署后完成low-s处理")
  2475  				}
  2476  			}
  2477  		}
  2478  	}
  2479  	// 返回证书申请DER字节数组
  2480  	return asn1.Marshal(certificateRequest{
  2481  		TBSCSR:             tbsCSR,
  2482  		SignatureAlgorithm: sigAlgo,
  2483  		SignatureValue: asn1.BitString{
  2484  			Bytes:     signature,
  2485  			BitLength: len(signature) * 8,
  2486  		},
  2487  	})
  2488  }
  2489  
  2490  // ParseCertificateRequest 将DER字节数组转为单个证书申请。
  2491  // ParseCertificateRequest parses a single certificate request from the
  2492  // given ASN.1 DER data.
  2493  func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
  2494  	var csr certificateRequest
  2495  
  2496  	rest, err := asn1.Unmarshal(asn1Data, &csr)
  2497  	if err != nil {
  2498  		return nil, err
  2499  	} else if len(rest) != 0 {
  2500  		return nil, asn1.SyntaxError{Msg: "trailing data"}
  2501  	}
  2502  
  2503  	return parseCertificateRequest(&csr)
  2504  }
  2505  
  2506  func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
  2507  	//goland:noinspection GoDeprecation
  2508  	out := &CertificateRequest{
  2509  		Raw:                      in.Raw,
  2510  		RawTBSCertificateRequest: in.TBSCSR.Raw,
  2511  		RawSubjectPublicKeyInfo:  in.TBSCSR.PublicKey.Raw,
  2512  		RawSubject:               in.TBSCSR.Subject.FullBytes,
  2513  
  2514  		Signature:          in.SignatureValue.RightAlign(),
  2515  		SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
  2516  
  2517  		PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
  2518  
  2519  		Version:    in.TBSCSR.Version,
  2520  		Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
  2521  	}
  2522  
  2523  	var err error
  2524  	out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
  2525  	if err != nil {
  2526  		return nil, err
  2527  	}
  2528  
  2529  	var subject pkix.RDNSequence
  2530  	if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
  2531  		return nil, err
  2532  	} else if len(rest) != 0 {
  2533  		return nil, errors.New("x509: trailing data after X.509 Subject")
  2534  	}
  2535  
  2536  	out.Subject.FillFromRDNSequence(&subject)
  2537  
  2538  	if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
  2539  		return nil, err
  2540  	}
  2541  
  2542  	for _, extension := range out.Extensions {
  2543  		switch {
  2544  		case extension.Id.Equal(oidExtensionSubjectAltName):
  2545  			out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
  2546  			if err != nil {
  2547  				return nil, err
  2548  			}
  2549  		case extension.Id.Equal(oidExtensionSignatureAlgorithm):
  2550  			// SignatureAlgorithm反序列化操作
  2551  			signAlg := SignatureAlgorithm(binary.BigEndian.Uint32(extension.Value))
  2552  			if signAlg > 0 {
  2553  				out.SignatureAlgorithm = signAlg
  2554  			}
  2555  		}
  2556  	}
  2557  
  2558  	return out, nil
  2559  }
  2560  
  2561  // CheckSignature 检查证书申请c的签名是否有效
  2562  // CheckSignature reports whether the signature on c is valid.
  2563  func (c *CertificateRequest) CheckSignature() error {
  2564  	return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
  2565  }
  2566  
  2567  // ToX509Certificate gmx509转x509
  2568  func (c *Certificate) ToX509Certificate() *x509.Certificate {
  2569  	x509cert := &x509.Certificate{
  2570  		Raw:                         c.Raw,
  2571  		RawTBSCertificate:           c.RawTBSCertificate,
  2572  		RawSubjectPublicKeyInfo:     c.RawSubjectPublicKeyInfo,
  2573  		RawSubject:                  c.RawSubject,
  2574  		RawIssuer:                   c.RawIssuer,
  2575  		Signature:                   c.Signature,
  2576  		SignatureAlgorithm:          x509.SignatureAlgorithm(c.SignatureAlgorithm),
  2577  		PublicKeyAlgorithm:          x509.PublicKeyAlgorithm(c.PublicKeyAlgorithm),
  2578  		PublicKey:                   c.PublicKey,
  2579  		Version:                     c.Version,
  2580  		SerialNumber:                c.SerialNumber,
  2581  		Issuer:                      c.Issuer,
  2582  		Subject:                     c.Subject,
  2583  		NotBefore:                   c.NotBefore,
  2584  		NotAfter:                    c.NotAfter,
  2585  		KeyUsage:                    x509.KeyUsage(c.KeyUsage),
  2586  		Extensions:                  c.Extensions,
  2587  		ExtraExtensions:             c.ExtraExtensions,
  2588  		UnhandledCriticalExtensions: c.UnhandledCriticalExtensions,
  2589  		// ExtKeyUsage:	[]x509.ExtKeyUsage(c.ExtKeyUsage) ,
  2590  		UnknownExtKeyUsage:    c.UnknownExtKeyUsage,
  2591  		BasicConstraintsValid: c.BasicConstraintsValid,
  2592  		IsCA:                  c.IsCA,
  2593  		MaxPathLen:            c.MaxPathLen,
  2594  		// MaxPathLenZero indicates that BasicConstraintsValid==true and
  2595  		// MaxPathLen==0 should be interpreted as an actual maximum path length
  2596  		// of zero. Otherwise, that combination is interpreted as MaxPathLen
  2597  		// not being set.
  2598  		MaxPathLenZero: c.MaxPathLenZero,
  2599  		SubjectKeyId:   c.SubjectKeyId,
  2600  		AuthorityKeyId: c.AuthorityKeyId,
  2601  		// RFC 5280, 4.2.2.1 (Authority Information Access)
  2602  		OCSPServer:            c.OCSPServer,
  2603  		IssuingCertificateURL: c.IssuingCertificateURL,
  2604  		// Subject Alternate Name values
  2605  		DNSNames:       c.DNSNames,
  2606  		EmailAddresses: c.EmailAddresses,
  2607  		IPAddresses:    c.IPAddresses,
  2608  		URIs:           c.URIs,
  2609  		// Name constraints
  2610  		PermittedDNSDomainsCritical: c.PermittedDNSDomainsCritical,
  2611  		PermittedDNSDomains:         c.PermittedDNSDomains,
  2612  		ExcludedDNSDomains:          c.ExcludedDNSDomains,
  2613  		PermittedIPRanges:           c.PermittedIPRanges,
  2614  		ExcludedIPRanges:            c.ExcludedIPRanges,
  2615  		PermittedEmailAddresses:     c.PermittedEmailAddresses,
  2616  		ExcludedEmailAddresses:      c.ExcludedEmailAddresses,
  2617  		PermittedURIDomains:         c.PermittedURIDomains,
  2618  		ExcludedURIDomains:          c.ExcludedURIDomains,
  2619  		// CRL Distribution Points
  2620  		CRLDistributionPoints: c.CRLDistributionPoints,
  2621  		PolicyIdentifiers:     c.PolicyIdentifiers,
  2622  	}
  2623  
  2624  	for _, val := range c.ExtKeyUsage {
  2625  		x509cert.ExtKeyUsage = append(x509cert.ExtKeyUsage, x509.ExtKeyUsage(val))
  2626  	}
  2627  
  2628  	return x509cert
  2629  }
  2630  
  2631  // FromX509Certificate x509转gmx509
  2632  func (c *Certificate) FromX509Certificate(x509Cert *x509.Certificate) {
  2633  	c.Raw = x509Cert.Raw
  2634  	c.RawTBSCertificate = x509Cert.RawTBSCertificate
  2635  	c.RawSubjectPublicKeyInfo = x509Cert.RawSubjectPublicKeyInfo
  2636  	c.RawSubject = x509Cert.RawSubject
  2637  	c.RawIssuer = x509Cert.RawIssuer
  2638  	c.Signature = x509Cert.Signature
  2639  	c.SignatureAlgorithm = SM2WithSM3
  2640  	c.PublicKeyAlgorithm = PublicKeyAlgorithm(x509Cert.PublicKeyAlgorithm)
  2641  	c.PublicKey = x509Cert.PublicKey
  2642  	c.Version = x509Cert.Version
  2643  	c.SerialNumber = x509Cert.SerialNumber
  2644  	c.Issuer = x509Cert.Issuer
  2645  	c.Subject = x509Cert.Subject
  2646  	c.NotBefore = x509Cert.NotBefore
  2647  	c.NotAfter = x509Cert.NotAfter
  2648  	c.KeyUsage = KeyUsage(x509Cert.KeyUsage)
  2649  	c.Extensions = x509Cert.Extensions
  2650  	c.ExtraExtensions = x509Cert.ExtraExtensions
  2651  	c.UnhandledCriticalExtensions = x509Cert.UnhandledCriticalExtensions
  2652  	c.UnknownExtKeyUsage = x509Cert.UnknownExtKeyUsage
  2653  	c.BasicConstraintsValid = x509Cert.BasicConstraintsValid
  2654  	c.IsCA = x509Cert.IsCA
  2655  	c.MaxPathLen = x509Cert.MaxPathLen
  2656  	c.MaxPathLenZero = x509Cert.MaxPathLenZero
  2657  	c.SubjectKeyId = x509Cert.SubjectKeyId
  2658  	c.AuthorityKeyId = x509Cert.AuthorityKeyId
  2659  	c.OCSPServer = x509Cert.OCSPServer
  2660  	c.IssuingCertificateURL = x509Cert.IssuingCertificateURL
  2661  	c.DNSNames = x509Cert.DNSNames
  2662  	c.EmailAddresses = x509Cert.EmailAddresses
  2663  	c.IPAddresses = x509Cert.IPAddresses
  2664  	c.URIs = x509Cert.URIs
  2665  	c.PermittedDNSDomainsCritical = x509Cert.PermittedDNSDomainsCritical
  2666  	c.PermittedDNSDomains = x509Cert.PermittedDNSDomains
  2667  	c.ExcludedDNSDomains = x509Cert.ExcludedDNSDomains
  2668  	c.PermittedIPRanges = x509Cert.PermittedIPRanges
  2669  	c.ExcludedIPRanges = x509Cert.ExcludedIPRanges
  2670  	c.PermittedEmailAddresses = x509Cert.PermittedEmailAddresses
  2671  	c.ExcludedEmailAddresses = x509Cert.ExcludedEmailAddresses
  2672  	c.PermittedURIDomains = x509Cert.PermittedURIDomains
  2673  	c.ExcludedURIDomains = x509Cert.ExcludedURIDomains
  2674  	c.CRLDistributionPoints = x509Cert.CRLDistributionPoints
  2675  	c.PolicyIdentifiers = x509Cert.PolicyIdentifiers
  2676  	for _, val := range x509Cert.ExtKeyUsage {
  2677  		c.ExtKeyUsage = append(c.ExtKeyUsage, ExtKeyUsage(val))
  2678  	}
  2679  }
  2680  
  2681  // RevocationList contains the fields used to create an X.509 v2 Certificate
  2682  // Revocation list with CreateRevocationList.
  2683  type RevocationList struct {
  2684  	// SignatureAlgorithm is used to determine the signature algorithm to be
  2685  	// used when signing the CRL. If 0 the default algorithm for the signing
  2686  	// key will be used.
  2687  	SignatureAlgorithm SignatureAlgorithm
  2688  
  2689  	// RevokedCertificates is used to populate the revokedCertificates
  2690  	// sequence in the CRL, it may be empty. RevokedCertificates may be nil,
  2691  	// in which case an empty CRL will be created.
  2692  	RevokedCertificates []pkix.RevokedCertificate
  2693  
  2694  	// Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
  2695  	// which should be a monotonically increasing sequence number for a given
  2696  	// CRL scope and CRL issuer.
  2697  	Number *big.Int
  2698  	// ThisUpdate is used to populate the thisUpdate field in the CRL, which
  2699  	// indicates the issuance date of the CRL.
  2700  	ThisUpdate time.Time
  2701  	// NextUpdate is used to populate the nextUpdate field in the CRL, which
  2702  	// indicates the date by which the next CRL will be issued. NextUpdate
  2703  	// must be greater than ThisUpdate.
  2704  	NextUpdate time.Time
  2705  	// ExtraExtensions contains any additional extensions to add directly to
  2706  	// the CRL.
  2707  	ExtraExtensions []pkix.Extension
  2708  }
  2709  
  2710  // CreateRevocationList 创建x509 v2版本的证书撤销列表
  2711  //
  2712  //	注意,私钥是ecdsa类型时,不支持low-s处理。
  2713  //
  2714  // creates a new X.509 v2 Certificate Revocation List,
  2715  // according to RFC 5280, based on template.
  2716  //
  2717  // The CRL is signed by priv which should be the private key associated with
  2718  // the public key in the issuer certificate.
  2719  //
  2720  // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
  2721  // order to use it as a CRL issuer.
  2722  //
  2723  // The issuer distinguished name CRL field and authority key identifier
  2724  // extension are populated using the issuer certificate. issuer must have
  2725  // SubjectKeyId set.
  2726  func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
  2727  	if template == nil {
  2728  		return nil, errors.New("x509: template can not be nil")
  2729  	}
  2730  	if issuer == nil {
  2731  		return nil, errors.New("x509: issuer can not be nil")
  2732  	}
  2733  	if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
  2734  		return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
  2735  	}
  2736  	if len(issuer.SubjectKeyId) == 0 {
  2737  		return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
  2738  	}
  2739  	if template.NextUpdate.Before(template.ThisUpdate) {
  2740  		return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
  2741  	}
  2742  	if template.Number == nil {
  2743  		return nil, errors.New("x509: template contains nil Number field")
  2744  	}
  2745  
  2746  	signOpts, hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
  2747  	if err != nil {
  2748  		return nil, err
  2749  	}
  2750  
  2751  	// Force revocation times to UTC per RFC 5280.
  2752  	revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
  2753  	for i, rc := range template.RevokedCertificates {
  2754  		rc.RevocationTime = rc.RevocationTime.UTC()
  2755  		revokedCertsUTC[i] = rc
  2756  	}
  2757  
  2758  	aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
  2759  	if err != nil {
  2760  		return nil, err
  2761  	}
  2762  	crlNum, err := asn1.Marshal(template.Number)
  2763  	if err != nil {
  2764  		return nil, err
  2765  	}
  2766  
  2767  	tbsCertList := pkix.TBSCertificateList{
  2768  		Version:    1, // v2
  2769  		Signature:  signatureAlgorithm,
  2770  		Issuer:     issuer.Subject.ToRDNSequence(),
  2771  		ThisUpdate: template.ThisUpdate.UTC(),
  2772  		NextUpdate: template.NextUpdate.UTC(),
  2773  		Extensions: []pkix.Extension{
  2774  			{
  2775  				Id:    oidExtensionAuthorityKeyId,
  2776  				Value: aki,
  2777  			},
  2778  			{
  2779  				Id:    oidExtensionCRLNumber,
  2780  				Value: crlNum,
  2781  			},
  2782  		},
  2783  	}
  2784  	if len(revokedCertsUTC) > 0 {
  2785  		tbsCertList.RevokedCertificates = revokedCertsUTC
  2786  	}
  2787  
  2788  	//// 添加oidExtensionSignatureAlgorithm
  2789  	//if template.SignatureAlgorithm > 0 && !oidInExtensions(oidExtensionSignatureAlgorithm, template.ExtraExtensions) {
  2790  	//	tbsCertList.Extensions = append(tbsCertList.Extensions, marshalSignatureAlgorithm(template.SignatureAlgorithm))
  2791  	//}
  2792  
  2793  	if len(template.ExtraExtensions) > 0 {
  2794  		tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
  2795  	}
  2796  
  2797  	tbsCertListContents, err := asn1.Marshal(tbsCertList)
  2798  	if err != nil {
  2799  		return nil, err
  2800  	}
  2801  
  2802  	input := tbsCertListContents
  2803  	if hashFunc != 0 {
  2804  		h := hashFunc.New()
  2805  		h.Write(tbsCertListContents)
  2806  		input = h.Sum(nil)
  2807  	}
  2808  	//var signerOpts crypto.SignerOpts = hashFunc
  2809  	//if template.SignatureAlgorithm.isRSAPSS() {
  2810  	//	signerOpts = &rsa.PSSOptions{
  2811  	//		SaltLength: rsa.PSSSaltLengthEqualsHash,
  2812  	//		Hash:       hashFunc.HashFunc(),
  2813  	//	}
  2814  	//}
  2815  
  2816  	signature, err := priv.Sign(rand, input, signOpts)
  2817  	if err != nil {
  2818  		return nil, err
  2819  	}
  2820  	//// ecdsa签名做low-s处理
  2821  	//if ecSignOpts, ok := signOpts.(ecbase.EcSignerOpts); ok {
  2822  	//	if ecSignOpts.NeedLowS() {
  2823  	//		// 对于ecdsa签名算法,如果指定了要做 low-s处理,那么这里需要针对使用`*ecdsa.PrivateKey`的场景做补丁处理。
  2824  	//		// 而如果使用的是`*ecdsa_ext.PrivateKey`,其内部已经根据EcSignerOpts参数做过low-s了,这里不需要额外再做一次。
  2825  	//		if ecdsaPriv, ok := priv.(*ecdsa.PrivateKey); ok {
  2826  	//			fmt.Println("x509证书签署后尝试low-s处理")
  2827  	//			doLow := false
  2828  	//			doLow, signature, err = ecdsa_ext.SignatureToLowS(&ecdsaPriv.PublicKey, signature)
  2829  	//			if err != nil {
  2830  	//				return nil, err
  2831  	//			}
  2832  	//			if doLow {
  2833  	//				fmt.Println("x509证书签署后完成low-s处理")
  2834  	//			}
  2835  	//		}
  2836  	//	}
  2837  	//}
  2838  
  2839  	return asn1.Marshal(pkix.CertificateList{
  2840  		TBSCertList:        tbsCertList,
  2841  		SignatureAlgorithm: signatureAlgorithm,
  2842  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  2843  	})
  2844  }