github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/x509/x509.go (about)

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