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