github.com/bigzoro/my_simplechain@v0.0.0-20240315012955-8ad0a2a29bb9/core/access_contoller/crypto/x509/x509.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package x509 parses X.509-encoded keys and certificates.
     6  //
     7  // On UNIX systems the environment variables SSL_CERT_FILE and SSL_CERT_DIR
     8  // can be used to override the system default locations for the SSL certificate
     9  // file and SSL certificate files directory, respectively.
    10  package x509
    11  
    12  // nolint: gosec
    13  import (
    14  	"bytes"
    15  	"crypto"
    16  	"crypto/ecdsa"
    17  	"crypto/elliptic"
    18  	"crypto/rsa"
    19  	_ "crypto/sha1"
    20  	_ "crypto/sha256"
    21  	_ "crypto/sha512"
    22  	"crypto/x509"
    23  	"crypto/x509/pkix"
    24  	"encoding/asn1"
    25  	"errors"
    26  	"fmt"
    27  	bccrypto "github.com/bigzoro/my_simplechain/core/access_contoller/crypto"
    28  	"github.com/bigzoro/my_simplechain/core/access_contoller/crypto/asym"
    29  	bcecdsa "github.com/bigzoro/my_simplechain/core/access_contoller/crypto/asym/ecdsa"
    30  	bcrsa "github.com/bigzoro/my_simplechain/core/access_contoller/crypto/asym/rsa"
    31  	bcsm2 "github.com/bigzoro/my_simplechain/core/access_contoller/crypto/asym/sm2"
    32  	"github.com/tjfoc/gmsm/sm2"
    33  	tjx509 "github.com/tjfoc/gmsm/x509"
    34  	"golang.org/x/crypto/cryptobyte"
    35  	cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
    36  	"io"
    37  	"math/big"
    38  	"net"
    39  	"net/url"
    40  	"strconv"
    41  	"strings"
    42  	"time"
    43  	"unicode/utf8"
    44  )
    45  
    46  // These structures reflect the ASN.1 structure of X.509 certificates.:
    47  
    48  type certificate struct {
    49  	Raw                asn1.RawContent
    50  	TBSCertificate     tbsCertificate
    51  	SignatureAlgorithm pkix.AlgorithmIdentifier
    52  	SignatureValue     asn1.BitString
    53  }
    54  
    55  type tbsCertificate struct {
    56  	Raw                asn1.RawContent
    57  	Version            int `asn1:"optional,explicit,default:0,tag:0"`
    58  	SerialNumber       *big.Int
    59  	SignatureAlgorithm pkix.AlgorithmIdentifier
    60  	Issuer             asn1.RawValue
    61  	Validity           validity
    62  	Subject            asn1.RawValue
    63  	PublicKey          publicKeyInfo
    64  	UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
    65  	SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
    66  	Extensions         []pkix.Extension `asn1:"optional,explicit,tag:3"`
    67  }
    68  
    69  // nolint: deadcode, unused
    70  type dsaAlgorithmParameters struct {
    71  	P, Q, G *big.Int
    72  }
    73  
    74  // nolint: unused
    75  type dsaSignature struct {
    76  	R, S *big.Int
    77  }
    78  
    79  // nolint: deadcode, unused
    80  type ecdsaSignature dsaSignature
    81  
    82  type validity struct {
    83  	NotBefore, NotAfter time.Time
    84  }
    85  
    86  type publicKeyInfo struct {
    87  	Raw       asn1.RawContent
    88  	Algorithm pkix.AlgorithmIdentifier
    89  	PublicKey asn1.BitString
    90  }
    91  
    92  // RFC 5280,  4.2.1.1
    93  type authKeyId struct {
    94  	Id []byte `asn1:"optional,tag:0"`
    95  }
    96  
    97  type SignatureAlgorithm int
    98  
    99  const (
   100  	UnknownSignatureAlgorithm SignatureAlgorithm = iota
   101  	MD2WithRSA
   102  	MD5WithRSA
   103  	SHA1WithRSA
   104  	SHA256WithRSA
   105  	SHA384WithRSA
   106  	SHA512WithRSA
   107  	DSAWithSHA1
   108  	DSAWithSHA256
   109  	ECDSAWithSHA1
   110  	ECDSAWithSHA256
   111  	ECDSAWithSHA384
   112  	ECDSAWithSHA512
   113  	SHA256WithRSAPSS
   114  	SHA384WithRSAPSS
   115  	SHA512WithRSAPSS
   116  	SHA256WithSM2
   117  	SM3WithSM2
   118  )
   119  
   120  func (algo SignatureAlgorithm) String() string {
   121  	for _, details := range signatureAlgorithmDetails {
   122  		if details.algo == algo {
   123  			return details.name
   124  		}
   125  	}
   126  	return strconv.Itoa(int(algo))
   127  }
   128  
   129  type PublicKeyAlgorithm int
   130  
   131  const (
   132  	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
   133  	RSA
   134  	DSA
   135  	ECDSA
   136  	SM2
   137  )
   138  
   139  var publicKeyAlgoName = [...]string{
   140  	RSA:   "RSA",
   141  	DSA:   "DSA",
   142  	ECDSA: "ECDSA",
   143  	SM2:   "SM2",
   144  }
   145  
   146  func (algo PublicKeyAlgorithm) String() string {
   147  	if 0 < algo && int(algo) < len(publicKeyAlgoName) {
   148  		return publicKeyAlgoName[algo]
   149  	}
   150  	return strconv.Itoa(int(algo))
   151  }
   152  
   153  // OIDs for signature algorithms
   154  //
   155  // pkcs-1 OBJECT IDENTIFIER ::= {
   156  //    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
   157  //
   158  //
   159  // RFC 3279 2.2.1 RSA Signature Algorithms
   160  //
   161  // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
   162  //
   163  // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
   164  //
   165  // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
   166  //
   167  // dsaWithSha1 OBJECT IDENTIFIER ::= {
   168  //    iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
   169  //
   170  // RFC 3279 2.2.3 ECDSA Signature Algorithm
   171  //
   172  // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
   173  // 	  iso(1) member-body(2) us(840) ansi-x962(10045)
   174  //    signatures(4) ecdsa-with-SHA1(1)}
   175  //
   176  //
   177  // RFC 4055 5 PKCS #1 Version 1.5
   178  //
   179  // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
   180  //
   181  // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
   182  //
   183  // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
   184  //
   185  //
   186  // RFC 5758 3.1 DSA Signature Algorithms
   187  //
   188  // dsaWithSha256 OBJECT IDENTIFIER ::= {
   189  //    joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
   190  //    csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
   191  //
   192  // RFC 5758 3.2 ECDSA Signature Algorithm
   193  //
   194  // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   195  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
   196  //
   197  // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   198  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
   199  //
   200  // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   201  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
   202  
   203  var (
   204  	oidSignatureMD2WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
   205  	oidSignatureMD5WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
   206  	oidSignatureSHA1WithRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
   207  	oidSignatureSHA256WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
   208  	oidSignatureSHA384WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
   209  	oidSignatureSHA512WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
   210  	oidSignatureRSAPSS          = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
   211  	oidSignatureDSAWithSHA1     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
   212  	oidSignatureDSAWithSHA256   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
   213  	oidSignatureECDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
   214  	oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
   215  	oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
   216  	oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
   217  
   218  	oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
   219  	oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
   220  	oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
   221  
   222  	oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
   223  
   224  	// oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
   225  	// but it's specified by ISO. Microsoft's makecert.exe has been known
   226  	// to produce certificates with this OID.
   227  	oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
   228  
   229  	oidSignatureSHA256WithSM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 503}
   230  	oidSignatureSM3WithSM2    = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 501}
   231  )
   232  
   233  var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
   234  
   235  var signatureAlgorithmDetails = []struct {
   236  	algo       SignatureAlgorithm
   237  	name       string
   238  	oid        asn1.ObjectIdentifier
   239  	pubKeyAlgo PublicKeyAlgorithm
   240  	hash       crypto.Hash
   241  }{
   242  	{MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
   243  	{MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
   244  	{SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
   245  	{SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
   246  	{SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
   247  	{SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
   248  	{SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
   249  	{SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
   250  	{SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
   251  	{SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
   252  	{DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
   253  	{DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
   254  	{ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
   255  	{ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
   256  	{ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
   257  	{ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
   258  	{SHA256WithSM2, "SM2-SHA256", oidSignatureSHA256WithSM2, ECDSA, crypto.SHA256},
   259  	{SM3WithSM2, "SM2-SM3", oidSignatureSM3WithSM2, ECDSA, crypto.Hash(bccrypto.HASH_TYPE_SM3)},
   260  }
   261  
   262  // pssParameters reflects the parameters in an AlgorithmIdentifier that
   263  // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
   264  type pssParameters struct {
   265  	// The following three fields are not marked as
   266  	// optional because the default values specify SHA-1,
   267  	// which is no longer suitable for use in signatures.
   268  	Hash         pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
   269  	MGF          pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
   270  	SaltLength   int                      `asn1:"explicit,tag:2"`
   271  	TrailerField int                      `asn1:"optional,explicit,tag:3,default:1"`
   272  }
   273  
   274  // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
   275  // in an AlgorithmIdentifier that specifies RSA PSS.
   276  func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue {
   277  	var hashOID asn1.ObjectIdentifier
   278  
   279  	switch hashFunc {
   280  	case crypto.SHA256:
   281  		hashOID = oidSHA256
   282  	case crypto.SHA384:
   283  		hashOID = oidSHA384
   284  	case crypto.SHA512:
   285  		hashOID = oidSHA512
   286  	}
   287  
   288  	params := pssParameters{
   289  		Hash: pkix.AlgorithmIdentifier{
   290  			Algorithm:  hashOID,
   291  			Parameters: asn1.NullRawValue,
   292  		},
   293  		MGF: pkix.AlgorithmIdentifier{
   294  			Algorithm: oidMGF1,
   295  		},
   296  		SaltLength:   hashFunc.Size(),
   297  		TrailerField: 1,
   298  	}
   299  
   300  	mgf1Params := pkix.AlgorithmIdentifier{
   301  		Algorithm:  hashOID,
   302  		Parameters: asn1.NullRawValue,
   303  	}
   304  
   305  	var err error
   306  	params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
   307  	if err != nil {
   308  		panic(err)
   309  	}
   310  
   311  	serialized, err := asn1.Marshal(params)
   312  	if err != nil {
   313  		panic(err)
   314  	}
   315  
   316  	return asn1.RawValue{FullBytes: serialized}
   317  }
   318  
   319  func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
   320  	if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
   321  		for _, details := range signatureAlgorithmDetails {
   322  			if ai.Algorithm.Equal(details.oid) {
   323  				return details.algo
   324  			}
   325  		}
   326  		return UnknownSignatureAlgorithm
   327  	}
   328  
   329  	// RSA PSS is special because it encodes important parameters
   330  	// in the Parameters.
   331  
   332  	var params pssParameters
   333  	if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, &params); err != nil {
   334  		return UnknownSignatureAlgorithm
   335  	}
   336  
   337  	var mgf1HashFunc pkix.AlgorithmIdentifier
   338  	if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
   339  		return UnknownSignatureAlgorithm
   340  	}
   341  
   342  	// PSS is greatly overburdened with options. This code forces them into
   343  	// three buckets by requiring that the MGF1 hash function always match the
   344  	// message hash function (as recommended in RFC 3447, Section 8.1), that the
   345  	// salt length matches the hash length, and that the trailer field has the
   346  	// default value.
   347  	if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
   348  		!params.MGF.Algorithm.Equal(oidMGF1) ||
   349  		!mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
   350  		(len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
   351  		params.TrailerField != 1 {
   352  		return UnknownSignatureAlgorithm
   353  	}
   354  
   355  	switch {
   356  	case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
   357  		return SHA256WithRSAPSS
   358  	case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
   359  		return SHA384WithRSAPSS
   360  	case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
   361  		return SHA512WithRSAPSS
   362  	}
   363  
   364  	return UnknownSignatureAlgorithm
   365  }
   366  
   367  // RFC 3279, 2.3 Public Key Algorithms
   368  //
   369  // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   370  //
   371  //	rsadsi(113549) pkcs(1) 1 }
   372  //
   373  // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
   374  //
   375  // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   376  //
   377  //	x9-57(10040) x9cm(4) 1 }
   378  //
   379  // # RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
   380  //
   381  //	id-ecPublicKey OBJECT IDENTIFIER ::= {
   382  //	      iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
   383  var (
   384  	oidPublicKeyRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
   385  	oidPublicKeyDSA   = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
   386  	oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
   387  
   388  	oidPublicKeySM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301, 1}
   389  )
   390  
   391  func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
   392  	switch {
   393  	case oid.Equal(oidPublicKeyRSA):
   394  		return RSA
   395  	case oid.Equal(oidPublicKeyDSA):
   396  		return DSA
   397  	case oid.Equal(oidPublicKeyECDSA):
   398  		return ECDSA
   399  	case oid.Equal(oidPublicKeySM2):
   400  		return SM2
   401  	}
   402  	return UnknownPublicKeyAlgorithm
   403  }
   404  
   405  // RFC 5480, 2.1.1.1. Named Curve
   406  //
   407  //	secp224r1 OBJECT IDENTIFIER ::= {
   408  //	  iso(1) identified-organization(3) certicom(132) curve(0) 33 }
   409  //
   410  //	secp256r1 OBJECT IDENTIFIER ::= {
   411  //	  iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
   412  //	  prime(1) 7 }
   413  //
   414  //	secp384r1 OBJECT IDENTIFIER ::= {
   415  //	  iso(1) identified-organization(3) certicom(132) curve(0) 34 }
   416  //
   417  //	secp521r1 OBJECT IDENTIFIER ::= {
   418  //	  iso(1) identified-organization(3) certicom(132) curve(0) 35 }
   419  //
   420  // NB: secp256r1 is equivalent to prime256v1
   421  var (
   422  	oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
   423  	oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
   424  	oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
   425  	oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
   426  
   427  	oidNamedCurveSm2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301}
   428  )
   429  
   430  func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
   431  	switch {
   432  	case oid.Equal(oidNamedCurveP224):
   433  		return elliptic.P224()
   434  	case oid.Equal(oidNamedCurveP256):
   435  		return elliptic.P256()
   436  	case oid.Equal(oidNamedCurveP384):
   437  		return elliptic.P384()
   438  	case oid.Equal(oidNamedCurveP521):
   439  		return elliptic.P521()
   440  	case oid.Equal(oidNamedCurveSm2):
   441  		return sm2.P256Sm2()
   442  	}
   443  	return nil
   444  }
   445  
   446  func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
   447  	switch curve {
   448  	case elliptic.P224():
   449  		return oidNamedCurveP224, true
   450  	case elliptic.P256():
   451  		return oidNamedCurveP256, true
   452  	case elliptic.P384():
   453  		return oidNamedCurveP384, true
   454  	case elliptic.P521():
   455  		return oidNamedCurveP521, true
   456  	case sm2.P256Sm2():
   457  		return oidNamedCurveSm2, true
   458  	}
   459  
   460  	return nil, false
   461  }
   462  
   463  // RFC 5280, 4.2.1.12  Extended Key Usage
   464  //
   465  // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
   466  //
   467  // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
   468  //
   469  // id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
   470  // id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
   471  // id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
   472  // id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
   473  // id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
   474  // id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
   475  var (
   476  	oidExtKeyUsageAny                            = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
   477  	oidExtKeyUsageServerAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
   478  	oidExtKeyUsageClientAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
   479  	oidExtKeyUsageCodeSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
   480  	oidExtKeyUsageEmailProtection                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
   481  	oidExtKeyUsageIPSECEndSystem                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
   482  	oidExtKeyUsageIPSECTunnel                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
   483  	oidExtKeyUsageIPSECUser                      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
   484  	oidExtKeyUsageTimeStamping                   = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
   485  	oidExtKeyUsageOCSPSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
   486  	oidExtKeyUsageMicrosoftServerGatedCrypto     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
   487  	oidExtKeyUsageNetscapeServerGatedCrypto      = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
   488  	oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
   489  	oidExtKeyUsageMicrosoftKernelCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
   490  )
   491  
   492  // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
   493  var extKeyUsageOIDs = []struct {
   494  	extKeyUsage x509.ExtKeyUsage
   495  	oid         asn1.ObjectIdentifier
   496  }{
   497  	{x509.ExtKeyUsageAny, oidExtKeyUsageAny},
   498  	{x509.ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
   499  	{x509.ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
   500  	{x509.ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
   501  	{x509.ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
   502  	{x509.ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
   503  	{x509.ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
   504  	{x509.ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
   505  	{x509.ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
   506  	{x509.ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
   507  	{x509.ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
   508  	{x509.ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
   509  	{x509.ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
   510  	{x509.ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
   511  }
   512  
   513  func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku x509.ExtKeyUsage, ok bool) {
   514  	for _, pair := range extKeyUsageOIDs {
   515  		if oid.Equal(pair.oid) {
   516  			return pair.extKeyUsage, true
   517  		}
   518  	}
   519  	return
   520  }
   521  
   522  func oidFromExtKeyUsage(eku x509.ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
   523  	for _, pair := range extKeyUsageOIDs {
   524  		if eku == pair.extKeyUsage {
   525  			return pair.oid, true
   526  		}
   527  	}
   528  	return
   529  }
   530  
   531  // A Certificate represents an X.509 certificate.
   532  type Certificate struct {
   533  	Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
   534  	RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
   535  	RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
   536  	RawSubject              []byte // DER encoded Subject
   537  	RawIssuer               []byte // DER encoded Issuer
   538  
   539  	Signature          []byte
   540  	SignatureAlgorithm SignatureAlgorithm
   541  
   542  	PublicKeyAlgorithm PublicKeyAlgorithm
   543  	PublicKey          bccrypto.PublicKey
   544  
   545  	Version             int
   546  	SerialNumber        *big.Int
   547  	Issuer              pkix.Name
   548  	Subject             pkix.Name
   549  	NotBefore, NotAfter time.Time // Validity bounds.
   550  	KeyUsage            x509.KeyUsage
   551  
   552  	// Extensions contains raw X.509 extensions. When parsing certificates,
   553  	// this can be used to extract non-critical extensions that are not
   554  	// parsed by this package. When marshaling certificates, the Extensions
   555  	// field is ignored, see ExtraExtensions.
   556  	Extensions []pkix.Extension
   557  
   558  	// ExtraExtensions contains extensions to be copied, raw, into any
   559  	// marshaled certificates. Values override any extensions that would
   560  	// otherwise be produced based on the other fields. The ExtraExtensions
   561  	// field is not populated when parsing certificates, see Extensions.
   562  	ExtraExtensions []pkix.Extension
   563  
   564  	// UnhandledCriticalExtensions contains a list of extension IDs that
   565  	// were not (fully) processed when parsing. Verify will fail if this
   566  	// slice is non-empty, unless verification is delegated to an OS
   567  	// library which understands all the critical extensions.
   568  	//
   569  	// Users can access these extensions using Extensions and can remove
   570  	// elements from this slice if they believe that they have been
   571  	// handled.
   572  	UnhandledCriticalExtensions []asn1.ObjectIdentifier
   573  
   574  	ExtKeyUsage        []x509.ExtKeyUsage      // Sequence of extended key usages.
   575  	UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
   576  
   577  	// BasicConstraintsValid indicates whether IsCA, MaxPathLen,
   578  	// and MaxPathLenZero are valid.
   579  	BasicConstraintsValid bool
   580  	IsCA                  bool
   581  
   582  	// MaxPathLen and MaxPathLenZero indicate the presence and
   583  	// value of the BasicConstraints' "pathLenConstraint".
   584  	//
   585  	// When parsing a certificate, a positive non-zero MaxPathLen
   586  	// means that the field was specified, -1 means it was unset,
   587  	// and MaxPathLenZero being true mean that the field was
   588  	// explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
   589  	// should be treated equivalent to -1 (unset).
   590  	//
   591  	// When generating a certificate, an unset pathLenConstraint
   592  	// can be requested with either MaxPathLen == -1 or using the
   593  	// zero value for both MaxPathLen and MaxPathLenZero.
   594  	MaxPathLen int
   595  	// MaxPathLenZero indicates that BasicConstraintsValid==true
   596  	// and MaxPathLen==0 should be interpreted as an actual
   597  	// maximum path length of zero. Otherwise, that combination is
   598  	// interpreted as MaxPathLen not being set.
   599  	MaxPathLenZero bool
   600  
   601  	SubjectKeyId   []byte
   602  	AuthorityKeyId []byte
   603  
   604  	// RFC 5280, 4.2.2.1 (Authority Information Access)
   605  	OCSPServer            []string
   606  	IssuingCertificateURL []string
   607  
   608  	// Subject Alternate Name values. (Note that these values may not be valid
   609  	// if invalid values were contained within a parsed certificate. For
   610  	// example, an element of DNSNames may not be a valid DNS domain name.)
   611  	DNSNames       []string
   612  	EmailAddresses []string
   613  	IPAddresses    []net.IP
   614  	URIs           []*url.URL
   615  
   616  	// Name constraints
   617  	PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
   618  	PermittedDNSDomains         []string
   619  	ExcludedDNSDomains          []string
   620  	PermittedIPRanges           []*net.IPNet
   621  	ExcludedIPRanges            []*net.IPNet
   622  	PermittedEmailAddresses     []string
   623  	ExcludedEmailAddresses      []string
   624  	PermittedURIDomains         []string
   625  	ExcludedURIDomains          []string
   626  
   627  	// CRL Distribution Points
   628  	CRLDistributionPoints []string
   629  
   630  	PolicyIdentifiers []asn1.ObjectIdentifier
   631  }
   632  
   633  // ErrUnsupportedAlgorithm results from attempting to perform an operation that
   634  // involves algorithms that are not currently implemented.
   635  var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
   636  
   637  // An InsecureAlgorithmError
   638  type InsecureAlgorithmError SignatureAlgorithm
   639  
   640  func (e InsecureAlgorithmError) Error() string {
   641  	return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
   642  }
   643  
   644  // ConstraintViolationError results when a requested usage is not permitted by
   645  // a certificate. For example: checking a signature when the public key isn't a
   646  // certificate signing key.
   647  type ConstraintViolationError struct{}
   648  
   649  func (ConstraintViolationError) Error() string {
   650  	return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
   651  }
   652  
   653  func (c *Certificate) Equal(other *Certificate) bool {
   654  	return bytes.Equal(c.Raw, other.Raw)
   655  }
   656  
   657  func (c *Certificate) hasSANExtension() bool {
   658  	return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
   659  }
   660  
   661  // Entrust have a broken root certificate (CN=Entrust.net Certification
   662  // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
   663  // according to PKIX.
   664  // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
   665  // from the Basic Constraints requirement.
   666  // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
   667  //
   668  // TODO(agl): remove this hack once their reissued root is sufficiently
   669  // widespread.
   670  var entrustBrokenSPKI = []byte{
   671  	0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
   672  	0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
   673  	0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
   674  	0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
   675  	0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
   676  	0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
   677  	0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
   678  	0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
   679  	0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
   680  	0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
   681  	0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
   682  	0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
   683  	0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
   684  	0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
   685  	0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
   686  	0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
   687  	0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
   688  	0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
   689  	0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
   690  	0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
   691  	0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
   692  	0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
   693  	0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
   694  	0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
   695  	0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
   696  	0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
   697  	0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
   698  	0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
   699  	0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
   700  	0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
   701  	0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
   702  	0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
   703  	0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
   704  	0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
   705  	0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
   706  	0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
   707  	0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
   708  }
   709  
   710  // CheckSignatureFrom verifies that the signature on c is a valid signature
   711  // from parent.
   712  func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
   713  	// RFC 5280, 4.2.1.9:
   714  	// "If the basic constraints extension is not present in a version 3
   715  	// certificate, or the extension is present but the cA boolean is not
   716  	// asserted, then the certified public key MUST NOT be used to verify
   717  	// certificate signatures."
   718  	// (except for Entrust, see comment above entrustBrokenSPKI)
   719  	if (parent.Version == 3 && !parent.BasicConstraintsValid ||
   720  		parent.BasicConstraintsValid && !parent.IsCA) &&
   721  		!bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
   722  		return ConstraintViolationError{}
   723  	}
   724  
   725  	if parent.KeyUsage != 0 && parent.KeyUsage&x509.KeyUsageCertSign == 0 {
   726  		return ConstraintViolationError{}
   727  	}
   728  
   729  	if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
   730  		return ErrUnsupportedAlgorithm
   731  	}
   732  
   733  	// TODO(agl): don't ignore the path length constraint.
   734  
   735  	return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
   736  }
   737  
   738  // CheckSignature verifies that signature is a valid signature over signed from
   739  // c's public key.
   740  func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
   741  	return checkSignature(algo, signed, signature, c.PublicKey)
   742  }
   743  
   744  func (c *Certificate) hasNameConstraints() bool {
   745  	return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
   746  }
   747  
   748  func (c *Certificate) getSANExtension() []byte {
   749  	for _, e := range c.Extensions {
   750  		if e.Id.Equal(oidExtensionSubjectAltName) {
   751  			return e.Value
   752  		}
   753  	}
   754  	return nil
   755  }
   756  
   757  // nolint: deadcode, unused
   758  func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
   759  	return fmt.Errorf(
   760  		"x509: signature algorithm specifies an %s public key, but have public key of type %T",
   761  		expectedPubKeyAlgo.String(), pubKey,
   762  	)
   763  }
   764  
   765  // CheckSignature verifies that signature is a valid signature over signed from
   766  // a libp2pcrypto.PublicKey.
   767  func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey bccrypto.PublicKey) (err error) {
   768  	hashAlgo, err := GetHashFromSignatureAlgorithm(algo)
   769  	if err != nil {
   770  		return err
   771  	}
   772  
   773  	ok, err := publicKey.VerifyWithOpts(signed, signature, &bccrypto.SignOpts{
   774  		Hash: hashAlgo,
   775  		UID:  bccrypto.CRYPTO_DEFAULT_UID,
   776  	})
   777  	if err != nil {
   778  		return err
   779  	}
   780  	if !ok {
   781  		return fmt.Errorf("invalid signature")
   782  	}
   783  
   784  	return nil
   785  }
   786  
   787  // CheckCRLSignature checks that the signature in crl is from c.
   788  func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
   789  	algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
   790  	return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
   791  }
   792  
   793  type UnhandledCriticalExtension struct{}
   794  
   795  func (h UnhandledCriticalExtension) Error() string {
   796  	return "x509: unhandled critical extension"
   797  }
   798  
   799  type basicConstraints struct {
   800  	IsCA       bool `asn1:"optional"`
   801  	MaxPathLen int  `asn1:"optional,default:-1"`
   802  }
   803  
   804  // RFC 5280 4.2.1.4
   805  type policyInformation struct {
   806  	Policy asn1.ObjectIdentifier
   807  	// policyQualifiers omitted
   808  }
   809  
   810  const (
   811  	nameTypeEmail = 1
   812  	nameTypeDNS   = 2
   813  	nameTypeURI   = 6
   814  	nameTypeIP    = 7
   815  )
   816  
   817  // RFC 5280, 4.2.2.1
   818  type authorityInfoAccess struct {
   819  	Method   asn1.ObjectIdentifier
   820  	Location asn1.RawValue
   821  }
   822  
   823  type generalSubtree struct {
   824  	Name string `asn1:"tag:2,optional,ia5"`
   825  }
   826  
   827  // RFC 5280, 4.2.1.10
   828  type nameConstraints struct {
   829  	Permitted []generalSubtree `asn1:"optional,tag:0"`
   830  	Excluded  []generalSubtree `asn1:"optional,tag:1"`
   831  }
   832  
   833  // RFC 5280, 4.2.1.14
   834  type distributionPoint struct {
   835  	DistributionPoint distributionPointName `asn1:"optional,tag:0"`
   836  	Reason            asn1.BitString        `asn1:"optional,tag:1"`
   837  	CRLIssuer         asn1.RawValue         `asn1:"optional,tag:2"`
   838  }
   839  
   840  type distributionPointName struct {
   841  	FullName     []asn1.RawValue  `asn1:"optional,tag:0"`
   842  	RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
   843  }
   844  
   845  func forEachSAN(extension []byte, callback func(int, []byte) error) error {
   846  	// RFC 5280, 4.2.1.6
   847  
   848  	// SubjectAltName ::= GeneralNames
   849  	//
   850  	// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
   851  	//
   852  	// GeneralName ::= CHOICE {
   853  	//      otherName                       [0]     OtherName,
   854  	//      rfc822Name                      [1]     IA5String,
   855  	//      dNSName                         [2]     IA5String,
   856  	//      x400Address                     [3]     ORAddress,
   857  	//      directoryName                   [4]     Name,
   858  	//      ediPartyName                    [5]     EDIPartyName,
   859  	//      uniformResourceIdentifier       [6]     IA5String,
   860  	//      iPAddress                       [7]     OCTET STRING,
   861  	//      registeredID                    [8]     OBJECT IDENTIFIER }
   862  	var seq asn1.RawValue
   863  	rest, err := asn1.Unmarshal(extension, &seq)
   864  	if err != nil {
   865  		return err
   866  	} else if len(rest) != 0 {
   867  		return errors.New("x509: trailing data after X.509 extension")
   868  	}
   869  	if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
   870  		return asn1.StructuralError{Msg: "bad SAN sequence"}
   871  	}
   872  
   873  	rest = seq.Bytes
   874  	for len(rest) > 0 {
   875  		var v asn1.RawValue
   876  		rest, err = asn1.Unmarshal(rest, &v)
   877  		if err != nil {
   878  			return err
   879  		}
   880  
   881  		if err := callback(v.Tag, v.Bytes); err != nil {
   882  			return err
   883  		}
   884  	}
   885  
   886  	return nil
   887  }
   888  
   889  func parseSANExtension(value []byte) (dnsNames, emailAddresses []string,
   890  	ipAddresses []net.IP, uris []*url.URL, err error) {
   891  	err = forEachSAN(value, func(tag int, data []byte) error {
   892  		switch tag {
   893  		case nameTypeEmail:
   894  			emailAddresses = append(emailAddresses, string(data))
   895  		case nameTypeDNS:
   896  			dnsNames = append(dnsNames, string(data))
   897  		case nameTypeURI:
   898  			uri, err := url.Parse(string(data))
   899  			if err != nil {
   900  				return fmt.Errorf("x509: cannot parse URI %q: %s", string(data), err)
   901  			}
   902  			if len(uri.Host) > 0 {
   903  				if _, ok := domainToReverseLabels(uri.Host); !ok {
   904  					return fmt.Errorf("x509: cannot parse URI %q: invalid domain", string(data))
   905  				}
   906  			}
   907  			uris = append(uris, uri)
   908  		case nameTypeIP:
   909  			switch len(data) {
   910  			case net.IPv4len, net.IPv6len:
   911  				ipAddresses = append(ipAddresses, data)
   912  			default:
   913  				return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
   914  			}
   915  		}
   916  
   917  		return nil
   918  	})
   919  
   920  	return
   921  }
   922  
   923  // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
   924  func isValidIPMask(mask []byte) bool {
   925  	seenZero := false
   926  
   927  	for _, b := range mask {
   928  		if seenZero {
   929  			if b != 0 {
   930  				return false
   931  			}
   932  
   933  			continue
   934  		}
   935  
   936  		switch b {
   937  		case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
   938  			seenZero = true
   939  		case 0xff:
   940  		default:
   941  			return false
   942  		}
   943  	}
   944  
   945  	return true
   946  }
   947  
   948  func reverseBitsInAByte(in byte) byte {
   949  	b1 := in>>4 | in<<4
   950  	b2 := b1>>2&0x33 | b1<<2&0xcc
   951  	b3 := b2>>1&0x55 | b2<<1&0xaa
   952  	return b3
   953  }
   954  
   955  // asn1BitLength returns the bit-length of bitString by considering the
   956  // most-significant bit in a byte to be the "first" bit. This convention
   957  // matches ASN.1, but differs from almost everything else.
   958  func asn1BitLength(bitString []byte) int {
   959  	bitLen := len(bitString) * 8
   960  
   961  	for i := range bitString {
   962  		b := bitString[len(bitString)-i-1]
   963  
   964  		for bit := uint(0); bit < 8; bit++ {
   965  			if (b>>bit)&1 == 1 {
   966  				return bitLen
   967  			}
   968  			bitLen--
   969  		}
   970  	}
   971  
   972  	return 0
   973  }
   974  
   975  var (
   976  	oidExtensionSubjectKeyId          = []int{2, 5, 29, 14}
   977  	oidExtensionKeyUsage              = []int{2, 5, 29, 15}
   978  	oidExtensionExtendedKeyUsage      = []int{2, 5, 29, 37}
   979  	oidExtensionAuthorityKeyId        = []int{2, 5, 29, 35}
   980  	oidExtensionBasicConstraints      = []int{2, 5, 29, 19}
   981  	oidExtensionSubjectAltName        = []int{2, 5, 29, 17}
   982  	oidExtensionCertificatePolicies   = []int{2, 5, 29, 32}
   983  	oidExtensionNameConstraints       = []int{2, 5, 29, 30}
   984  	oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
   985  	oidExtensionAuthorityInfoAccess   = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
   986  )
   987  
   988  var (
   989  	oidAuthorityInfoAccessOcsp    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
   990  	oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
   991  )
   992  
   993  // oidNotInExtensions reports whether an extension with the given oid exists in
   994  // extensions.
   995  func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
   996  	for _, e := range extensions {
   997  		if e.Id.Equal(oid) {
   998  			return true
   999  		}
  1000  	}
  1001  	return false
  1002  }
  1003  
  1004  func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (bccrypto.PublicKey, error) {
  1005  	asn1Data := keyData.PublicKey.RightAlign()
  1006  	switch algo {
  1007  	case RSA:
  1008  		// RSA public keys must have a NULL in the parameters.
  1009  		// See RFC 3279, Section 2.3.1.
  1010  		if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
  1011  			return nil, errors.New("x509: RSA key missing NULL parameters")
  1012  		}
  1013  
  1014  		p := new(pkcs1PublicKey)
  1015  		rest, err := asn1.Unmarshal(asn1Data, p)
  1016  		if err != nil {
  1017  			return nil, err
  1018  		}
  1019  		if len(rest) != 0 {
  1020  			return nil, errors.New("x509: trailing data after RSA public key")
  1021  		}
  1022  
  1023  		if p.N.Sign() <= 0 {
  1024  			return nil, errors.New("x509: RSA modulus is not a positive number")
  1025  		}
  1026  		if p.E <= 0 {
  1027  			return nil, errors.New("x509: RSA public exponent is not a positive number")
  1028  		}
  1029  
  1030  		pub := &rsa.PublicKey{
  1031  			E: p.E,
  1032  			N: p.N,
  1033  		}
  1034  		return &bcrsa.PublicKey{K: pub}, nil
  1035  	case ECDSA:
  1036  		paramsData := keyData.Algorithm.Parameters.FullBytes
  1037  		namedCurveOID := new(asn1.ObjectIdentifier)
  1038  		rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
  1039  		if err != nil {
  1040  			return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
  1041  		}
  1042  		if len(rest) != 0 {
  1043  			return nil, errors.New("x509: trailing data after ECDSA parameters")
  1044  		}
  1045  		namedCurve := namedCurveFromOID(*namedCurveOID)
  1046  		if namedCurve == nil {
  1047  			return nil, errors.New("x509: unsupported elliptic curve")
  1048  		}
  1049  		if namedCurveOID.Equal(oidNamedCurveSm2) {
  1050  			pk, err := asym.ParseSM2PublicKey(asn1Data)
  1051  			if err != nil {
  1052  				return nil, fmt.Errorf("fail to unmarshal sm2 public key")
  1053  			}
  1054  			return &bcsm2.PublicKey{K: pk}, nil
  1055  		}
  1056  		x, y := elliptic.Unmarshal(namedCurve, asn1Data)
  1057  		if x == nil {
  1058  			return nil, errors.New("x509: failed to unmarshal elliptic curve point")
  1059  		}
  1060  		pub := &ecdsa.PublicKey{
  1061  			Curve: namedCurve,
  1062  			X:     x,
  1063  			Y:     y,
  1064  		}
  1065  		//fmt.Println("parse to ecdsa.PublicKey")
  1066  		return &bcecdsa.PublicKey{K: pub}, nil
  1067  	case SM2:
  1068  		paramsData := keyData.Algorithm.Parameters.FullBytes
  1069  		namedCurveOID := new(asn1.ObjectIdentifier)
  1070  		rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
  1071  		if err != nil {
  1072  			return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
  1073  		}
  1074  		if len(rest) != 0 {
  1075  			return nil, errors.New("x509: trailing data after ECDSA parameters")
  1076  		}
  1077  		namedCurve := namedCurveFromOID(*namedCurveOID)
  1078  		if namedCurve == nil {
  1079  			return nil, errors.New("x509: unsupported elliptic curve")
  1080  		}
  1081  		pk, err := tjx509.ParseSm2PublicKey(asn1Data)
  1082  		if err != nil {
  1083  			pk, err = asym.ParseSM2PublicKey(asn1Data)
  1084  			if err != nil {
  1085  				return nil, errors.New("fail to unmarshal sm2 public key")
  1086  			}
  1087  		}
  1088  		return &bcsm2.PublicKey{K: pk}, nil
  1089  
  1090  	default:
  1091  		return nil, nil
  1092  	}
  1093  }
  1094  
  1095  // marshalSANs marshals a list of addresses into a the contents of an X.509
  1096  // SubjectAlternativeName extension.
  1097  func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) {
  1098  	var rawValues []asn1.RawValue
  1099  	for _, name := range dnsNames {
  1100  		rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
  1101  	}
  1102  	for _, email := range emailAddresses {
  1103  		rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
  1104  	}
  1105  	for _, rawIP := range ipAddresses {
  1106  		// If possible, we always want to encode IPv4 addresses in 4 bytes.
  1107  		ip := rawIP.To4()
  1108  		if ip == nil {
  1109  			ip = rawIP
  1110  		}
  1111  		rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
  1112  	}
  1113  	return asn1.Marshal(rawValues)
  1114  }
  1115  
  1116  func isIA5String(s string) error {
  1117  	for _, r := range s {
  1118  		if r >= utf8.RuneSelf {
  1119  			return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
  1120  		}
  1121  	}
  1122  
  1123  	return nil
  1124  }
  1125  
  1126  // nolint: gocyclo, revive
  1127  func buildExtensions(template *x509.Certificate) (ret []pkix.Extension, err error) {
  1128  	ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
  1129  	n := 0
  1130  
  1131  	if template.KeyUsage != 0 &&
  1132  		!oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
  1133  		ret[n].Id = oidExtensionKeyUsage
  1134  		ret[n].Critical = true
  1135  
  1136  		var a [2]byte
  1137  		a[0] = reverseBitsInAByte(byte(template.KeyUsage))
  1138  		a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
  1139  
  1140  		l := 1
  1141  		if a[1] != 0 {
  1142  			l = 2
  1143  		}
  1144  
  1145  		bitString := a[:l]
  1146  		ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
  1147  		if err != nil {
  1148  			return
  1149  		}
  1150  		n++
  1151  	}
  1152  
  1153  	if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
  1154  		!oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
  1155  		ret[n].Id = oidExtensionExtendedKeyUsage
  1156  
  1157  		var oids []asn1.ObjectIdentifier
  1158  		for _, u := range template.ExtKeyUsage {
  1159  			if oid, ok := oidFromExtKeyUsage(u); ok {
  1160  				oids = append(oids, oid)
  1161  			} else {
  1162  				panic("internal error")
  1163  			}
  1164  		}
  1165  
  1166  		oids = append(oids, template.UnknownExtKeyUsage...)
  1167  
  1168  		ret[n].Value, err = asn1.Marshal(oids)
  1169  		if err != nil {
  1170  			return
  1171  		}
  1172  		n++
  1173  	}
  1174  
  1175  	if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
  1176  		// Leaving MaxPathLen as zero indicates that no maximum path
  1177  		// length is desired, unless MaxPathLenZero is set. A value of
  1178  		// -1 causes encoding/asn1 to omit the value as desired.
  1179  		maxPathLen := template.MaxPathLen
  1180  		if maxPathLen == 0 && !template.MaxPathLenZero {
  1181  			maxPathLen = -1
  1182  		}
  1183  		ret[n].Id = oidExtensionBasicConstraints
  1184  		ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
  1185  		ret[n].Critical = true
  1186  		if err != nil {
  1187  			return
  1188  		}
  1189  		n++
  1190  	}
  1191  
  1192  	if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
  1193  		ret[n].Id = oidExtensionSubjectKeyId
  1194  		ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
  1195  		if err != nil {
  1196  			return
  1197  		}
  1198  		n++
  1199  	}
  1200  
  1201  	if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
  1202  		ret[n].Id = oidExtensionAuthorityKeyId
  1203  		ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
  1204  		if err != nil {
  1205  			return
  1206  		}
  1207  		n++
  1208  	}
  1209  
  1210  	if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
  1211  		!oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
  1212  		ret[n].Id = oidExtensionAuthorityInfoAccess
  1213  		var aiaValues []authorityInfoAccess
  1214  		for _, name := range template.OCSPServer {
  1215  			aiaValues = append(aiaValues, authorityInfoAccess{
  1216  				Method:   oidAuthorityInfoAccessOcsp,
  1217  				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1218  			})
  1219  		}
  1220  		for _, name := range template.IssuingCertificateURL {
  1221  			aiaValues = append(aiaValues, authorityInfoAccess{
  1222  				Method:   oidAuthorityInfoAccessIssuers,
  1223  				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1224  			})
  1225  		}
  1226  		ret[n].Value, err = asn1.Marshal(aiaValues)
  1227  		if err != nil {
  1228  			return
  1229  		}
  1230  		n++
  1231  	}
  1232  
  1233  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
  1234  		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1235  		ret[n].Id = oidExtensionSubjectAltName
  1236  		ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses)
  1237  		if err != nil {
  1238  			return
  1239  		}
  1240  		n++
  1241  	}
  1242  
  1243  	if len(template.PolicyIdentifiers) > 0 &&
  1244  		!oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
  1245  		ret[n].Id = oidExtensionCertificatePolicies
  1246  		policies := make([]policyInformation, len(template.PolicyIdentifiers))
  1247  		for i, policy := range template.PolicyIdentifiers {
  1248  			policies[i].Policy = policy
  1249  		}
  1250  		ret[n].Value, err = asn1.Marshal(policies)
  1251  		if err != nil {
  1252  			return
  1253  		}
  1254  		n++
  1255  	}
  1256  
  1257  	if len(template.PermittedDNSDomains) > 0 &&
  1258  		!oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
  1259  		ret[n].Id = oidExtensionNameConstraints
  1260  		ret[n].Critical = template.PermittedDNSDomainsCritical
  1261  
  1262  		var out nameConstraints
  1263  		out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
  1264  		for i, permitted := range template.PermittedDNSDomains {
  1265  			out.Permitted[i] = generalSubtree{Name: permitted}
  1266  		}
  1267  		ret[n].Value, err = asn1.Marshal(out)
  1268  		if err != nil {
  1269  			return
  1270  		}
  1271  		n++
  1272  	}
  1273  
  1274  	if len(template.CRLDistributionPoints) > 0 &&
  1275  		!oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
  1276  		ret[n].Id = oidExtensionCRLDistributionPoints
  1277  
  1278  		var crlDp []distributionPoint
  1279  		for _, name := range template.CRLDistributionPoints {
  1280  			rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)})
  1281  
  1282  			dp := distributionPoint{
  1283  				DistributionPoint: distributionPointName{
  1284  					FullName: []asn1.RawValue{
  1285  						{Tag: 0, Class: 2, IsCompound: true, Bytes: rawFullName},
  1286  					},
  1287  				},
  1288  			}
  1289  			crlDp = append(crlDp, dp)
  1290  		}
  1291  
  1292  		ret[n].Value, err = asn1.Marshal(crlDp)
  1293  		if err != nil {
  1294  			return
  1295  		}
  1296  		n++
  1297  	}
  1298  
  1299  	// Adding another extension here? Remember to update the maximum number
  1300  	// of elements in the make() at the top of the function.
  1301  
  1302  	return append(ret[:n], template.ExtraExtensions...), nil
  1303  }
  1304  
  1305  // nolint: gocyclo
  1306  func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) {
  1307  	// RFC 5280, 4.2.1.10
  1308  
  1309  	// NameConstraints ::= SEQUENCE {
  1310  	//      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
  1311  	//      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
  1312  	//
  1313  	// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
  1314  	//
  1315  	// GeneralSubtree ::= SEQUENCE {
  1316  	//      base                    GeneralName,
  1317  	//      minimum         [0]     BaseDistance DEFAULT 0,
  1318  	//      maximum         [1]     BaseDistance OPTIONAL }
  1319  	//
  1320  	// BaseDistance ::= INTEGER (0..MAX)
  1321  
  1322  	outer := cryptobyte.String(e.Value)
  1323  	var toplevel, permitted, excluded cryptobyte.String
  1324  	var havePermitted, haveExcluded bool
  1325  	if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
  1326  		!outer.Empty() ||
  1327  		!toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
  1328  		!toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
  1329  		!toplevel.Empty() {
  1330  		return false, errors.New("x509: invalid NameConstraints extension")
  1331  	}
  1332  
  1333  	if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
  1334  		// From RFC 5280, Section 4.2.1.10:
  1335  		//   “either the permittedSubtrees field
  1336  		//   or the excludedSubtrees MUST be
  1337  		//   present”
  1338  		return false, errors.New("x509: empty name constraints extension")
  1339  	}
  1340  
  1341  	getValues := func(subtrees cryptobyte.String) (
  1342  		dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
  1343  		for !subtrees.Empty() {
  1344  			var seq, value cryptobyte.String
  1345  			var tag cryptobyte_asn1.Tag
  1346  			if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
  1347  				!seq.ReadAnyASN1(&value, &tag) {
  1348  				return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
  1349  			}
  1350  
  1351  			var (
  1352  				dnsTag   = cryptobyte_asn1.Tag(2).ContextSpecific()
  1353  				emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
  1354  				ipTag    = cryptobyte_asn1.Tag(7).ContextSpecific()
  1355  				uriTag   = cryptobyte_asn1.Tag(6).ContextSpecific()
  1356  			)
  1357  
  1358  			switch tag {
  1359  			case dnsTag:
  1360  				domain := string(value)
  1361  				if err := isIA5String(domain); err != nil {
  1362  					return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
  1363  				}
  1364  
  1365  				trimmedDomain := domain
  1366  				if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
  1367  					// constraints can have a leading
  1368  					// period to exclude the domain
  1369  					// itself, but that's not valid in a
  1370  					// normal domain name.
  1371  					trimmedDomain = trimmedDomain[1:]
  1372  				}
  1373  				if _, ok := domainToReverseLabels(trimmedDomain); !ok {
  1374  					return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
  1375  				}
  1376  				dnsNames = append(dnsNames, domain)
  1377  
  1378  			case ipTag:
  1379  				l := len(value)
  1380  				var ip, mask []byte
  1381  
  1382  				switch l {
  1383  				case 8:
  1384  					ip = value[:4]
  1385  					mask = value[4:]
  1386  
  1387  				case 32:
  1388  					ip = value[:16]
  1389  					mask = value[16:]
  1390  
  1391  				default:
  1392  					return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
  1393  				}
  1394  
  1395  				if !isValidIPMask(mask) {
  1396  					return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
  1397  				}
  1398  
  1399  				ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
  1400  
  1401  			case emailTag:
  1402  				constraint := string(value)
  1403  				if err := isIA5String(constraint); err != nil {
  1404  					return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
  1405  				}
  1406  
  1407  				// If the constraint contains an @ then
  1408  				// it specifies an exact mailbox name.
  1409  				if strings.Contains(constraint, "@") {
  1410  					if _, ok := parseRFC2821Mailbox(constraint); !ok {
  1411  						return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
  1412  					}
  1413  				} else {
  1414  					// Otherwise it's a domain name.
  1415  					domain := constraint
  1416  					if len(domain) > 0 && domain[0] == '.' {
  1417  						domain = domain[1:]
  1418  					}
  1419  					if _, ok := domainToReverseLabels(domain); !ok {
  1420  						return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
  1421  					}
  1422  				}
  1423  				emails = append(emails, constraint)
  1424  
  1425  			case uriTag:
  1426  				domain := string(value)
  1427  				if err := isIA5String(domain); err != nil {
  1428  					return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
  1429  				}
  1430  
  1431  				if net.ParseIP(domain) != nil {
  1432  					return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
  1433  				}
  1434  
  1435  				trimmedDomain := domain
  1436  				if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
  1437  					// constraints can have a leading
  1438  					// period to exclude the domain itself,
  1439  					// but that's not valid in a normal
  1440  					// domain name.
  1441  					trimmedDomain = trimmedDomain[1:]
  1442  				}
  1443  				if _, ok := domainToReverseLabels(trimmedDomain); !ok {
  1444  					return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain)
  1445  				}
  1446  				uriDomains = append(uriDomains, domain)
  1447  
  1448  			default:
  1449  				unhandled = true
  1450  			}
  1451  		}
  1452  
  1453  		return dnsNames, ips, emails, uriDomains, nil
  1454  	}
  1455  
  1456  	if out.PermittedDNSDomains,
  1457  		out.PermittedIPRanges,
  1458  		out.PermittedEmailAddresses,
  1459  		out.PermittedURIDomains,
  1460  		err = getValues(permitted); err != nil {
  1461  		return false, err
  1462  	}
  1463  	if out.ExcludedDNSDomains,
  1464  		out.ExcludedIPRanges,
  1465  		out.ExcludedEmailAddresses,
  1466  		out.ExcludedURIDomains,
  1467  		err = getValues(excluded); err != nil {
  1468  		return false, err
  1469  	}
  1470  	out.PermittedDNSDomainsCritical = e.Critical
  1471  
  1472  	return unhandled, nil
  1473  }
  1474  
  1475  // nolint: gocyclo, govet, revive
  1476  func parseCertificate(in *certificate) (*Certificate, error) {
  1477  	out := new(Certificate)
  1478  	out.Raw = in.Raw
  1479  	out.RawTBSCertificate = in.TBSCertificate.Raw
  1480  	out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
  1481  	out.RawSubject = in.TBSCertificate.Subject.FullBytes
  1482  	out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
  1483  
  1484  	out.Signature = in.SignatureValue.RightAlign()
  1485  	out.SignatureAlgorithm =
  1486  		getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
  1487  
  1488  	out.PublicKeyAlgorithm =
  1489  		getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
  1490  	var err error
  1491  	out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
  1492  	if err != nil {
  1493  		return nil, err
  1494  	}
  1495  
  1496  	out.Version = in.TBSCertificate.Version + 1
  1497  	out.SerialNumber = in.TBSCertificate.SerialNumber
  1498  
  1499  	var issuer, subject pkix.RDNSequence
  1500  	if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
  1501  		return nil, err
  1502  	} else if len(rest) != 0 {
  1503  		return nil, errors.New("x509: trailing data after X.509 subject")
  1504  	}
  1505  	if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
  1506  		return nil, err
  1507  	} else if len(rest) != 0 {
  1508  		return nil, errors.New("x509: trailing data after X.509 subject")
  1509  	}
  1510  
  1511  	out.Issuer.FillFromRDNSequence(&issuer)
  1512  	out.Subject.FillFromRDNSequence(&subject)
  1513  
  1514  	out.NotBefore = in.TBSCertificate.Validity.NotBefore
  1515  	out.NotAfter = in.TBSCertificate.Validity.NotAfter
  1516  
  1517  	for _, e := range in.TBSCertificate.Extensions {
  1518  		out.Extensions = append(out.Extensions, e)
  1519  		unhandled := false
  1520  
  1521  		if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
  1522  			switch e.Id[3] {
  1523  			case 15:
  1524  				// RFC 5280, 4.2.1.3
  1525  				var usageBits asn1.BitString
  1526  				if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
  1527  					return nil, err
  1528  				} else if len(rest) != 0 {
  1529  					return nil, errors.New("x509: trailing data after X.509 KeyUsage")
  1530  				}
  1531  
  1532  				var usage int
  1533  				for i := 0; i < 9; i++ {
  1534  					if usageBits.At(i) != 0 {
  1535  						usage |= 1 << uint(i)
  1536  					}
  1537  				}
  1538  				out.KeyUsage = x509.KeyUsage(usage)
  1539  
  1540  			case 19:
  1541  				// RFC 5280, 4.2.1.9
  1542  				var constraints basicConstraints
  1543  				if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
  1544  					return nil, err
  1545  				} else if len(rest) != 0 {
  1546  					return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
  1547  				}
  1548  
  1549  				out.BasicConstraintsValid = true
  1550  				out.IsCA = constraints.IsCA
  1551  				out.MaxPathLen = constraints.MaxPathLen
  1552  				out.MaxPathLenZero = out.MaxPathLen == 0
  1553  				// TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
  1554  			case 17:
  1555  				out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value)
  1556  				if err != nil {
  1557  					return nil, err
  1558  				}
  1559  
  1560  				if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
  1561  					// If we didn't parse anything then we do the critical check, below.
  1562  					unhandled = true
  1563  				}
  1564  
  1565  			case 30:
  1566  				unhandled, err = parseNameConstraintsExtension(out, e)
  1567  				if err != nil {
  1568  					return nil, err
  1569  				}
  1570  
  1571  			case 31:
  1572  				// RFC 5280, 4.2.1.13
  1573  
  1574  				// CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
  1575  				//
  1576  				// DistributionPoint ::= SEQUENCE {
  1577  				//     distributionPoint       [0]     DistributionPointName OPTIONAL,
  1578  				//     reasons                 [1]     ReasonFlags OPTIONAL,
  1579  				//     cRLIssuer               [2]     GeneralNames OPTIONAL }
  1580  				//
  1581  				// DistributionPointName ::= CHOICE {
  1582  				//     fullName                [0]     GeneralNames,
  1583  				//     nameRelativeToCRLIssuer [1]     RelativeDistinguishedName }
  1584  
  1585  				var cdp []distributionPoint
  1586  				if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
  1587  					return nil, err
  1588  				} else if len(rest) != 0 {
  1589  					return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
  1590  				}
  1591  
  1592  				for _, dp := range cdp {
  1593  					// Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
  1594  					if len(dp.DistributionPoint.FullName) == 0 {
  1595  						continue
  1596  					}
  1597  
  1598  					for _, fullName := range dp.DistributionPoint.FullName {
  1599  						if fullName.Tag == 6 {
  1600  							out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(fullName.Bytes))
  1601  						}
  1602  					}
  1603  				}
  1604  
  1605  			case 35:
  1606  				// RFC 5280, 4.2.1.1
  1607  				var a authKeyId
  1608  				if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
  1609  					return nil, err
  1610  				} else if len(rest) != 0 {
  1611  					return nil, errors.New("x509: trailing data after X.509 authority key-id")
  1612  				}
  1613  				out.AuthorityKeyId = a.Id
  1614  
  1615  			case 37:
  1616  				// RFC 5280, 4.2.1.12.  Extended Key Usage
  1617  
  1618  				// id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
  1619  				//
  1620  				// ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
  1621  				//
  1622  				// KeyPurposeId ::= OBJECT IDENTIFIER
  1623  
  1624  				var keyUsage []asn1.ObjectIdentifier
  1625  				if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
  1626  					return nil, err
  1627  				} else if len(rest) != 0 {
  1628  					return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
  1629  				}
  1630  
  1631  				for _, u := range keyUsage {
  1632  					if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
  1633  						out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
  1634  					} else {
  1635  						out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
  1636  					}
  1637  				}
  1638  
  1639  			case 14:
  1640  				// RFC 5280, 4.2.1.2
  1641  				var keyid []byte
  1642  				if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
  1643  					return nil, err
  1644  				} else if len(rest) != 0 {
  1645  					return nil, errors.New("x509: trailing data after X.509 key-id")
  1646  				}
  1647  				out.SubjectKeyId = keyid
  1648  
  1649  			case 32:
  1650  				// RFC 5280 4.2.1.4: Certificate Policies
  1651  				var policies []policyInformation
  1652  				if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
  1653  					return nil, err
  1654  				} else if len(rest) != 0 {
  1655  					return nil, errors.New("x509: trailing data after X.509 certificate policies")
  1656  				}
  1657  				out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
  1658  				for i, policy := range policies {
  1659  					out.PolicyIdentifiers[i] = policy.Policy
  1660  				}
  1661  
  1662  			default:
  1663  				// Unknown extensions are recorded if critical.
  1664  				unhandled = true
  1665  			}
  1666  		} else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
  1667  			// RFC 5280 4.2.2.1: Authority Information Access
  1668  			var aia []authorityInfoAccess
  1669  			if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
  1670  				return nil, err
  1671  			} else if len(rest) != 0 {
  1672  				return nil, errors.New("x509: trailing data after X.509 authority information")
  1673  			}
  1674  
  1675  			for _, v := range aia {
  1676  				// GeneralName: uniformResourceIdentifier [6] IA5String
  1677  				if v.Location.Tag != 6 {
  1678  					continue
  1679  				}
  1680  				if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
  1681  					out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
  1682  				} else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
  1683  					out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
  1684  				}
  1685  			}
  1686  		} else {
  1687  			// Unknown extensions are recorded if critical.
  1688  			unhandled = true
  1689  		}
  1690  
  1691  		if e.Critical && unhandled {
  1692  			out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
  1693  		}
  1694  	}
  1695  
  1696  	return out, nil
  1697  }
  1698  
  1699  // ParseCertificate parses a single certificate from the given ASN.1 DER data.
  1700  func ParseCertificate(asn1Data []byte) (*Certificate, error) {
  1701  	var cert certificate
  1702  	rest, err := asn1.Unmarshal(asn1Data, &cert)
  1703  	if err != nil {
  1704  		return nil, err
  1705  	}
  1706  	if len(rest) > 0 {
  1707  		return nil, asn1.SyntaxError{Msg: "trailing data"}
  1708  	}
  1709  
  1710  	return parseCertificate(&cert)
  1711  }
  1712  
  1713  // ParseCertificates parses one or more certificates from the given ASN.1 DER
  1714  // data. The certificates must be concatenated with no intermediate padding.
  1715  func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
  1716  	var v []*certificate
  1717  
  1718  	for len(asn1Data) > 0 {
  1719  		cert := new(certificate)
  1720  		var err error
  1721  		asn1Data, err = asn1.Unmarshal(asn1Data, cert)
  1722  		if err != nil {
  1723  			return nil, err
  1724  		}
  1725  		v = append(v, cert)
  1726  	}
  1727  
  1728  	ret := make([]*Certificate, len(v))
  1729  	for i, ci := range v {
  1730  		cert, err := parseCertificate(ci)
  1731  		if err != nil {
  1732  			return nil, err
  1733  		}
  1734  		ret[i] = cert
  1735  	}
  1736  
  1737  	return ret, nil
  1738  }
  1739  
  1740  func GetHashFromSignatureAlgorithm(algo SignatureAlgorithm) (bccrypto.HashType, error) {
  1741  	for _, details := range signatureAlgorithmDetails {
  1742  		if details.algo == algo {
  1743  			return bccrypto.HashType(details.hash), nil
  1744  		}
  1745  	}
  1746  	return 0, fmt.Errorf("certificate: invalid algorithm suite")
  1747  }
  1748  
  1749  func ChainMakerCertToX509Cert(cert *Certificate) (*x509.Certificate, error) {
  1750  	newCert := &x509.Certificate{
  1751  		Raw:                         cert.Raw,
  1752  		RawTBSCertificate:           cert.RawTBSCertificate,
  1753  		RawSubjectPublicKeyInfo:     cert.RawSubjectPublicKeyInfo,
  1754  		RawSubject:                  cert.RawSubject,
  1755  		RawIssuer:                   cert.RawIssuer,
  1756  		Signature:                   cert.Signature,
  1757  		SignatureAlgorithm:          x509.SignatureAlgorithm(cert.SignatureAlgorithm),
  1758  		PublicKeyAlgorithm:          x509.PublicKeyAlgorithm(cert.PublicKeyAlgorithm),
  1759  		PublicKey:                   cert.PublicKey.ToStandardKey(),
  1760  		Version:                     cert.Version,
  1761  		SerialNumber:                cert.SerialNumber,
  1762  		Issuer:                      cert.Issuer,
  1763  		Subject:                     cert.Subject,
  1764  		NotBefore:                   cert.NotBefore,
  1765  		NotAfter:                    cert.NotAfter,
  1766  		KeyUsage:                    cert.KeyUsage,
  1767  		Extensions:                  cert.Extensions,
  1768  		ExtraExtensions:             cert.ExtraExtensions,
  1769  		UnhandledCriticalExtensions: cert.UnhandledCriticalExtensions,
  1770  		ExtKeyUsage:                 cert.ExtKeyUsage,
  1771  		UnknownExtKeyUsage:          cert.UnknownExtKeyUsage,
  1772  		BasicConstraintsValid:       cert.BasicConstraintsValid,
  1773  		IsCA:                        cert.IsCA,
  1774  		MaxPathLen:                  cert.MaxPathLen,
  1775  		MaxPathLenZero:              cert.MaxPathLenZero,
  1776  		SubjectKeyId:                cert.SubjectKeyId,
  1777  		AuthorityKeyId:              cert.AuthorityKeyId,
  1778  		OCSPServer:                  cert.OCSPServer,
  1779  		IssuingCertificateURL:       cert.IssuingCertificateURL,
  1780  		DNSNames:                    cert.DNSNames,
  1781  		EmailAddresses:              cert.EmailAddresses,
  1782  		IPAddresses:                 cert.IPAddresses,
  1783  		URIs:                        cert.URIs,
  1784  		PermittedDNSDomainsCritical: cert.PermittedDNSDomainsCritical,
  1785  		PermittedDNSDomains:         cert.PermittedDNSDomains,
  1786  		ExcludedDNSDomains:          cert.ExcludedDNSDomains,
  1787  		PermittedIPRanges:           cert.PermittedIPRanges,
  1788  		ExcludedIPRanges:            cert.ExcludedIPRanges,
  1789  		PermittedEmailAddresses:     cert.PermittedEmailAddresses,
  1790  		ExcludedEmailAddresses:      cert.ExcludedEmailAddresses,
  1791  		PermittedURIDomains:         cert.PermittedURIDomains,
  1792  		ExcludedURIDomains:          cert.ExcludedURIDomains,
  1793  		CRLDistributionPoints:       cert.CRLDistributionPoints,
  1794  		PolicyIdentifiers:           cert.PolicyIdentifiers,
  1795  	}
  1796  	return newCert, nil
  1797  }
  1798  
  1799  func X509CertToChainMakerCert(cert *x509.Certificate) (*Certificate, error) {
  1800  	der, err := x509.MarshalPKIXPublicKey(cert.PublicKey)
  1801  	if err != nil {
  1802  		return nil, fmt.Errorf("fail to parse re-encode (marshal) public key in certificate: %v", err)
  1803  	}
  1804  	pk, err := asym.PublicKeyFromDER(der)
  1805  	if err != nil {
  1806  		return nil, fmt.Errorf("fail to parse re-encode (unmarshal) public key in certificate: %v", err)
  1807  	}
  1808  	newCert := &Certificate{
  1809  		Raw:                         cert.Raw,
  1810  		RawTBSCertificate:           cert.RawTBSCertificate,
  1811  		RawSubjectPublicKeyInfo:     cert.RawSubjectPublicKeyInfo,
  1812  		RawSubject:                  cert.RawSubject,
  1813  		RawIssuer:                   cert.RawIssuer,
  1814  		Signature:                   cert.Signature,
  1815  		SignatureAlgorithm:          SignatureAlgorithm(cert.SignatureAlgorithm),
  1816  		PublicKeyAlgorithm:          PublicKeyAlgorithm(cert.PublicKeyAlgorithm),
  1817  		PublicKey:                   pk,
  1818  		Version:                     cert.Version,
  1819  		SerialNumber:                cert.SerialNumber,
  1820  		Issuer:                      cert.Issuer,
  1821  		Subject:                     cert.Subject,
  1822  		NotBefore:                   cert.NotBefore,
  1823  		NotAfter:                    cert.NotAfter,
  1824  		KeyUsage:                    cert.KeyUsage,
  1825  		Extensions:                  cert.Extensions,
  1826  		ExtraExtensions:             cert.ExtraExtensions,
  1827  		UnhandledCriticalExtensions: cert.UnhandledCriticalExtensions,
  1828  		ExtKeyUsage:                 cert.ExtKeyUsage,
  1829  		UnknownExtKeyUsage:          cert.UnknownExtKeyUsage,
  1830  		BasicConstraintsValid:       cert.BasicConstraintsValid,
  1831  		IsCA:                        cert.IsCA,
  1832  		MaxPathLen:                  cert.MaxPathLen,
  1833  		MaxPathLenZero:              cert.MaxPathLenZero,
  1834  		SubjectKeyId:                cert.SubjectKeyId,
  1835  		AuthorityKeyId:              cert.AuthorityKeyId,
  1836  		OCSPServer:                  cert.OCSPServer,
  1837  		IssuingCertificateURL:       cert.IssuingCertificateURL,
  1838  		DNSNames:                    cert.DNSNames,
  1839  		EmailAddresses:              cert.EmailAddresses,
  1840  		IPAddresses:                 cert.IPAddresses,
  1841  		URIs:                        cert.URIs,
  1842  		PermittedDNSDomainsCritical: cert.PermittedDNSDomainsCritical,
  1843  		PermittedDNSDomains:         cert.PermittedDNSDomains,
  1844  		ExcludedDNSDomains:          cert.ExcludedDNSDomains,
  1845  		PermittedIPRanges:           cert.PermittedIPRanges,
  1846  		ExcludedIPRanges:            cert.ExcludedIPRanges,
  1847  		PermittedEmailAddresses:     cert.PermittedEmailAddresses,
  1848  		ExcludedEmailAddresses:      cert.ExcludedEmailAddresses,
  1849  		PermittedURIDomains:         cert.PermittedURIDomains,
  1850  		ExcludedURIDomains:          cert.ExcludedURIDomains,
  1851  		CRLDistributionPoints:       cert.CRLDistributionPoints,
  1852  		PolicyIdentifiers:           cert.PolicyIdentifiers,
  1853  	}
  1854  	return newCert, nil
  1855  }
  1856  
  1857  var OidNodeId = asn1.ObjectIdentifier{2, 87, 88, 2020, 11, 30, 2020, 11, 4}
  1858  
  1859  func GetExtByOid(oid asn1.ObjectIdentifier, extensions []pkix.Extension) ([]byte, error) {
  1860  	for _, e := range extensions {
  1861  		if e.Id.Equal(oid) {
  1862  			return e.Value, nil
  1863  		}
  1864  	}
  1865  	return nil, fmt.Errorf("extension with given oid does not exist")
  1866  }
  1867  
  1868  func GetAKIFromExtensions(extensions []pkix.Extension) ([]byte, bool, error) {
  1869  	akiASN1, err := GetExtByOid(oidExtensionAuthorityKeyId, extensions)
  1870  	if err != nil {
  1871  		return nil, false, err
  1872  	}
  1873  	var aki authKeyId
  1874  	_, err = asn1.Unmarshal(akiASN1, &aki)
  1875  	if err != nil {
  1876  		return akiASN1, false, nil
  1877  	}
  1878  	return aki.Id, true, nil
  1879  }
  1880  
  1881  func GetNodeIdFromCertificate(oid asn1.ObjectIdentifier, cert x509.Certificate) ([]byte, error) {
  1882  	id, err := GetExtByOid(oid, cert.Extensions)
  1883  	if err != nil || id == nil {
  1884  		id = []byte(cert.Subject.CommonName)
  1885  		if id == nil || len(id) <= 0 {
  1886  			return nil, fmt.Errorf("given certificate does not contain node ID")
  1887  		}
  1888  	}
  1889  	return id, nil
  1890  }
  1891  
  1892  func GetNodeIdFromSm2Certificate(oid asn1.ObjectIdentifier, cert Certificate) ([]byte, error) {
  1893  	id, err := GetExtByOid(oid, cert.Extensions)
  1894  	if err != nil || id == nil {
  1895  		id = []byte(cert.Subject.CommonName)
  1896  		if id == nil || len(id) <= 0 {
  1897  			return nil, fmt.Errorf("given certificate does not contain node ID")
  1898  		}
  1899  	}
  1900  	return id, nil
  1901  }
  1902  
  1903  // Create Certificate
  1904  
  1905  func (algo SignatureAlgorithm) isRSAPSS() bool {
  1906  	switch algo {
  1907  	case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
  1908  		return true
  1909  	default:
  1910  		return false
  1911  	}
  1912  }
  1913  
  1914  func subjectBytes(cert *x509.Certificate) ([]byte, error) {
  1915  	if len(cert.RawSubject) > 0 {
  1916  		return cert.RawSubject, nil
  1917  	}
  1918  
  1919  	return asn1.Marshal(cert.Subject.ToRDNSequence())
  1920  }
  1921  
  1922  // signingParamsForPublicKey returns the parameters to use for signing with
  1923  // priv. If requestedSigAlgo is not zero then it overrides the default
  1924  // signature algorithm.
  1925  func signingParamsForPublicKey(pub interface{},
  1926  	requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
  1927  	var pubType PublicKeyAlgorithm
  1928  
  1929  	switch pub := pub.(type) {
  1930  	case *rsa.PublicKey:
  1931  		pubType = RSA
  1932  		hashFunc = crypto.SHA256
  1933  		sigAlgo.Algorithm = oidSignatureSHA256WithRSA
  1934  		sigAlgo.Parameters = asn1.NullRawValue
  1935  
  1936  	case *ecdsa.PublicKey:
  1937  		pubType = ECDSA
  1938  
  1939  		switch pub.Curve {
  1940  		case elliptic.P224(), elliptic.P256():
  1941  			hashFunc = crypto.SHA256
  1942  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
  1943  		case elliptic.P384():
  1944  			hashFunc = crypto.SHA384
  1945  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
  1946  		case elliptic.P521():
  1947  			hashFunc = crypto.SHA512
  1948  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
  1949  		default:
  1950  			err = errors.New("x509: unknown elliptic curve")
  1951  		}
  1952  
  1953  	case *sm2.PublicKey:
  1954  		pubType = ECDSA
  1955  		//hashFunc = crypto.SHA256
  1956  		//sigAlgo.Algorithm = oidSignatureSHA256WithSM2
  1957  		hashFunc = crypto.Hash(bccrypto.HASH_TYPE_SM3)
  1958  		sigAlgo.Algorithm = oidSignatureSM3WithSM2
  1959  
  1960  	default:
  1961  		err = errors.New("x509: only RSA and ECDSA keys supported")
  1962  	}
  1963  
  1964  	if err != nil {
  1965  		return
  1966  	}
  1967  
  1968  	if requestedSigAlgo == 0 {
  1969  		return
  1970  	}
  1971  
  1972  	found := false
  1973  	for _, details := range signatureAlgorithmDetails {
  1974  		if details.algo == requestedSigAlgo {
  1975  			if details.pubKeyAlgo != pubType {
  1976  				err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
  1977  				return
  1978  			}
  1979  			sigAlgo.Algorithm, hashFunc = details.oid, details.hash
  1980  			if hashFunc == 0 {
  1981  				err = errors.New("x509: cannot sign with hash function requested")
  1982  				return
  1983  			}
  1984  			if requestedSigAlgo.isRSAPSS() {
  1985  				sigAlgo.Parameters = rsaPSSParameters(hashFunc)
  1986  			}
  1987  			found = true
  1988  			break
  1989  		}
  1990  	}
  1991  
  1992  	if !found {
  1993  		err = errors.New("x509: unknown SignatureAlgorithm")
  1994  	}
  1995  
  1996  	return
  1997  }
  1998  
  1999  func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
  2000  	switch pub := pub.(type) {
  2001  	case *rsa.PublicKey:
  2002  		publicKeyBytes, err = asn1.Marshal(rsaPublicKey{
  2003  			N: pub.N,
  2004  			E: pub.E,
  2005  		})
  2006  		if err != nil {
  2007  			return nil, pkix.AlgorithmIdentifier{}, err
  2008  		}
  2009  		publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
  2010  		// This is a NULL parameters value which is required by
  2011  		// https://tools.ietf.org/html/rfc3279#section-2.3.1.
  2012  		publicKeyAlgorithm.Parameters = asn1.RawValue{
  2013  			Tag: 5,
  2014  		}
  2015  	case *ecdsa.PublicKey:
  2016  		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  2017  		oid, ok := oidFromNamedCurve(pub.Curve)
  2018  		if !ok {
  2019  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported ecdsa.PublicKey elliptic curve")
  2020  		}
  2021  		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
  2022  		var paramBytes []byte
  2023  		paramBytes, err = asn1.Marshal(oid)
  2024  		if err != nil {
  2025  			return
  2026  		}
  2027  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
  2028  	case *sm2.PublicKey:
  2029  		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  2030  		oid, ok := oidFromNamedCurve(pub.Curve)
  2031  		if !ok {
  2032  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported marshal sm2 public key")
  2033  		}
  2034  		//oid := oidNamedCurveSm2
  2035  		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
  2036  		var paramBytes []byte
  2037  		paramBytes, err = asn1.Marshal(oid)
  2038  		if err != nil {
  2039  			return nil, pkix.AlgorithmIdentifier{}, errors.New("asn1 marshal sm2 oid failed")
  2040  		}
  2041  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
  2042  	default:
  2043  		return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA public keys supported")
  2044  
  2045  	}
  2046  
  2047  	return publicKeyBytes, publicKeyAlgorithm, nil
  2048  }
  2049  
  2050  // CreateCertificate creates a new certificate based on a template. The
  2051  // following members of template are used: SerialNumber, Subject, NotBefore,
  2052  // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
  2053  // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
  2054  // PermittedDNSDomains, SignatureAlgorithm.
  2055  //
  2056  // The certificate is signed by parent. If parent is equal to template then the
  2057  // certificate is self-signed. The parameter pub is the public key of the
  2058  // signee and priv is the private key of the signer.
  2059  //
  2060  // The returned slice is the certificate in DER encoding.
  2061  //
  2062  // All keys types that are implemented via crypto.Signer are supported (This
  2063  // includes *rsa.PublicKey and *ecdsa.PublicKey.)
  2064  func CreateCertificate(rand io.Reader, template,
  2065  	parent *x509.Certificate, pub, priv interface{}) (cert []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  	if template.SerialNumber == nil {
  2072  		return nil, errors.New("x509: no SerialNumber given")
  2073  	}
  2074  
  2075  	hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(
  2076  		key.Public(),
  2077  		SignatureAlgorithm(template.SignatureAlgorithm))
  2078  	if err != nil {
  2079  		return nil, err
  2080  	}
  2081  	publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
  2082  	if err != nil {
  2083  		return nil, err
  2084  	}
  2085  	asn1Issuer, err := subjectBytes(parent)
  2086  	if err != nil {
  2087  		return
  2088  	}
  2089  
  2090  	asn1Subject, err := subjectBytes(template)
  2091  	if err != nil {
  2092  		return
  2093  	}
  2094  
  2095  	if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
  2096  		template.AuthorityKeyId = parent.SubjectKeyId
  2097  	}
  2098  
  2099  	extensions, err := buildExtensions(template)
  2100  	if err != nil {
  2101  		return
  2102  	}
  2103  
  2104  	encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
  2105  	c := tbsCertificate{
  2106  		Version:            2,
  2107  		SerialNumber:       template.SerialNumber,
  2108  		SignatureAlgorithm: signatureAlgorithm,
  2109  		Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
  2110  		Validity:           validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
  2111  		Subject:            asn1.RawValue{FullBytes: asn1Subject},
  2112  		PublicKey:          publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
  2113  		Extensions:         extensions,
  2114  	}
  2115  
  2116  	tbsCertContents, err := asn1.Marshal(c)
  2117  	if err != nil {
  2118  		return
  2119  	}
  2120  
  2121  	c.Raw = tbsCertContents
  2122  
  2123  	var digest []byte
  2124  	if hashFunc == crypto.Hash(bccrypto.HASH_TYPE_SM3) {
  2125  		//当SM3时取ZA方式签名,所以不在这里做hash
  2126  		digest = tbsCertContents
  2127  	} else {
  2128  		if !hashFunc.Available() {
  2129  			return nil, x509.ErrUnsupportedAlgorithm
  2130  		}
  2131  		h := hashFunc.New()
  2132  		h.Write(tbsCertContents)
  2133  		digest = h.Sum(nil)
  2134  	}
  2135  
  2136  	var signerOpts crypto.SignerOpts
  2137  	signerOpts = hashFunc
  2138  	switch template.SignatureAlgorithm {
  2139  	case x509.SHA256WithRSAPSS, x509.SHA384WithRSAPSS, x509.SHA512WithRSAPSS:
  2140  		signerOpts = &rsa.PSSOptions{
  2141  			SaltLength: rsa.PSSSaltLengthEqualsHash,
  2142  			Hash:       hashFunc,
  2143  		}
  2144  	}
  2145  
  2146  	var signature []byte
  2147  	signature, err = key.Sign(rand, digest, signerOpts)
  2148  	if err != nil {
  2149  		return
  2150  	}
  2151  
  2152  	return asn1.Marshal(certificate{
  2153  		nil,
  2154  		c,
  2155  		signatureAlgorithm,
  2156  		asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  2157  	})
  2158  }
  2159  
  2160  type tbsCertificateRequest struct {
  2161  	Raw           asn1.RawContent
  2162  	Version       int
  2163  	Subject       asn1.RawValue
  2164  	PublicKey     publicKeyInfo
  2165  	RawAttributes []asn1.RawValue `asn1:"tag:0"`
  2166  }
  2167  
  2168  type certificateRequest struct {
  2169  	Raw                asn1.RawContent
  2170  	TBSCSR             tbsCertificateRequest
  2171  	SignatureAlgorithm pkix.AlgorithmIdentifier
  2172  	SignatureValue     asn1.BitString
  2173  }
  2174  
  2175  // newRawAttributes converts AttributeTypeAndValueSETs from a template
  2176  // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
  2177  func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
  2178  	var rawAttributes []asn1.RawValue
  2179  	b, err := asn1.Marshal(attributes)
  2180  	if err != nil {
  2181  		return nil, err
  2182  	}
  2183  	rest, err := asn1.Unmarshal(b, &rawAttributes)
  2184  	if err != nil {
  2185  		return nil, err
  2186  	}
  2187  	if len(rest) != 0 {
  2188  		return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
  2189  	}
  2190  	return rawAttributes, nil
  2191  }
  2192  
  2193  // CertificateRequest represents a PKCS #10, certificate signature request.
  2194  type CertificateRequest struct {
  2195  	Raw                      []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
  2196  	RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
  2197  	RawSubjectPublicKeyInfo  []byte // DER encoded SubjectPublicKeyInfo.
  2198  	RawSubject               []byte // DER encoded Subject.
  2199  
  2200  	Version            int
  2201  	Signature          []byte
  2202  	SignatureAlgorithm SignatureAlgorithm
  2203  
  2204  	PublicKeyAlgorithm PublicKeyAlgorithm
  2205  	PublicKey          bccrypto.PublicKey
  2206  
  2207  	Subject pkix.Name
  2208  
  2209  	// Attributes contains the CSR attributes that can parse as
  2210  	// pkix.AttributeTypeAndValueSET.
  2211  	//
  2212  	// Deprecated: use Extensions and ExtraExtensions instead for parsing and
  2213  	// generating the requestedExtensions attribute.
  2214  	Attributes []pkix.AttributeTypeAndValueSET
  2215  
  2216  	// Extensions contains all requested extensions, in raw form. When parsing
  2217  	// CSRs, this can be used to extract extensions that are not parsed by this
  2218  	// package.
  2219  	Extensions []pkix.Extension
  2220  
  2221  	// ExtraExtensions contains extensions to be copied, raw, into any CSR
  2222  	// marshaled by CreateCertificateRequest. Values override any extensions
  2223  	// that would otherwise be produced based on the other fields but are
  2224  	// overridden by any extensions specified in Attributes.
  2225  	//
  2226  	// The ExtraExtensions field is not populated by ParseCertificateRequest,
  2227  	// see Extensions instead.
  2228  	ExtraExtensions []pkix.Extension
  2229  
  2230  	// Subject Alternate Name values.
  2231  	DNSNames       []string
  2232  	EmailAddresses []string
  2233  	IPAddresses    []net.IP
  2234  	URIs           []*url.URL
  2235  }
  2236  
  2237  // CreateCertificateRequest creates a new certificate request based on a template.
  2238  // The following members of template are used: Subject, Attributes,
  2239  // SignatureAlgorithm, Extensions, DNSNames, EmailAddresses, and IPAddresses.
  2240  // The private key is the private key of the signer.
  2241  //
  2242  // The returned slice is the certificate request in DER encoding.
  2243  //
  2244  // All keys types that are implemented via crypto.Signer are supported (This
  2245  // includes *rsa.PublicKey and *ecdsa.PublicKey.)
  2246  // nolint: gocyclo
  2247  func CreateCertificateRequest(rand io.Reader,
  2248  	template *CertificateRequest, priv interface{}) (csr []byte, err error) {
  2249  	key, ok := priv.(crypto.Signer)
  2250  	if !ok {
  2251  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  2252  	}
  2253  
  2254  	var hashFunc crypto.Hash
  2255  	var sigAlgo pkix.AlgorithmIdentifier
  2256  	hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), SignatureAlgorithm(template.SignatureAlgorithm))
  2257  	if err != nil {
  2258  		return nil, err
  2259  	}
  2260  
  2261  	var publicKeyBytes []byte
  2262  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
  2263  	publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
  2264  	if err != nil {
  2265  		return nil, err
  2266  	}
  2267  
  2268  	var extensions []pkix.Extension
  2269  
  2270  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
  2271  		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  2272  		var sanBytes []byte
  2273  		sanBytes, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses)
  2274  		if err != nil {
  2275  			return nil, err
  2276  		}
  2277  
  2278  		extensions = append(extensions, pkix.Extension{
  2279  			Id:    oidExtensionSubjectAltName,
  2280  			Value: sanBytes,
  2281  		})
  2282  	}
  2283  
  2284  	extensions = append(extensions, template.ExtraExtensions...)
  2285  
  2286  	var attributes []pkix.AttributeTypeAndValueSET
  2287  	attributes = append(attributes, template.Attributes...)
  2288  
  2289  	if len(extensions) > 0 {
  2290  		// specifiedExtensions contains all the extensions that we
  2291  		// found specified via template.Attributes.
  2292  		specifiedExtensions := make(map[string]bool)
  2293  
  2294  		for _, atvSet := range template.Attributes {
  2295  			if !atvSet.Type.Equal(oidExtensionRequest) {
  2296  				continue
  2297  			}
  2298  
  2299  			for _, atvs := range atvSet.Value {
  2300  				for _, atv := range atvs {
  2301  					specifiedExtensions[atv.Type.String()] = true
  2302  				}
  2303  			}
  2304  		}
  2305  
  2306  		atvs := make([]pkix.AttributeTypeAndValue, 0, len(extensions))
  2307  		for _, e := range extensions {
  2308  			if specifiedExtensions[e.Id.String()] {
  2309  				// Attributes already contained a value for
  2310  				// this extension and it takes priority.
  2311  				continue
  2312  			}
  2313  
  2314  			atvs = append(atvs, pkix.AttributeTypeAndValue{
  2315  				// There is no place for the critical flag in a CSR.
  2316  				Type:  e.Id,
  2317  				Value: e.Value,
  2318  			})
  2319  		}
  2320  
  2321  		// Append the extensions to an existing attribute if possible.
  2322  		appended := false
  2323  		for _, atvSet := range attributes {
  2324  			if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
  2325  				continue
  2326  			}
  2327  
  2328  			atvSet.Value[0] = append(atvSet.Value[0], atvs...)
  2329  			appended = true
  2330  			break
  2331  		}
  2332  
  2333  		// Otherwise, add a new attribute for the extensions.
  2334  		if !appended {
  2335  			attributes = append(attributes, pkix.AttributeTypeAndValueSET{
  2336  				Type: oidExtensionRequest,
  2337  				Value: [][]pkix.AttributeTypeAndValue{
  2338  					atvs,
  2339  				},
  2340  			})
  2341  		}
  2342  	}
  2343  
  2344  	asn1Subject := template.RawSubject
  2345  	if len(asn1Subject) == 0 {
  2346  		asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
  2347  		if err != nil {
  2348  			return
  2349  		}
  2350  	}
  2351  
  2352  	rawAttributes, err := newRawAttributes(attributes)
  2353  	if err != nil {
  2354  		return
  2355  	}
  2356  
  2357  	tbsCSR := tbsCertificateRequest{
  2358  		Version: 0, // PKCS #10, RFC 2986
  2359  		Subject: asn1.RawValue{FullBytes: asn1Subject},
  2360  		PublicKey: publicKeyInfo{
  2361  			Algorithm: publicKeyAlgorithm,
  2362  			PublicKey: asn1.BitString{
  2363  				Bytes:     publicKeyBytes,
  2364  				BitLength: len(publicKeyBytes) * 8,
  2365  			},
  2366  		},
  2367  		RawAttributes: rawAttributes,
  2368  	}
  2369  
  2370  	tbsCSRContents, err := asn1.Marshal(tbsCSR)
  2371  	if err != nil {
  2372  		return
  2373  	}
  2374  	tbsCSR.Raw = tbsCSRContents
  2375  
  2376  	var digest []byte
  2377  	if hashFunc == crypto.Hash(bccrypto.HASH_TYPE_SM3) {
  2378  		//当SM3时取ZA方式签名,所以不在这里做hash
  2379  		digest = tbsCSRContents
  2380  	} else {
  2381  		if !hashFunc.Available() {
  2382  			return nil, x509.ErrUnsupportedAlgorithm
  2383  		}
  2384  		h := hashFunc.New()
  2385  		h.Write(tbsCSRContents)
  2386  		digest = h.Sum(nil)
  2387  	}
  2388  
  2389  	var signature []byte
  2390  	signature, err = key.Sign(rand, digest, hashFunc)
  2391  	if err != nil {
  2392  		return
  2393  	}
  2394  
  2395  	return asn1.Marshal(certificateRequest{
  2396  		TBSCSR:             tbsCSR,
  2397  		SignatureAlgorithm: sigAlgo,
  2398  		SignatureValue: asn1.BitString{
  2399  			Bytes:     signature,
  2400  			BitLength: len(signature) * 8,
  2401  		},
  2402  	})
  2403  }
  2404  
  2405  // ParseCertificateRequest parses a single certificate request from the
  2406  // given ASN.1 DER data.
  2407  func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
  2408  	var csr certificateRequest
  2409  
  2410  	rest, err := asn1.Unmarshal(asn1Data, &csr)
  2411  	if err != nil {
  2412  		return nil, err
  2413  	} else if len(rest) != 0 {
  2414  		return nil, asn1.SyntaxError{Msg: "trailing data"}
  2415  	}
  2416  
  2417  	return parseCertificateRequest(&csr)
  2418  }
  2419  
  2420  func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
  2421  	out := &CertificateRequest{
  2422  		Raw:                      in.Raw,
  2423  		RawTBSCertificateRequest: in.TBSCSR.Raw,
  2424  		RawSubjectPublicKeyInfo:  in.TBSCSR.PublicKey.Raw,
  2425  		RawSubject:               in.TBSCSR.Subject.FullBytes,
  2426  
  2427  		Signature:          in.SignatureValue.RightAlign(),
  2428  		SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
  2429  
  2430  		PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
  2431  
  2432  		Version:    in.TBSCSR.Version,
  2433  		Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
  2434  	}
  2435  
  2436  	var err error
  2437  	out.PublicKey, err = parsePublicKey(PublicKeyAlgorithm(out.PublicKeyAlgorithm), &in.TBSCSR.PublicKey)
  2438  	if err != nil {
  2439  		return nil, err
  2440  	}
  2441  
  2442  	var subject pkix.RDNSequence
  2443  	var rest []byte
  2444  	if rest, err = asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
  2445  		return nil, err
  2446  	} else if len(rest) != 0 {
  2447  		return nil, errors.New("x509: trailing data after X.509 Subject")
  2448  	}
  2449  
  2450  	out.Subject.FillFromRDNSequence(&subject)
  2451  
  2452  	if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
  2453  		return nil, err
  2454  	}
  2455  
  2456  	for _, extension := range out.Extensions {
  2457  		if extension.Id.Equal(oidExtensionSubjectAltName) {
  2458  			out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
  2459  			if err != nil {
  2460  				return nil, err
  2461  			}
  2462  		}
  2463  	}
  2464  
  2465  	return out, nil
  2466  }
  2467  
  2468  // parseRawAttributes Unmarshals RawAttributes intos AttributeTypeAndValueSETs.
  2469  func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
  2470  	var attributes []pkix.AttributeTypeAndValueSET
  2471  	for _, rawAttr := range rawAttributes {
  2472  		var attr pkix.AttributeTypeAndValueSET
  2473  		rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
  2474  		// Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
  2475  		// (i.e.: challengePassword or unstructuredName).
  2476  		if err == nil && len(rest) == 0 {
  2477  			attributes = append(attributes, attr)
  2478  		}
  2479  	}
  2480  	return attributes
  2481  }
  2482  
  2483  // parseCSRExtensions parses the attributes from a CSR and extracts any
  2484  // requested extensions.
  2485  func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
  2486  	// pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
  2487  	type pkcs10Attribute struct {
  2488  		Id     asn1.ObjectIdentifier
  2489  		Values []asn1.RawValue `asn1:"set"`
  2490  	}
  2491  
  2492  	var ret []pkix.Extension
  2493  	for _, rawAttr := range rawAttributes {
  2494  		var attr pkcs10Attribute
  2495  		if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
  2496  			// Ignore attributes that don't parse.
  2497  			continue
  2498  		}
  2499  
  2500  		if !attr.Id.Equal(oidExtensionRequest) {
  2501  			continue
  2502  		}
  2503  
  2504  		var extensions []pkix.Extension
  2505  		if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
  2506  			return nil, err
  2507  		}
  2508  		ret = append(ret, extensions...)
  2509  	}
  2510  
  2511  	return ret, nil
  2512  }
  2513  
  2514  // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
  2515  // in RFC 3280.
  2516  type pkixPublicKey struct {
  2517  	Algo      pkix.AlgorithmIdentifier
  2518  	BitString asn1.BitString
  2519  }
  2520  
  2521  // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
  2522  func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
  2523  	var publicKeyBytes []byte
  2524  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
  2525  	var err error
  2526  
  2527  	if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
  2528  		return nil, err
  2529  	}
  2530  
  2531  	pkix := pkixPublicKey{
  2532  		Algo: publicKeyAlgorithm,
  2533  		BitString: asn1.BitString{
  2534  			Bytes:     publicKeyBytes,
  2535  			BitLength: 8 * len(publicKeyBytes),
  2536  		},
  2537  	}
  2538  
  2539  	ret, _ := asn1.Marshal(pkix)
  2540  	return ret, nil
  2541  }
  2542  
  2543  // CheckSignature reports whether the signature on c is valid.
  2544  func (c *CertificateRequest) CheckSignature() error {
  2545  	return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
  2546  }
  2547  
  2548  // nolint: staticcheck
  2549  func ChainMakerCertCsrToX509CertCsr(cert *CertificateRequest) (*x509.CertificateRequest, error) {
  2550  	var pk crypto.PublicKey
  2551  	if cert.PublicKey == nil {
  2552  		pk = nil
  2553  	} else {
  2554  		pk = cert.PublicKey.ToStandardKey()
  2555  	}
  2556  	newCert := &x509.CertificateRequest{
  2557  		Raw:                      cert.Raw,
  2558  		RawTBSCertificateRequest: cert.RawTBSCertificateRequest,
  2559  		RawSubjectPublicKeyInfo:  cert.RawSubjectPublicKeyInfo,
  2560  		RawSubject:               cert.RawSubject,
  2561  		Version:                  cert.Version,
  2562  		Signature:                cert.Signature,
  2563  		SignatureAlgorithm:       x509.SignatureAlgorithm(cert.SignatureAlgorithm),
  2564  		PublicKeyAlgorithm:       x509.PublicKeyAlgorithm(cert.PublicKeyAlgorithm),
  2565  		PublicKey:                pk,
  2566  		Subject:                  cert.Subject,
  2567  		Attributes:               cert.Attributes,
  2568  		Extensions:               cert.Extensions,
  2569  		ExtraExtensions:          cert.ExtraExtensions,
  2570  		DNSNames:                 cert.DNSNames,
  2571  		EmailAddresses:           cert.EmailAddresses,
  2572  		IPAddresses:              cert.IPAddresses,
  2573  		URIs:                     cert.URIs,
  2574  	}
  2575  	return newCert, nil
  2576  }
  2577  
  2578  // nolint: staticcheck
  2579  func X509CertCsrToChainMakerCertCsr(cert *x509.CertificateRequest) (*CertificateRequest, error) {
  2580  	var pk bccrypto.PublicKey
  2581  	if cert.PublicKey != nil {
  2582  		der, err := MarshalPKIXPublicKey(cert.PublicKey)
  2583  		if err != nil {
  2584  			return nil, fmt.Errorf("fail to parse re-encode (marshal) public key in certificate: %v", err)
  2585  		}
  2586  		pk, err = asym.PublicKeyFromDER(der)
  2587  		if err != nil {
  2588  			return nil, fmt.Errorf("fail to parse re-encode (unmarshal) public key in certificate: %v", err)
  2589  		}
  2590  	}
  2591  	newCert := &CertificateRequest{
  2592  		Raw:                      cert.Raw,
  2593  		RawTBSCertificateRequest: cert.RawTBSCertificateRequest,
  2594  		RawSubjectPublicKeyInfo:  cert.RawSubjectPublicKeyInfo,
  2595  		RawSubject:               cert.RawSubject,
  2596  		Version:                  cert.Version,
  2597  		Signature:                cert.Signature,
  2598  		SignatureAlgorithm:       SignatureAlgorithm(cert.SignatureAlgorithm),
  2599  		PublicKeyAlgorithm:       PublicKeyAlgorithm(cert.PublicKeyAlgorithm),
  2600  		PublicKey:                pk,
  2601  		Subject:                  cert.Subject,
  2602  		Attributes:               cert.Attributes,
  2603  		Extensions:               cert.Extensions,
  2604  		ExtraExtensions:          cert.ExtraExtensions,
  2605  		DNSNames:                 cert.DNSNames,
  2606  		EmailAddresses:           cert.EmailAddresses,
  2607  		IPAddresses:              cert.IPAddresses,
  2608  		URIs:                     cert.URIs,
  2609  	}
  2610  	return newCert, nil
  2611  }
  2612  
  2613  func BuildCertificateChain(certs []*Certificate) []*Certificate {
  2614  	if len(certs) <= 1 {
  2615  		return certs
  2616  	}
  2617  
  2618  	caPool := NewCertPool()
  2619  	intermediatePool := NewCertPool()
  2620  	var nonCaCerts []*Certificate
  2621  	var caCerts []*Certificate
  2622  	for _, cert := range certs {
  2623  		if cert.IsCA {
  2624  			caCerts = append(caCerts, cert)
  2625  			caPool.AddCert(cert)
  2626  			if !bytes.Equal(cert.SubjectKeyId, cert.AuthorityKeyId) {
  2627  				intermediatePool.AddCert(cert)
  2628  			}
  2629  		} else {
  2630  			nonCaCerts = append(nonCaCerts, cert)
  2631  			intermediatePool.AddCert(cert)
  2632  		}
  2633  	}
  2634  
  2635  	var chain []*Certificate
  2636  	if len(nonCaCerts) <= 0 {
  2637  		for i, certCandidate := range caCerts {
  2638  			intermediateCAPool := NewCertPool()
  2639  			for j, cert := range caCerts {
  2640  				if i != j {
  2641  					intermediateCAPool.AddCert(cert)
  2642  				}
  2643  			}
  2644  			candidateChains, err := certCandidate.Verify(VerifyOptions{
  2645  				DNSName:                   "",
  2646  				Intermediates:             caPool,
  2647  				Roots:                     intermediateCAPool,
  2648  				CurrentTime:               time.Time{},
  2649  				KeyUsages:                 []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  2650  				MaxConstraintComparisions: 0,
  2651  			})
  2652  			if err != nil {
  2653  				continue
  2654  			}
  2655  			for _, candidate := range candidateChains {
  2656  				if len(candidate) > len(chain) {
  2657  					chain = candidate
  2658  				}
  2659  			}
  2660  		}
  2661  		if len(chain) > 0 {
  2662  			return chain
  2663  		}
  2664  		return nil
  2665  	}
  2666  	for _, cert := range nonCaCerts {
  2667  		candidateChains, err := cert.Verify(VerifyOptions{
  2668  			DNSName:                   "",
  2669  			Intermediates:             intermediatePool,
  2670  			Roots:                     caPool,
  2671  			CurrentTime:               time.Time{},
  2672  			KeyUsages:                 []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
  2673  			MaxConstraintComparisions: 0,
  2674  		})
  2675  		if err != nil {
  2676  			continue
  2677  		}
  2678  		candidateTmp := candidateChains[0]
  2679  		for _, candidate := range candidateChains {
  2680  			if len(candidate) > len(candidateTmp) {
  2681  				candidateTmp = candidate
  2682  			}
  2683  		}
  2684  		if len(candidateTmp) > len(chain) {
  2685  			chain = candidateTmp
  2686  		}
  2687  	}
  2688  
  2689  	if len(chain) <= 0 {
  2690  		return nil
  2691  	}
  2692  	return chain
  2693  }
  2694  
  2695  // CreateCRL .ceate crl
  2696  func CreateCRL(rand io.Reader, cert *x509.Certificate, priv interface{},
  2697  	revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
  2698  	key, ok := priv.(crypto.Signer)
  2699  	if !ok {
  2700  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  2701  	}
  2702  
  2703  	hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(
  2704  		key.Public(),
  2705  		SignatureAlgorithm(cert.SignatureAlgorithm))
  2706  	if err != nil {
  2707  		return nil, err
  2708  	}
  2709  
  2710  	// Force revocation times to UTC per RFC 5280.
  2711  	revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
  2712  	for i, rc := range revokedCerts {
  2713  		rc.RevocationTime = rc.RevocationTime.UTC()
  2714  		revokedCertsUTC[i] = rc
  2715  	}
  2716  
  2717  	tbsCertList := pkix.TBSCertificateList{
  2718  		Version:             1,
  2719  		Signature:           signatureAlgorithm,
  2720  		Issuer:              cert.Subject.ToRDNSequence(),
  2721  		ThisUpdate:          now.UTC(),
  2722  		NextUpdate:          expiry.UTC(),
  2723  		RevokedCertificates: revokedCertsUTC,
  2724  	}
  2725  
  2726  	// Authority Key Id
  2727  	if len(cert.SubjectKeyId) > 0 {
  2728  		var aki pkix.Extension
  2729  		aki.Id = oidExtensionAuthorityKeyId
  2730  		aki.Value, err = asn1.Marshal(authKeyId{Id: cert.SubjectKeyId})
  2731  		if err != nil {
  2732  			return
  2733  		}
  2734  		tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
  2735  	}
  2736  
  2737  	tbsCertListContents, err := asn1.Marshal(tbsCertList)
  2738  	if err != nil {
  2739  		return
  2740  	}
  2741  
  2742  	var digest []byte
  2743  	if hashFunc == crypto.Hash(bccrypto.HASH_TYPE_SM3) {
  2744  		//当SM3时取ZA方式签名,所以不在这里做hash
  2745  		digest = tbsCertListContents
  2746  	} else {
  2747  		if !hashFunc.Available() {
  2748  			return nil, x509.ErrUnsupportedAlgorithm
  2749  		}
  2750  		h := hashFunc.New()
  2751  		h.Write(tbsCertListContents)
  2752  		digest = h.Sum(nil)
  2753  	}
  2754  
  2755  	var signature []byte
  2756  	signature, err = key.Sign(rand, digest, hashFunc)
  2757  	if err != nil {
  2758  		return
  2759  	}
  2760  
  2761  	return asn1.Marshal(pkix.CertificateList{
  2762  		TBSCertList:        tbsCertList,
  2763  		SignatureAlgorithm: signatureAlgorithm,
  2764  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  2765  	})
  2766  
  2767  }