github.com/emmansun/gmsm@v0.29.1/smx509/x509.go (about)

     1  // Package smx509 parses X.509-encoded keys and certificates include SM2/SM3 support.
     2  //
     3  // It allows parsing and generating certificates, certificate signing
     4  // requests, certificate revocation lists, and encoded public and private keys.
     5  // It provides a certificate verifier, complete with a chain builder.
     6  //
     7  // The package targets the X.509 technical profile defined by the IETF (RFC
     8  // 2459/3280/5280), and as further restricted by the CA/Browser Forum Baseline
     9  // Requirements. There is minimal support for features outside of these
    10  // profiles, as the primary goal of the package is to provide compatibility
    11  // with the publicly trusted TLS certificate ecosystem and its policies and
    12  // constraints.
    13  //
    14  // On Windows, certificate verification is handled by system APIs, but
    15  // the package aims to apply consistent validation rules across operating
    16  // systems.
    17  //
    18  // On macOS, we did NOT support to use system root CA yet due to too many SDK internal
    19  // package's dependencies.
    20  package smx509
    21  
    22  import (
    23  	"bytes"
    24  	"crypto"
    25  	"crypto/ecdsa"
    26  	"crypto/ed25519"
    27  	"crypto/elliptic"
    28  	"crypto/rsa"
    29  	"crypto/sha1"
    30  	"crypto/x509"
    31  	"crypto/x509/pkix"
    32  	"encoding/asn1"
    33  	"encoding/pem"
    34  	"errors"
    35  	"fmt"
    36  	"io"
    37  	"math/big"
    38  	"net"
    39  	"net/url"
    40  	"time"
    41  	"unicode"
    42  
    43  	// Explicitly import these for their crypto.RegisterHash init side-effects.
    44  	// Keep these as blank imports, even if they're imported above.
    45  	_ "crypto/sha1"
    46  	_ "crypto/sha256"
    47  	_ "crypto/sha512"
    48  
    49  	"golang.org/x/crypto/cryptobyte"
    50  	cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
    51  
    52  	"github.com/emmansun/gmsm/ecdh"
    53  	"github.com/emmansun/gmsm/internal/godebug"
    54  	"github.com/emmansun/gmsm/sm2"
    55  )
    56  
    57  // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
    58  // in RFC 3280.
    59  type pkixPublicKey struct {
    60  	Algo      pkix.AlgorithmIdentifier
    61  	BitString asn1.BitString
    62  }
    63  
    64  // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
    65  // The encoded public key is a SubjectPublicKeyInfo structure
    66  // (see RFC 5280, Section 4.1).
    67  //
    68  // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
    69  // ed25519.PublicKey. More types might be supported in the future.
    70  //
    71  // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
    72  func ParsePKIXPublicKey(derBytes []byte) (any, error) {
    73  	var pki publicKeyInfo
    74  	if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
    75  		if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
    76  			return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
    77  		}
    78  		return nil, err
    79  	} else if len(rest) != 0 {
    80  		return nil, errors.New("x509: trailing data after ASN.1 of public-key")
    81  	}
    82  	return parsePublicKey(&pki)
    83  }
    84  
    85  func marshalPublicKey(pub any) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
    86  	switch pub := pub.(type) {
    87  	case *rsa.PublicKey:
    88  		publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
    89  			N: pub.N,
    90  			E: pub.E,
    91  		})
    92  		if err != nil {
    93  			return nil, pkix.AlgorithmIdentifier{}, err
    94  		}
    95  		publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
    96  		// This is a NULL parameters value which is required by
    97  		// RFC 3279, Section 2.3.1.
    98  		publicKeyAlgorithm.Parameters = asn1.NullRawValue
    99  	case *ecdsa.PublicKey:
   100  		oid, ok := oidFromNamedCurve(pub.Curve)
   101  		if !ok {
   102  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
   103  		}
   104  		if !pub.Curve.IsOnCurve(pub.X, pub.Y) {
   105  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: invalid elliptic curve public key")
   106  		}
   107  		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
   108  		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
   109  		var paramBytes []byte
   110  		paramBytes, err = asn1.Marshal(oid)
   111  		if err != nil {
   112  			return
   113  		}
   114  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
   115  	case ed25519.PublicKey:
   116  		publicKeyBytes = pub
   117  		publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
   118  	case *ecdh.PublicKey: //TODO:will add SDK ECDH public key support from golang 1.19 later.
   119  		publicKeyBytes = pub.Bytes()
   120  
   121  		oid, ok := oidFromECDHCurve(pub.Curve())
   122  		if !ok {
   123  			return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
   124  		}
   125  		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
   126  		var paramBytes []byte
   127  		paramBytes, err = asn1.Marshal(oid)
   128  		if err != nil {
   129  			return
   130  		}
   131  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
   132  	default:
   133  		return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
   134  	}
   135  
   136  	return publicKeyBytes, publicKeyAlgorithm, nil
   137  }
   138  
   139  // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
   140  // The encoded public key is a SubjectPublicKeyInfo structure
   141  // (see RFC 5280, Section 4.1).
   142  //
   143  // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
   144  // and ed25519.PublicKey. Unsupported key types result in an error.
   145  //
   146  // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
   147  func MarshalPKIXPublicKey(pub any) ([]byte, error) {
   148  	var publicKeyBytes []byte
   149  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
   150  	var err error
   151  
   152  	if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
   153  		return nil, err
   154  	}
   155  
   156  	pkix := pkixPublicKey{
   157  		Algo: publicKeyAlgorithm,
   158  		BitString: asn1.BitString{
   159  			Bytes:     publicKeyBytes,
   160  			BitLength: 8 * len(publicKeyBytes),
   161  		},
   162  	}
   163  
   164  	ret, _ := asn1.Marshal(pkix)
   165  	return ret, nil
   166  }
   167  
   168  // These structures reflect the ASN.1 structure of X.509 certificates.:
   169  
   170  type certificate struct {
   171  	TBSCertificate     tbsCertificate
   172  	SignatureAlgorithm pkix.AlgorithmIdentifier
   173  	SignatureValue     asn1.BitString
   174  }
   175  
   176  type tbsCertificate struct {
   177  	Raw                asn1.RawContent
   178  	Version            int `asn1:"optional,explicit,default:0,tag:0"`
   179  	SerialNumber       *big.Int
   180  	SignatureAlgorithm pkix.AlgorithmIdentifier
   181  	Issuer             asn1.RawValue
   182  	Validity           validity
   183  	Subject            asn1.RawValue
   184  	PublicKey          publicKeyInfo
   185  	UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
   186  	SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
   187  	Extensions         []pkix.Extension `asn1:"omitempty,optional,explicit,tag:3"`
   188  }
   189  
   190  type dsaAlgorithmParameters struct {
   191  	P, Q, G *big.Int
   192  }
   193  
   194  type validity struct {
   195  	NotBefore, NotAfter time.Time
   196  }
   197  
   198  type publicKeyInfo struct {
   199  	Raw       asn1.RawContent
   200  	Algorithm pkix.AlgorithmIdentifier
   201  	PublicKey asn1.BitString
   202  }
   203  
   204  // RFC 5280,  4.2.1.1
   205  type authKeyId struct {
   206  	Id []byte `asn1:"optional,tag:0"`
   207  }
   208  
   209  type SignatureAlgorithm = x509.SignatureAlgorithm
   210  
   211  const (
   212  	UnknownSignatureAlgorithm = x509.UnknownSignatureAlgorithm
   213  
   214  	MD2WithRSA       = x509.MD2WithRSA  // Unsupported.
   215  	MD5WithRSA       = x509.MD5WithRSA  // Only supported for signing, not verification.
   216  	SHA1WithRSA      = x509.SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
   217  	SHA256WithRSA    = x509.SHA256WithRSA
   218  	SHA384WithRSA    = x509.SHA384WithRSA
   219  	SHA512WithRSA    = x509.SHA512WithRSA
   220  	DSAWithSHA1      = x509.DSAWithSHA1   // Unsupported.
   221  	DSAWithSHA256    = x509.DSAWithSHA256 // Unsupported.
   222  	ECDSAWithSHA1    = x509.ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
   223  	ECDSAWithSHA256  = x509.ECDSAWithSHA256
   224  	ECDSAWithSHA384  = x509.ECDSAWithSHA384
   225  	ECDSAWithSHA512  = x509.ECDSAWithSHA512
   226  	SHA256WithRSAPSS = x509.SHA256WithRSAPSS
   227  	SHA384WithRSAPSS = x509.SHA384WithRSAPSS
   228  	SHA512WithRSAPSS = x509.SHA512WithRSAPSS
   229  	PureEd25519      = x509.PureEd25519
   230  
   231  	SM2WithSM3 SignatureAlgorithm = 99 // Make sure the vaule is not conflict with x509.SignatureAlgorithm
   232  )
   233  
   234  func isRSAPSS(algo SignatureAlgorithm) bool {
   235  	for _, details := range signatureAlgorithmDetails {
   236  		if details.algo == algo {
   237  			return details.isRSAPSS
   238  		}
   239  	}
   240  	return false
   241  }
   242  
   243  func hashFunc(algo SignatureAlgorithm) crypto.Hash {
   244  	for _, details := range signatureAlgorithmDetails {
   245  		if details.algo == algo {
   246  			return details.hash
   247  		}
   248  	}
   249  	return crypto.Hash(0)
   250  }
   251  
   252  type PublicKeyAlgorithm = x509.PublicKeyAlgorithm
   253  
   254  const (
   255  	UnknownPublicKeyAlgorithm = x509.UnknownPublicKeyAlgorithm
   256  
   257  	RSA     = x509.RSA
   258  	DSA     = x509.DSA // Only supported for parsing.
   259  	ECDSA   = x509.ECDSA
   260  	Ed25519 = x509.Ed25519
   261  )
   262  
   263  // OIDs for signature algorithms
   264  //
   265  //	pkcs-1 OBJECT IDENTIFIER ::= {
   266  //		iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
   267  //
   268  // RFC 3279 2.2.1 RSA Signature Algorithms
   269  //
   270  //	md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
   271  //
   272  //	md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
   273  //
   274  //	sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
   275  //
   276  //	dsaWithSha1 OBJECT IDENTIFIER ::= {
   277  //		iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
   278  //
   279  // RFC 3279 2.2.3 ECDSA Signature Algorithm
   280  //
   281  //	ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
   282  //		iso(1) member-body(2) us(840) ansi-x962(10045)
   283  //		signatures(4) ecdsa-with-SHA1(1)}
   284  //
   285  // RFC 4055 5 PKCS #1 Version 1.5
   286  //
   287  //	sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
   288  //
   289  //	sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
   290  //
   291  //	sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
   292  //
   293  // RFC 5758 3.1 DSA Signature Algorithms
   294  //
   295  //	dsaWithSha256 OBJECT IDENTIFIER ::= {
   296  //		joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
   297  //		csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
   298  //
   299  // RFC 5758 3.2 ECDSA Signature Algorithm
   300  //
   301  //	ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   302  //		us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
   303  //
   304  //	ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   305  //		us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
   306  //
   307  //	ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   308  //		us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
   309  //
   310  // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
   311  //
   312  //	id-Ed25519   OBJECT IDENTIFIER ::= { 1 3 101 112 }
   313  var (
   314  	oidSignatureMD2WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
   315  	oidSignatureMD5WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
   316  	oidSignatureSHA1WithRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
   317  	oidSignatureSHA256WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
   318  	oidSignatureSHA384WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
   319  	oidSignatureSHA512WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
   320  	oidSignatureRSAPSS          = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
   321  	oidSignatureDSAWithSHA1     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
   322  	oidSignatureDSAWithSHA256   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
   323  	oidSignatureECDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
   324  	oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
   325  	oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
   326  	oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
   327  	oidSignatureEd25519         = asn1.ObjectIdentifier{1, 3, 101, 112}
   328  
   329  	oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
   330  	oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
   331  	oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
   332  
   333  	oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
   334  
   335  	// oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
   336  	// but it's specified by ISO. Microsoft's makecert.exe has been known
   337  	// to produce certificates with this OID.
   338  	oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
   339  
   340  	// GB/T 33560-2017 信息安全技术 密码应用标识规范
   341  	// 附录A(规范性附录)商用密码领域中的相关OID定义
   342  	//
   343  	// http://gmssl.org/docs/oid.html
   344  	oidSignatureSM2WithSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 501}
   345  	//oidSignatureSM2WithSHA1   = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 502}
   346  	//oidSignatureSM2WithSHA256 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 503}
   347  )
   348  
   349  var signatureAlgorithmDetails = []struct {
   350  	algo       SignatureAlgorithm
   351  	name       string
   352  	oid        asn1.ObjectIdentifier
   353  	params     asn1.RawValue
   354  	pubKeyAlgo PublicKeyAlgorithm
   355  	hash       crypto.Hash
   356  	isRSAPSS   bool
   357  }{
   358  	{MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, asn1.NullRawValue, RSA, crypto.Hash(0) /* no value for MD2 */, false},
   359  	{MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, asn1.NullRawValue, RSA, crypto.MD5, false},
   360  	{SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, asn1.NullRawValue, RSA, crypto.SHA1, false},
   361  	{SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, asn1.NullRawValue, RSA, crypto.SHA1, false},
   362  	{SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, asn1.NullRawValue, RSA, crypto.SHA256, false},
   363  	{SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, asn1.NullRawValue, RSA, crypto.SHA384, false},
   364  	{SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, asn1.NullRawValue, RSA, crypto.SHA512, false},
   365  	{SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, pssParametersSHA256, RSA, crypto.SHA256, true},
   366  	{SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, pssParametersSHA384, RSA, crypto.SHA384, true},
   367  	{SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, pssParametersSHA512, RSA, crypto.SHA512, true},
   368  	{DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, emptyRawValue, DSA, crypto.SHA1, false},
   369  	{DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, emptyRawValue, DSA, crypto.SHA256, false},
   370  	{ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, emptyRawValue, ECDSA, crypto.SHA1, false},
   371  	{ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, emptyRawValue, ECDSA, crypto.SHA256, false},
   372  	{ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, emptyRawValue, ECDSA, crypto.SHA384, false},
   373  	{ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, emptyRawValue, ECDSA, crypto.SHA512, false},
   374  	{PureEd25519, "Ed25519", oidSignatureEd25519, emptyRawValue, Ed25519, crypto.Hash(0) /* no pre-hashing */, false},
   375  	{SM2WithSM3, "SM2-SM3", oidSignatureSM2WithSM3, emptyRawValue, ECDSA, crypto.Hash(0) /* no pre-hashing */, false},
   376  }
   377  
   378  var emptyRawValue = asn1.RawValue{}
   379  
   380  // DER encoded RSA PSS parameters for the
   381  // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
   382  // The parameters contain the following values:
   383  //   - hashAlgorithm contains the associated hash identifier with NULL parameters
   384  //   - maskGenAlgorithm always contains the default mgf1SHA1 identifier
   385  //   - saltLength contains the length of the associated hash
   386  //   - trailerField always contains the default trailerFieldBC value
   387  var (
   388  	pssParametersSHA256 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 162, 3, 2, 1, 32}}
   389  	pssParametersSHA384 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 162, 3, 2, 1, 48}}
   390  	pssParametersSHA512 = asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 162, 3, 2, 1, 64}}
   391  )
   392  
   393  // pssParameters reflects the parameters in an AlgorithmIdentifier that
   394  // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
   395  type pssParameters struct {
   396  	// The following three fields are not marked as
   397  	// optional because the default values specify SHA-1,
   398  	// which is no longer suitable for use in signatures.
   399  	Hash         pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
   400  	MGF          pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
   401  	SaltLength   int                      `asn1:"explicit,tag:2"`
   402  	TrailerField int                      `asn1:"optional,explicit,tag:3,default:1"`
   403  }
   404  
   405  func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
   406  	if ai.Algorithm.Equal(oidSignatureEd25519) {
   407  		// RFC 8410, Section 3
   408  		// > For all of the OIDs, the parameters MUST be absent.
   409  		if len(ai.Parameters.FullBytes) != 0 {
   410  			return UnknownSignatureAlgorithm
   411  		}
   412  	}
   413  
   414  	if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
   415  		for _, details := range signatureAlgorithmDetails {
   416  			if ai.Algorithm.Equal(details.oid) {
   417  				return details.algo
   418  			}
   419  		}
   420  		return UnknownSignatureAlgorithm
   421  	}
   422  
   423  	// RSA PSS is special because it encodes important parameters
   424  	// in the Parameters.
   425  
   426  	var params pssParameters
   427  	if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, &params); err != nil {
   428  		return UnknownSignatureAlgorithm
   429  	}
   430  
   431  	var mgf1HashFunc pkix.AlgorithmIdentifier
   432  	if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
   433  		return UnknownSignatureAlgorithm
   434  	}
   435  
   436  	// PSS is greatly overburdened with options. This code forces them into
   437  	// three buckets by requiring that the MGF1 hash function always match the
   438  	// message hash function (as recommended in RFC 3447, Section 8.1), that the
   439  	// salt length matches the hash length, and that the trailer field has the
   440  	// default value.
   441  	if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
   442  		!params.MGF.Algorithm.Equal(oidMGF1) ||
   443  		!mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
   444  		(len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
   445  		params.TrailerField != 1 {
   446  		return UnknownSignatureAlgorithm
   447  	}
   448  
   449  	switch {
   450  	case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
   451  		return SHA256WithRSAPSS
   452  	case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
   453  		return SHA384WithRSAPSS
   454  	case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
   455  		return SHA512WithRSAPSS
   456  	}
   457  
   458  	return UnknownSignatureAlgorithm
   459  }
   460  
   461  var (
   462  	// RFC 3279, 2.3 Public Key Algorithms
   463  	//
   464  	//	pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   465  	//		rsadsi(113549) pkcs(1) 1 }
   466  	//
   467  	// rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
   468  	//
   469  	//	id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   470  	//		x9-57(10040) x9cm(4) 1 }
   471  	oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
   472  	oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
   473  	// RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
   474  	//
   475  	//	id-ecPublicKey OBJECT IDENTIFIER ::= {
   476  	//		iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
   477  	oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
   478  	// GB/T 33560-2017 信息安全技术 密码应用标识规范
   479  	// 附录A(规范性附录)商用密码领域中的相关OID定义
   480  	oidPublicKeySM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301}
   481  	// RFC 8410, Section 3
   482  	//
   483  	//	id-X25519    OBJECT IDENTIFIER ::= { 1 3 101 110 }
   484  	//	id-Ed25519   OBJECT IDENTIFIER ::= { 1 3 101 112 }
   485  	oidPublicKeyX25519  = asn1.ObjectIdentifier{1, 3, 101, 110}
   486  	oidPublicKeyEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
   487  )
   488  
   489  // getPublicKeyAlgorithmFromOID returns the exposed PublicKeyAlgorithm
   490  // identifier for public key types supported in certificates and CSRs. Marshal
   491  // and Parse functions may support a different set of public key types.
   492  func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
   493  	switch {
   494  	case oid.Equal(oidPublicKeyRSA):
   495  		return RSA
   496  	case oid.Equal(oidPublicKeyDSA):
   497  		return DSA
   498  	case oid.Equal(oidPublicKeyECDSA):
   499  		return ECDSA
   500  	case oid.Equal(oidPublicKeySM2):
   501  		return ECDSA		
   502  	case oid.Equal(oidPublicKeyEd25519):
   503  		return Ed25519
   504  	}
   505  	return UnknownPublicKeyAlgorithm
   506  }
   507  
   508  // RFC 5480, 2.1.1.1. Named Curve
   509  var (
   510  	oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
   511  	oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
   512  	oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
   513  	oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
   514  
   515  	// GB/T 33560-2017 信息安全技术 密码应用标识规范
   516  	// 附录A(规范性附录)商用密码领域中的相关OID定义
   517  	//
   518  	// http://gmssl.org/docs/oid.html
   519  	oidNamedCurveP256SM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301}
   520  )
   521  
   522  func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
   523  	switch {
   524  	case oid.Equal(oidNamedCurveP224):
   525  		return elliptic.P224()
   526  	case oid.Equal(oidNamedCurveP256):
   527  		return elliptic.P256()
   528  	case oid.Equal(oidNamedCurveP384):
   529  		return elliptic.P384()
   530  	case oid.Equal(oidNamedCurveP521):
   531  		return elliptic.P521()
   532  	case oid.Equal(oidNamedCurveP256SM2):
   533  		return sm2.P256()
   534  	}
   535  	return nil
   536  }
   537  
   538  func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
   539  	switch curve {
   540  	case elliptic.P224():
   541  		return oidNamedCurveP224, true
   542  	case elliptic.P256():
   543  		return oidNamedCurveP256, true
   544  	case elliptic.P384():
   545  		return oidNamedCurveP384, true
   546  	case elliptic.P521():
   547  		return oidNamedCurveP521, true
   548  	case sm2.P256():
   549  		return oidNamedCurveP256SM2, true
   550  	}
   551  
   552  	return nil, false
   553  }
   554  
   555  func oidFromECDHCurve(curve ecdh.Curve) (asn1.ObjectIdentifier, bool) {
   556  	switch curve {
   557  	case ecdh.P256():
   558  		return oidNamedCurveP256SM2, true
   559  	}
   560  
   561  	return nil, false
   562  }
   563  
   564  // KeyUsage represents the set of actions that are valid for a given key. It's
   565  // a bitmap of the KeyUsage* constants.
   566  type KeyUsage = x509.KeyUsage
   567  
   568  const (
   569  	KeyUsageDigitalSignature  = x509.KeyUsageDigitalSignature
   570  	KeyUsageContentCommitment = x509.KeyUsageContentCommitment
   571  	KeyUsageKeyEncipherment   = x509.KeyUsageKeyEncipherment
   572  	KeyUsageDataEncipherment  = x509.KeyUsageDataEncipherment
   573  	KeyUsageKeyAgreement      = x509.KeyUsageKeyAgreement
   574  	KeyUsageCertSign          = x509.KeyUsageCertSign
   575  	KeyUsageCRLSign           = x509.KeyUsageCRLSign
   576  	KeyUsageEncipherOnly      = x509.KeyUsageEncipherOnly
   577  	KeyUsageDecipherOnly      = x509.KeyUsageDecipherOnly
   578  )
   579  
   580  // RFC 5280, 4.2.1.12  Extended Key Usage
   581  //
   582  //	anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
   583  //
   584  //	id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
   585  //
   586  //	id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
   587  //	id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
   588  //	id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
   589  //	id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
   590  //	id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
   591  //	id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
   592  var (
   593  	oidExtKeyUsageAny                            = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
   594  	oidExtKeyUsageServerAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
   595  	oidExtKeyUsageClientAuth                     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
   596  	oidExtKeyUsageCodeSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
   597  	oidExtKeyUsageEmailProtection                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
   598  	oidExtKeyUsageIPSECEndSystem                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
   599  	oidExtKeyUsageIPSECTunnel                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
   600  	oidExtKeyUsageIPSECUser                      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
   601  	oidExtKeyUsageTimeStamping                   = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
   602  	oidExtKeyUsageOCSPSigning                    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
   603  	oidExtKeyUsageMicrosoftServerGatedCrypto     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
   604  	oidExtKeyUsageNetscapeServerGatedCrypto      = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
   605  	oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
   606  	oidExtKeyUsageMicrosoftKernelCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
   607  )
   608  
   609  // ExtKeyUsage represents an extended set of actions that are valid for a given key.
   610  // Each of the ExtKeyUsage* constants define a unique action.
   611  type ExtKeyUsage = x509.ExtKeyUsage
   612  
   613  const (
   614  	ExtKeyUsageAny                            = x509.ExtKeyUsageAny
   615  	ExtKeyUsageServerAuth                     = x509.ExtKeyUsageServerAuth
   616  	ExtKeyUsageClientAuth                     = x509.ExtKeyUsageClientAuth
   617  	ExtKeyUsageCodeSigning                    = x509.ExtKeyUsageCodeSigning
   618  	ExtKeyUsageEmailProtection                = x509.ExtKeyUsageEmailProtection
   619  	ExtKeyUsageIPSECEndSystem                 = x509.ExtKeyUsageIPSECEndSystem
   620  	ExtKeyUsageIPSECTunnel                    = x509.ExtKeyUsageIPSECTunnel
   621  	ExtKeyUsageIPSECUser                      = x509.ExtKeyUsageIPSECUser
   622  	ExtKeyUsageTimeStamping                   = x509.ExtKeyUsageTimeStamping
   623  	ExtKeyUsageOCSPSigning                    = x509.ExtKeyUsageOCSPSigning
   624  	ExtKeyUsageMicrosoftServerGatedCrypto     = x509.ExtKeyUsageMicrosoftServerGatedCrypto
   625  	ExtKeyUsageNetscapeServerGatedCrypto      = x509.ExtKeyUsageNetscapeServerGatedCrypto
   626  	ExtKeyUsageMicrosoftCommercialCodeSigning = x509.ExtKeyUsageMicrosoftCommercialCodeSigning
   627  	ExtKeyUsageMicrosoftKernelCodeSigning     = x509.ExtKeyUsageMicrosoftKernelCodeSigning
   628  )
   629  
   630  // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
   631  var extKeyUsageOIDs = []struct {
   632  	extKeyUsage ExtKeyUsage
   633  	oid         asn1.ObjectIdentifier
   634  }{
   635  	{ExtKeyUsageAny, oidExtKeyUsageAny},
   636  	{ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
   637  	{ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
   638  	{ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
   639  	{ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
   640  	{ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
   641  	{ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
   642  	{ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
   643  	{ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
   644  	{ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
   645  	{ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
   646  	{ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
   647  	{ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
   648  	{ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
   649  }
   650  
   651  func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
   652  	for _, pair := range extKeyUsageOIDs {
   653  		if oid.Equal(pair.oid) {
   654  			return pair.extKeyUsage, true
   655  		}
   656  	}
   657  	return
   658  }
   659  
   660  func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
   661  	for _, pair := range extKeyUsageOIDs {
   662  		if eku == pair.extKeyUsage {
   663  			return pair.oid, true
   664  		}
   665  	}
   666  	return
   667  }
   668  
   669  // debugAllowSHA1 allows SHA-1 signatures. See issue 41682.
   670  var debugAllowSHA1 = godebug.Get("x509sha1") == "1"
   671  
   672  // A Certificate represents an X.509 certificate.
   673  type Certificate x509.Certificate
   674  
   675  func (c *Certificate) asX509() *x509.Certificate {
   676  	return (*x509.Certificate)(c)
   677  }
   678  
   679  // ToX509 convert smx509.Certificate reference to x509.Certificate
   680  func (c *Certificate) ToX509() *x509.Certificate {
   681  	return c.asX509()
   682  }
   683  
   684  func (c *Certificate) Equal(other *Certificate) bool {
   685  	if c == nil || other == nil {
   686  		return c == other
   687  	}
   688  	return bytes.Equal(c.Raw, other.Raw)
   689  }
   690  
   691  func (c *Certificate) hasSANExtension() bool {
   692  	return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
   693  }
   694  
   695  // CheckSignatureFrom verifies that the signature on c is a valid signature from parent.
   696  //
   697  // This is a low-level API that performs very limited checks, and not a full
   698  // path verifier. Most users should use [Certificate.Verify] instead.
   699  func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
   700  	// RFC 5280, 4.2.1.9:
   701  	// "If the basic constraints extension is not present in a version 3
   702  	// certificate, or the extension is present but the cA boolean is not
   703  	// asserted, then the certified public key MUST NOT be used to verify
   704  	// certificate signatures."
   705  	if parent.Version == 3 && !parent.BasicConstraintsValid ||
   706  		parent.BasicConstraintsValid && !parent.IsCA {
   707  		return x509.ConstraintViolationError{}
   708  	}
   709  
   710  	if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
   711  		return x509.ConstraintViolationError{}
   712  	}
   713  
   714  	if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
   715  		return x509.ErrUnsupportedAlgorithm
   716  	}
   717  
   718  	// TODO(agl): don't ignore the path length constraint.
   719  
   720  	return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature, parent.PublicKey, debugAllowSHA1)
   721  }
   722  
   723  // CheckSignature verifies that signature is a valid signature over signed from
   724  // c's public key.
   725  //
   726  // This is a low-level API that performs no validity checks on the certificate.
   727  //
   728  // [MD5WithRSA] signatures are rejected, while [SHA1WithRSA] and [ECDSAWithSHA1]
   729  // signatures are currently accepted.
   730  func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
   731  	return checkSignature(algo, signed, signature, c.PublicKey, true)
   732  }
   733  
   734  func (c *Certificate) hasNameConstraints() bool {
   735  	return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
   736  }
   737  
   738  func (c *Certificate) getSANExtension() []byte {
   739  	for _, e := range c.Extensions {
   740  		if e.Id.Equal(oidExtensionSubjectAltName) {
   741  			return e.Value
   742  		}
   743  	}
   744  	return nil
   745  }
   746  
   747  func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {
   748  	return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
   749  }
   750  
   751  // checkSignature verifies that signature is a valid signature over signed from
   752  // a crypto.PublicKey.
   753  func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error) {
   754  	var hashType crypto.Hash
   755  	var pubKeyAlgo PublicKeyAlgorithm
   756  
   757  	isSM2 := (algo == SM2WithSM3)
   758  	for _, details := range signatureAlgorithmDetails {
   759  		if details.algo == algo {
   760  			hashType = details.hash
   761  			pubKeyAlgo = details.pubKeyAlgo
   762  			break
   763  		}
   764  	}
   765  
   766  	switch hashType {
   767  	case crypto.Hash(0):
   768  		if !isSM2 && pubKeyAlgo != Ed25519 {
   769  			return x509.ErrUnsupportedAlgorithm
   770  		}
   771  	case crypto.MD5:
   772  		return x509.InsecureAlgorithmError(algo)
   773  	case crypto.SHA1:
   774  		// SHA-1 signatures are mostly disabled. See go.dev/issue/41682.
   775  		if !allowSHA1 {
   776  			return x509.InsecureAlgorithmError(algo)
   777  		}
   778  		fallthrough
   779  	default:
   780  		if !hashType.Available() {
   781  			return x509.ErrUnsupportedAlgorithm
   782  		}
   783  		h := hashType.New()
   784  		h.Write(signed)
   785  		signed = h.Sum(nil)
   786  	}
   787  
   788  	switch pub := publicKey.(type) {
   789  	case *rsa.PublicKey:
   790  		if pubKeyAlgo != RSA {
   791  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
   792  		}
   793  		if isRSAPSS(algo) {
   794  			return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
   795  		} else {
   796  			return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
   797  		}
   798  	case *ecdsa.PublicKey:
   799  		if pubKeyAlgo != ECDSA {
   800  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
   801  		}
   802  		if isSM2 {
   803  			if !sm2.VerifyASN1WithSM2(pub, nil, signed, signature) {
   804  				return errors.New("x509: SM2 verification failure")
   805  			}
   806  		} else if !ecdsa.VerifyASN1(pub, signed, signature) {
   807  			return errors.New("x509: ECDSA verification failure")
   808  		}
   809  		return
   810  	case ed25519.PublicKey:
   811  		if pubKeyAlgo != Ed25519 {
   812  			return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
   813  		}
   814  		if !ed25519.Verify(pub, signed, signature) {
   815  			return errors.New("x509: Ed25519 verification failure")
   816  		}
   817  		return
   818  	}
   819  	return x509.ErrUnsupportedAlgorithm
   820  }
   821  
   822  // CheckCRLSignature checks that the signature in crl is from c.
   823  func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
   824  	algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
   825  	return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
   826  }
   827  
   828  type basicConstraints struct {
   829  	IsCA       bool `asn1:"optional"`
   830  	MaxPathLen int  `asn1:"optional,default:-1"`
   831  }
   832  
   833  // RFC 5280 4.2.1.4
   834  type policyInformation struct {
   835  	Policy asn1.ObjectIdentifier
   836  	// policyQualifiers omitted
   837  }
   838  
   839  const (
   840  	nameTypeEmail = 1
   841  	nameTypeDNS   = 2
   842  	nameTypeURI   = 6
   843  	nameTypeIP    = 7
   844  )
   845  
   846  // RFC 5280, 4.2.2.1
   847  type authorityInfoAccess struct {
   848  	Method   asn1.ObjectIdentifier
   849  	Location asn1.RawValue
   850  }
   851  
   852  // RFC 5280, 4.2.1.14
   853  type distributionPoint struct {
   854  	DistributionPoint distributionPointName `asn1:"optional,tag:0"`
   855  	Reason            asn1.BitString        `asn1:"optional,tag:1"`
   856  	CRLIssuer         asn1.RawValue         `asn1:"optional,tag:2"`
   857  }
   858  
   859  type distributionPointName struct {
   860  	FullName     []asn1.RawValue  `asn1:"optional,tag:0"`
   861  	RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
   862  }
   863  
   864  func reverseBitsInAByte(in byte) byte {
   865  	b1 := in>>4 | in<<4
   866  	b2 := b1>>2&0x33 | b1<<2&0xcc
   867  	b3 := b2>>1&0x55 | b2<<1&0xaa
   868  	return b3
   869  }
   870  
   871  // asn1BitLength returns the bit-length of bitString by considering the
   872  // most-significant bit in a byte to be the "first" bit. This convention
   873  // matches ASN.1, but differs from almost everything else.
   874  func asn1BitLength(bitString []byte) int {
   875  	bitLen := len(bitString) * 8
   876  
   877  	for i := range bitString {
   878  		b := bitString[len(bitString)-i-1]
   879  
   880  		for bit := uint(0); bit < 8; bit++ {
   881  			if (b>>bit)&1 == 1 {
   882  				return bitLen
   883  			}
   884  			bitLen--
   885  		}
   886  	}
   887  
   888  	return 0
   889  }
   890  
   891  var (
   892  	oidExtensionSubjectKeyId          = []int{2, 5, 29, 14}
   893  	oidExtensionKeyUsage              = []int{2, 5, 29, 15}
   894  	oidExtensionExtendedKeyUsage      = []int{2, 5, 29, 37}
   895  	oidExtensionAuthorityKeyId        = []int{2, 5, 29, 35}
   896  	oidExtensionBasicConstraints      = []int{2, 5, 29, 19}
   897  	oidExtensionSubjectAltName        = []int{2, 5, 29, 17}
   898  	oidExtensionCertificatePolicies   = []int{2, 5, 29, 32}
   899  	oidExtensionNameConstraints       = []int{2, 5, 29, 30}
   900  	oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
   901  	oidExtensionAuthorityInfoAccess   = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
   902  	oidExtensionCRLNumber             = []int{2, 5, 29, 20}
   903  	oidExtensionReasonCode            = []int{2, 5, 29, 21}
   904  )
   905  
   906  var (
   907  	oidAuthorityInfoAccessOcsp    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
   908  	oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
   909  )
   910  
   911  // oidNotInExtensions reports whether an extension with the given oid exists in
   912  // extensions.
   913  func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
   914  	for _, e := range extensions {
   915  		if e.Id.Equal(oid) {
   916  			return true
   917  		}
   918  	}
   919  	return false
   920  }
   921  
   922  // marshalSANs marshals a list of addresses into a the contents of an X.509
   923  // SubjectAlternativeName extension.
   924  func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
   925  	var rawValues []asn1.RawValue
   926  	for _, name := range dnsNames {
   927  		if err := isIA5String(name); err != nil {
   928  			return nil, err
   929  		}
   930  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
   931  	}
   932  	for _, email := range emailAddresses {
   933  		if err := isIA5String(email); err != nil {
   934  			return nil, err
   935  		}
   936  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
   937  	}
   938  	for _, rawIP := range ipAddresses {
   939  		// If possible, we always want to encode IPv4 addresses in 4 bytes.
   940  		ip := rawIP.To4()
   941  		if ip == nil {
   942  			ip = rawIP
   943  		}
   944  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
   945  	}
   946  	for _, uri := range uris {
   947  		uriStr := uri.String()
   948  		if err := isIA5String(uriStr); err != nil {
   949  			return nil, err
   950  		}
   951  		rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
   952  	}
   953  	return asn1.Marshal(rawValues)
   954  }
   955  
   956  func isIA5String(s string) error {
   957  	for _, r := range s {
   958  		// Per RFC5280 "IA5String is limited to the set of ASCII characters"
   959  		if r >= unicode.MaxASCII {
   960  			return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
   961  		}
   962  	}
   963  
   964  	return nil
   965  }
   966  
   967  func buildCertExtensions(template *x509.Certificate, subjectIsEmpty bool, authorityKeyId, subjectKeyId []byte) (ret []pkix.Extension, err error) {
   968  	ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
   969  	n := 0
   970  
   971  	if template.KeyUsage != 0 &&
   972  		!oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
   973  		ret[n], err = marshalKeyUsage(template.KeyUsage)
   974  		if err != nil {
   975  			return nil, err
   976  		}
   977  		n++
   978  	}
   979  
   980  	if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
   981  		!oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
   982  		ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
   983  		if err != nil {
   984  			return nil, err
   985  		}
   986  		n++
   987  	}
   988  
   989  	if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
   990  		ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
   991  		if err != nil {
   992  			return nil, err
   993  		}
   994  		n++
   995  	}
   996  
   997  	if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
   998  		ret[n].Id = oidExtensionSubjectKeyId
   999  		ret[n].Value, err = asn1.Marshal(subjectKeyId)
  1000  		if err != nil {
  1001  			return
  1002  		}
  1003  		n++
  1004  	}
  1005  
  1006  	if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
  1007  		ret[n].Id = oidExtensionAuthorityKeyId
  1008  		ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
  1009  		if err != nil {
  1010  			return
  1011  		}
  1012  		n++
  1013  	}
  1014  
  1015  	if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
  1016  		!oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
  1017  		ret[n].Id = oidExtensionAuthorityInfoAccess
  1018  		var aiaValues []authorityInfoAccess
  1019  		for _, name := range template.OCSPServer {
  1020  			aiaValues = append(aiaValues, authorityInfoAccess{
  1021  				Method:   oidAuthorityInfoAccessOcsp,
  1022  				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1023  			})
  1024  		}
  1025  		for _, name := range template.IssuingCertificateURL {
  1026  			aiaValues = append(aiaValues, authorityInfoAccess{
  1027  				Method:   oidAuthorityInfoAccessIssuers,
  1028  				Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
  1029  			})
  1030  		}
  1031  		ret[n].Value, err = asn1.Marshal(aiaValues)
  1032  		if err != nil {
  1033  			return
  1034  		}
  1035  		n++
  1036  	}
  1037  
  1038  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
  1039  		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1040  		ret[n].Id = oidExtensionSubjectAltName
  1041  		// From RFC 5280, Section 4.2.1.6:
  1042  		// “If the subject field contains an empty sequence ... then
  1043  		// subjectAltName extension ... is marked as critical”
  1044  		ret[n].Critical = subjectIsEmpty
  1045  		ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
  1046  		if err != nil {
  1047  			return
  1048  		}
  1049  		n++
  1050  	}
  1051  
  1052  	if len(template.PolicyIdentifiers) > 0 &&
  1053  		!oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
  1054  		ret[n], err = marshalCertificatePolicies(template.PolicyIdentifiers)
  1055  		if err != nil {
  1056  			return nil, err
  1057  		}
  1058  		n++
  1059  	}
  1060  
  1061  	if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
  1062  		len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
  1063  		len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
  1064  		len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
  1065  		!oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
  1066  		ret[n].Id = oidExtensionNameConstraints
  1067  		ret[n].Critical = template.PermittedDNSDomainsCritical
  1068  
  1069  		ipAndMask := func(ipNet *net.IPNet) []byte {
  1070  			maskedIP := ipNet.IP.Mask(ipNet.Mask)
  1071  			ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
  1072  			ipAndMask = append(ipAndMask, maskedIP...)
  1073  			ipAndMask = append(ipAndMask, ipNet.Mask...)
  1074  			return ipAndMask
  1075  		}
  1076  
  1077  		serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
  1078  			var b cryptobyte.Builder
  1079  
  1080  			for _, name := range dns {
  1081  				if err = isIA5String(name); err != nil {
  1082  					return nil, err
  1083  				}
  1084  
  1085  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1086  					b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
  1087  						b.AddBytes([]byte(name))
  1088  					})
  1089  				})
  1090  			}
  1091  
  1092  			for _, ipNet := range ips {
  1093  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1094  					b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
  1095  						b.AddBytes(ipAndMask(ipNet))
  1096  					})
  1097  				})
  1098  			}
  1099  
  1100  			for _, email := range emails {
  1101  				if err = isIA5String(email); err != nil {
  1102  					return nil, err
  1103  				}
  1104  
  1105  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1106  					b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
  1107  						b.AddBytes([]byte(email))
  1108  					})
  1109  				})
  1110  			}
  1111  
  1112  			for _, uriDomain := range uriDomains {
  1113  				if err = isIA5String(uriDomain); err != nil {
  1114  					return nil, err
  1115  				}
  1116  
  1117  				b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1118  					b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
  1119  						b.AddBytes([]byte(uriDomain))
  1120  					})
  1121  				})
  1122  			}
  1123  
  1124  			return b.Bytes()
  1125  		}
  1126  
  1127  		permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
  1128  		if err != nil {
  1129  			return nil, err
  1130  		}
  1131  
  1132  		excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
  1133  		if err != nil {
  1134  			return nil, err
  1135  		}
  1136  
  1137  		var b cryptobyte.Builder
  1138  		b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
  1139  			if len(permitted) > 0 {
  1140  				b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
  1141  					b.AddBytes(permitted)
  1142  				})
  1143  			}
  1144  
  1145  			if len(excluded) > 0 {
  1146  				b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
  1147  					b.AddBytes(excluded)
  1148  				})
  1149  			}
  1150  		})
  1151  
  1152  		ret[n].Value, err = b.Bytes()
  1153  		if err != nil {
  1154  			return nil, err
  1155  		}
  1156  		n++
  1157  	}
  1158  
  1159  	if len(template.CRLDistributionPoints) > 0 &&
  1160  		!oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
  1161  		ret[n].Id = oidExtensionCRLDistributionPoints
  1162  
  1163  		var crlDp []distributionPoint
  1164  		for _, name := range template.CRLDistributionPoints {
  1165  			dp := distributionPoint{
  1166  				DistributionPoint: distributionPointName{
  1167  					FullName: []asn1.RawValue{
  1168  						{Tag: 6, Class: 2, Bytes: []byte(name)},
  1169  					},
  1170  				},
  1171  			}
  1172  			crlDp = append(crlDp, dp)
  1173  		}
  1174  
  1175  		ret[n].Value, err = asn1.Marshal(crlDp)
  1176  		if err != nil {
  1177  			return
  1178  		}
  1179  		n++
  1180  	}
  1181  
  1182  	// Adding another extension here? Remember to update the maximum number
  1183  	// of elements in the make() at the top of the function and the list of
  1184  	// template fields used in CreateCertificate documentation.
  1185  
  1186  	return append(ret[:n], template.ExtraExtensions...), nil
  1187  }
  1188  
  1189  func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
  1190  	ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
  1191  
  1192  	var a [2]byte
  1193  	a[0] = reverseBitsInAByte(byte(ku))
  1194  	a[1] = reverseBitsInAByte(byte(ku >> 8))
  1195  
  1196  	l := 1
  1197  	if a[1] != 0 {
  1198  		l = 2
  1199  	}
  1200  
  1201  	bitString := a[:l]
  1202  	var err error
  1203  	ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
  1204  	return ext, err
  1205  }
  1206  
  1207  func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
  1208  	ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
  1209  
  1210  	oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
  1211  	for i, u := range extUsages {
  1212  		if oid, ok := oidFromExtKeyUsage(u); ok {
  1213  			oids[i] = oid
  1214  		} else {
  1215  			return ext, errors.New("x509: unknown extended key usage")
  1216  		}
  1217  	}
  1218  
  1219  	copy(oids[len(extUsages):], unknownUsages)
  1220  
  1221  	var err error
  1222  	ext.Value, err = asn1.Marshal(oids)
  1223  	return ext, err
  1224  }
  1225  
  1226  func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
  1227  	ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
  1228  	// Leaving MaxPathLen as zero indicates that no maximum path
  1229  	// length is desired, unless MaxPathLenZero is set. A value of
  1230  	// -1 causes encoding/asn1 to omit the value as desired.
  1231  	if maxPathLen == 0 && !maxPathLenZero {
  1232  		maxPathLen = -1
  1233  	}
  1234  	var err error
  1235  	ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
  1236  	return ext, err
  1237  }
  1238  
  1239  func marshalCertificatePolicies(policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
  1240  	ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
  1241  	policies := make([]policyInformation, len(policyIdentifiers))
  1242  	for i, policy := range policyIdentifiers {
  1243  		policies[i].Policy = policy
  1244  	}
  1245  	var err error
  1246  	ext.Value, err = asn1.Marshal(policies)
  1247  	return ext, err
  1248  }
  1249  
  1250  func buildCSRExtensions(template *x509.CertificateRequest) ([]pkix.Extension, error) {
  1251  	var ret []pkix.Extension
  1252  
  1253  	if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
  1254  		!oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
  1255  		sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
  1256  		if err != nil {
  1257  			return nil, err
  1258  		}
  1259  
  1260  		ret = append(ret, pkix.Extension{
  1261  			Id:    oidExtensionSubjectAltName,
  1262  			Value: sanBytes,
  1263  		})
  1264  	}
  1265  
  1266  	return append(ret, template.ExtraExtensions...), nil
  1267  }
  1268  
  1269  func subjectBytes(cert *x509.Certificate) ([]byte, error) {
  1270  	if len(cert.RawSubject) > 0 {
  1271  		return cert.RawSubject, nil
  1272  	}
  1273  
  1274  	return asn1.Marshal(cert.Subject.ToRDNSequence())
  1275  }
  1276  
  1277  // signingParamsForKey returns the signature algorithm and its Algorithm
  1278  // Identifier to use for signing, based on the key type. If sigAlgo is not zero
  1279  // then it overrides the default.
  1280  func signingParamsForKey(key crypto.Signer, sigAlgo SignatureAlgorithm) (SignatureAlgorithm, pkix.AlgorithmIdentifier, error) {
  1281  	var ai pkix.AlgorithmIdentifier
  1282  	var pubType PublicKeyAlgorithm
  1283  	var defaultAlgo SignatureAlgorithm
  1284  
  1285  	switch pub := key.Public().(type) {
  1286  	case *rsa.PublicKey:
  1287  		pubType = RSA
  1288  		defaultAlgo = SHA256WithRSA
  1289  
  1290  	case *ecdsa.PublicKey:
  1291  		pubType = ECDSA
  1292  		switch pub.Curve {
  1293  		case elliptic.P224(), elliptic.P256():
  1294  			defaultAlgo = ECDSAWithSHA256
  1295  		case elliptic.P384():
  1296  			defaultAlgo = ECDSAWithSHA384
  1297  		case elliptic.P521():
  1298  			defaultAlgo = ECDSAWithSHA512
  1299  		case sm2.P256():
  1300  			defaultAlgo = SM2WithSM3
  1301  		default:
  1302  			return 0, ai, errors.New("x509: unsupported elliptic curve")
  1303  		}
  1304  
  1305  	case ed25519.PublicKey:
  1306  		pubType = Ed25519
  1307  		defaultAlgo = PureEd25519
  1308  
  1309  	default:
  1310  		return 0, ai, errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
  1311  	}
  1312  
  1313  	if sigAlgo == 0 {
  1314  		sigAlgo = defaultAlgo
  1315  	}
  1316  
  1317  	for _, details := range signatureAlgorithmDetails {
  1318  		if details.algo == sigAlgo {
  1319  			if details.pubKeyAlgo != pubType || (sigAlgo != defaultAlgo && defaultAlgo == SM2WithSM3) {
  1320  				return 0, ai, errors.New("x509: requested SignatureAlgorithm does not match private key type")
  1321  			}
  1322  			if details.hash == crypto.MD5 {
  1323  				return 0, ai, errors.New("x509: signing with MD5 is not supported")
  1324  			}
  1325  
  1326  			return sigAlgo, pkix.AlgorithmIdentifier{
  1327  				Algorithm:  details.oid,
  1328  				Parameters: details.params,
  1329  			}, nil
  1330  		}
  1331  	}
  1332  
  1333  	return 0, ai, errors.New("x509: unknown SignatureAlgorithm")
  1334  }
  1335  
  1336  func signTBS(tbs []byte, key crypto.Signer, sigAlg SignatureAlgorithm, rand io.Reader) ([]byte, error) {
  1337  	signed := tbs
  1338  	hashFunc := hashFunc(sigAlg)
  1339  	if hashFunc != 0 {
  1340  		h := hashFunc.New()
  1341  		h.Write(signed)
  1342  		signed = h.Sum(nil)
  1343  	}
  1344  
  1345  	var signerOpts crypto.SignerOpts = hashFunc
  1346  	if isRSAPSS(sigAlg) {
  1347  		signerOpts = &rsa.PSSOptions{
  1348  			SaltLength: rsa.PSSSaltLengthEqualsHash,
  1349  			Hash:       hashFunc,
  1350  		}
  1351  	} else if sigAlg == SM2WithSM3 {
  1352  		signerOpts = sm2.DefaultSM2SignerOpts
  1353  	}
  1354  
  1355  	signature, err := key.Sign(rand, signed, signerOpts)
  1356  	if err != nil {
  1357  		return nil, err
  1358  	}
  1359  
  1360  	// Check the signature to ensure the crypto.Signer behaved correctly.
  1361  	if err := checkSignature(sigAlg, tbs, signature, key.Public(), true); err != nil {
  1362  		return nil, fmt.Errorf("x509: signature returned by signer is invalid: %w", err)
  1363  	}
  1364  
  1365  	return signature, nil
  1366  }
  1367  
  1368  // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
  1369  // just an empty SEQUENCE.
  1370  var emptyASN1Subject = []byte{0x30, 0}
  1371  
  1372  // CreateCertificate creates a new X.509 v3 certificate based on a template.
  1373  // The following members of template are currently used:
  1374  //
  1375  //   - AuthorityKeyId
  1376  //   - BasicConstraintsValid
  1377  //   - CRLDistributionPoints
  1378  //   - DNSNames
  1379  //   - EmailAddresses
  1380  //   - ExcludedDNSDomains
  1381  //   - ExcludedEmailAddresses
  1382  //   - ExcludedIPRanges
  1383  //   - ExcludedURIDomains
  1384  //   - ExtKeyUsage
  1385  //   - ExtraExtensions
  1386  //   - IPAddresses
  1387  //   - IsCA
  1388  //   - IssuingCertificateURL
  1389  //   - KeyUsage
  1390  //   - MaxPathLen
  1391  //   - MaxPathLenZero
  1392  //   - NotAfter
  1393  //   - NotBefore
  1394  //   - OCSPServer
  1395  //   - PermittedDNSDomains
  1396  //   - PermittedDNSDomainsCritical
  1397  //   - PermittedEmailAddresses
  1398  //   - PermittedIPRanges
  1399  //   - PermittedURIDomains
  1400  //   - PolicyIdentifiers
  1401  //   - SerialNumber
  1402  //   - SignatureAlgorithm
  1403  //   - Subject
  1404  //   - SubjectKeyId
  1405  //   - URIs
  1406  //   - UnknownExtKeyUsage
  1407  //
  1408  // The certificate is signed by parent. If parent is equal to template then the
  1409  // certificate is self-signed, both parent and template should be *x509.Certificate or
  1410  // *smx509.Certificate type. The parameter pub is the public key of the certificate to
  1411  // be generated and priv is the private key of the signer.
  1412  //
  1413  // The returned slice is the certificate in DER encoding.
  1414  //
  1415  // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
  1416  // ed25519.PublicKey. pub must be a supported key type, and priv must be a
  1417  // crypto.Signer with a supported public key.
  1418  //
  1419  // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
  1420  // unless the resulting certificate is self-signed. Otherwise the value from
  1421  // template will be used.
  1422  //
  1423  // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
  1424  // will be generated from the hash of the public key.
  1425  func CreateCertificate(rand io.Reader, template, parent, pub, priv any) ([]byte, error) {
  1426  	realTemplate, err := toCertificate(template)
  1427  	if err != nil {
  1428  		return nil, fmt.Errorf("x509: unsupported template parameter type: %T", template)
  1429  	}
  1430  
  1431  	realParent, err := toCertificate(parent)
  1432  	if err != nil {
  1433  		return nil, fmt.Errorf("x509: unsupported parent parameter type: %T", parent)
  1434  	}
  1435  
  1436  	key, ok := priv.(crypto.Signer)
  1437  	if !ok {
  1438  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1439  	}
  1440  
  1441  	if realTemplate.SerialNumber == nil {
  1442  		return nil, errors.New("x509: no SerialNumber given")
  1443  	}
  1444  
  1445  	// RFC 5280 Section 4.1.2.2: serial number must positive
  1446  
  1447  	// We _should_ also restrict serials to <= 20 octets, but it turns out a lot of people
  1448  	// get this wrong, in part because the encoding can itself alter the length of the
  1449  	// serial. For now we accept these non-conformant serials.
  1450  	if realTemplate.SerialNumber.Sign() == -1 {
  1451  		return nil, errors.New("x509: serial number must be positive")
  1452  	}
  1453  
  1454  	if realTemplate.BasicConstraintsValid && !realTemplate.IsCA && realTemplate.MaxPathLen != -1 && (realTemplate.MaxPathLen != 0 || realTemplate.MaxPathLenZero) {
  1455  		return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
  1456  	}
  1457  
  1458  	signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, realTemplate.SignatureAlgorithm)
  1459  	if err != nil {
  1460  		return nil, err
  1461  	}
  1462  
  1463  	publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
  1464  	if err != nil {
  1465  		return nil, err
  1466  	}
  1467  
  1468  	if getPublicKeyAlgorithmFromOID(publicKeyAlgorithm.Algorithm) == UnknownPublicKeyAlgorithm {
  1469  		return nil, fmt.Errorf("x509: unsupported public key type: %T", pub)
  1470  	}
  1471  
  1472  	asn1Issuer, err := subjectBytes(realParent)
  1473  	if err != nil {
  1474  		return nil, err
  1475  	}
  1476  
  1477  	asn1Subject, err := subjectBytes(realTemplate)
  1478  	if err != nil {
  1479  		return nil, err
  1480  	}
  1481  
  1482  	authorityKeyId := realTemplate.AuthorityKeyId
  1483  	if !bytes.Equal(asn1Issuer, asn1Subject) && len(realParent.SubjectKeyId) > 0 {
  1484  		authorityKeyId = realParent.SubjectKeyId
  1485  	}
  1486  
  1487  	subjectKeyId := realTemplate.SubjectKeyId
  1488  	if len(subjectKeyId) == 0 && realTemplate.IsCA {
  1489  		// SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
  1490  		//   (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
  1491  		//   value of the BIT STRING subjectPublicKey (excluding the tag,
  1492  		//   length, and number of unused bits).
  1493  		h := sha1.Sum(publicKeyBytes)
  1494  		subjectKeyId = h[:]
  1495  	}
  1496  
  1497  	// Check that the signer's public key matches the private key, if available.
  1498  	type privateKey interface {
  1499  		Equal(crypto.PublicKey) bool
  1500  	}
  1501  
  1502  	if privPub, ok := key.Public().(privateKey); !ok {
  1503  		return nil, errors.New("x509: internal error: supported public key does not implement Equal")
  1504  	} else if realParent.PublicKey != nil && !privPub.Equal(realParent.PublicKey) {
  1505  		return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
  1506  	}
  1507  
  1508  	extensions, err := buildCertExtensions(realTemplate, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
  1509  	if err != nil {
  1510  		return nil, err
  1511  	}
  1512  
  1513  	encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
  1514  	c := tbsCertificate{
  1515  		Version:            2,
  1516  		SerialNumber:       realTemplate.SerialNumber,
  1517  		SignatureAlgorithm: algorithmIdentifier,
  1518  		Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
  1519  		Validity:           validity{realTemplate.NotBefore.UTC(), realTemplate.NotAfter.UTC()},
  1520  		Subject:            asn1.RawValue{FullBytes: asn1Subject},
  1521  		PublicKey:          publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
  1522  		Extensions:         extensions,
  1523  	}
  1524  
  1525  	tbsCertContents, err := asn1.Marshal(c)
  1526  	if err != nil {
  1527  		return nil, err
  1528  	}
  1529  	c.Raw = tbsCertContents
  1530  
  1531  	signature, err := signTBS(tbsCertContents, key, signatureAlgorithm, rand)
  1532  	if err != nil {
  1533  		return nil, err
  1534  	}
  1535  	return asn1.Marshal(certificate{
  1536  		TBSCertificate:     c,
  1537  		SignatureAlgorithm: algorithmIdentifier,
  1538  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1539  	})
  1540  }
  1541  
  1542  func toCertificate(in any) (*x509.Certificate, error) {
  1543  	switch c := in.(type) {
  1544  	case *x509.Certificate:
  1545  		return c, nil
  1546  	case *Certificate:
  1547  		return c.asX509(), nil
  1548  	default:
  1549  		return nil, fmt.Errorf("unsupported certificate of type %T", in)
  1550  	}
  1551  }
  1552  
  1553  // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
  1554  // encoded CRLs will appear where they should be DER encoded, so this function
  1555  // will transparently handle PEM encoding as long as there isn't any leading
  1556  // garbage.
  1557  func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
  1558  	return x509.ParseCRL(crlBytes)
  1559  }
  1560  
  1561  // ParseDERCRL parses a DER encoded CRL from the given bytes.
  1562  func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
  1563  	return x509.ParseDERCRL(derBytes)
  1564  }
  1565  
  1566  // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
  1567  // contains the given list of revoked certificates.
  1568  //
  1569  // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
  1570  // To generate a standards compliant CRL, use CreateRevocationList instead.
  1571  func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
  1572  	key, ok := priv.(crypto.Signer)
  1573  	if !ok {
  1574  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1575  	}
  1576  
  1577  	signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, 0)
  1578  	if err != nil {
  1579  		return nil, err
  1580  	}
  1581  
  1582  	// Force revocation times to UTC per RFC 5280.
  1583  	revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
  1584  	for i, rc := range revokedCerts {
  1585  		rc.RevocationTime = rc.RevocationTime.UTC()
  1586  		revokedCertsUTC[i] = rc
  1587  	}
  1588  
  1589  	tbsCertList := pkix.TBSCertificateList{
  1590  		Version:             1,
  1591  		Signature:           algorithmIdentifier,
  1592  		Issuer:              c.Subject.ToRDNSequence(),
  1593  		ThisUpdate:          now.UTC(),
  1594  		NextUpdate:          expiry.UTC(),
  1595  		RevokedCertificates: revokedCertsUTC,
  1596  	}
  1597  
  1598  	// Authority Key Id
  1599  	if len(c.SubjectKeyId) > 0 {
  1600  		var aki pkix.Extension
  1601  		aki.Id = oidExtensionAuthorityKeyId
  1602  		aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
  1603  		if err != nil {
  1604  			return nil, err
  1605  		}
  1606  		tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
  1607  	}
  1608  
  1609  	tbsCertListContents, err := asn1.Marshal(tbsCertList)
  1610  	if err != nil {
  1611  		return nil, err
  1612  	}
  1613  
  1614  	tbsCertList.Raw = tbsCertListContents
  1615  	signature, err := signTBS(tbsCertListContents, key, signatureAlgorithm, rand)
  1616  	if err != nil {
  1617  		return nil, err
  1618  	}
  1619  
  1620  	return asn1.Marshal(pkix.CertificateList{
  1621  		TBSCertList:        tbsCertList,
  1622  		SignatureAlgorithm: algorithmIdentifier,
  1623  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1624  	})
  1625  }
  1626  
  1627  // CertificateRequest represents a PKCS #10, certificate signature request.
  1628  type CertificateRequest x509.CertificateRequest
  1629  
  1630  func (c *CertificateRequest) asX509() *x509.CertificateRequest {
  1631  	return (*x509.CertificateRequest)(c)
  1632  }
  1633  
  1634  // ToX509 convert smx509.CertificateRequest reference to x509.CertificateRequest
  1635  func (c *CertificateRequest) ToX509() *x509.CertificateRequest {
  1636  	return c.asX509()
  1637  }
  1638  
  1639  // These structures reflect the ASN.1 structure of X.509 certificate
  1640  // signature requests (see RFC 2986):
  1641  
  1642  type tbsCertificateRequest struct {
  1643  	Raw           asn1.RawContent
  1644  	Version       int
  1645  	Subject       asn1.RawValue
  1646  	PublicKey     publicKeyInfo
  1647  	RawAttributes []asn1.RawValue `asn1:"tag:0"`
  1648  }
  1649  
  1650  type certificateRequest struct {
  1651  	Raw                asn1.RawContent
  1652  	TBSCSR             tbsCertificateRequest
  1653  	SignatureAlgorithm pkix.AlgorithmIdentifier
  1654  	SignatureValue     asn1.BitString
  1655  }
  1656  
  1657  // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
  1658  // extensions in a CSR.
  1659  var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
  1660  
  1661  // newRawAttributes converts AttributeTypeAndValueSETs from a template
  1662  // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
  1663  func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
  1664  	var rawAttributes []asn1.RawValue
  1665  	b, err := asn1.Marshal(attributes)
  1666  	if err != nil {
  1667  		return nil, err
  1668  	}
  1669  	rest, err := asn1.Unmarshal(b, &rawAttributes)
  1670  	if err != nil {
  1671  		return nil, err
  1672  	}
  1673  	if len(rest) != 0 {
  1674  		return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
  1675  	}
  1676  	return rawAttributes, nil
  1677  }
  1678  
  1679  // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
  1680  func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
  1681  	var attributes []pkix.AttributeTypeAndValueSET
  1682  	for _, rawAttr := range rawAttributes {
  1683  		var attr pkix.AttributeTypeAndValueSET
  1684  		rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
  1685  		// Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
  1686  		// (i.e.: challengePassword or unstructuredName).
  1687  		if err == nil && len(rest) == 0 {
  1688  			attributes = append(attributes, attr)
  1689  		}
  1690  	}
  1691  	return attributes
  1692  }
  1693  
  1694  // parseCSRExtensions parses the attributes from a CSR and extracts any
  1695  // requested extensions.
  1696  func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
  1697  	// pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
  1698  	type pkcs10Attribute struct {
  1699  		Id     asn1.ObjectIdentifier
  1700  		Values []asn1.RawValue `asn1:"set"`
  1701  	}
  1702  
  1703  	var ret []pkix.Extension
  1704  	requestedExts := make(map[string]bool)
  1705  	for _, rawAttr := range rawAttributes {
  1706  		var attr pkcs10Attribute
  1707  		if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
  1708  			// Ignore attributes that don't parse.
  1709  			continue
  1710  		}
  1711  
  1712  		if !attr.Id.Equal(oidExtensionRequest) {
  1713  			continue
  1714  		}
  1715  
  1716  		var extensions []pkix.Extension
  1717  		if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
  1718  			return nil, err
  1719  		}
  1720  
  1721  		for _, ext := range extensions {
  1722  			oidStr := ext.Id.String()
  1723  			if requestedExts[oidStr] {
  1724  				return nil, errors.New("x509: certificate request contains duplicate requested extensions")
  1725  			}
  1726  			requestedExts[oidStr] = true
  1727  		}
  1728  		ret = append(ret, extensions...)
  1729  	}
  1730  
  1731  	return ret, nil
  1732  }
  1733  
  1734  // CreateCertificateRequest creates a new certificate request based on a
  1735  // template. The following members of template are used:
  1736  //
  1737  //   - SignatureAlgorithm
  1738  //   - Subject
  1739  //   - DNSNames
  1740  //   - EmailAddresses
  1741  //   - IPAddresses
  1742  //   - URIs
  1743  //   - ExtraExtensions
  1744  //   - Attributes (deprecated)
  1745  //
  1746  // priv is the private key to sign the CSR with, and the corresponding public
  1747  // key will be included in the CSR. It must implement crypto.Signer and its
  1748  // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
  1749  // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
  1750  // ed25519.PrivateKey satisfies this.)
  1751  //
  1752  // The returned slice is the certificate request in DER encoding.
  1753  func CreateCertificateRequest(rand io.Reader, template *x509.CertificateRequest, priv any) (csr []byte, err error) {
  1754  	key, ok := priv.(crypto.Signer)
  1755  	if !ok {
  1756  		return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
  1757  	}
  1758  
  1759  	signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(key, template.SignatureAlgorithm)
  1760  	if err != nil {
  1761  		return nil, err
  1762  	}
  1763  
  1764  	var publicKeyBytes []byte
  1765  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
  1766  	publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
  1767  	if err != nil {
  1768  		return nil, err
  1769  	}
  1770  
  1771  	extensions, err := buildCSRExtensions(template)
  1772  	if err != nil {
  1773  		return nil, err
  1774  	}
  1775  
  1776  	// Make a copy of template.Attributes because we may alter it below.
  1777  	attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
  1778  	for _, attr := range template.Attributes {
  1779  		values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
  1780  		copy(values, attr.Value)
  1781  		attributes = append(attributes, pkix.AttributeTypeAndValueSET{
  1782  			Type:  attr.Type,
  1783  			Value: values,
  1784  		})
  1785  	}
  1786  
  1787  	extensionsAppended := false
  1788  	if len(extensions) > 0 {
  1789  		// Append the extensions to an existing attribute if possible.
  1790  		for _, atvSet := range attributes {
  1791  			if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
  1792  				continue
  1793  			}
  1794  
  1795  			// specifiedExtensions contains all the extensions that we
  1796  			// found specified via template.Attributes.
  1797  			specifiedExtensions := make(map[string]bool)
  1798  
  1799  			for _, atvs := range atvSet.Value {
  1800  				for _, atv := range atvs {
  1801  					specifiedExtensions[atv.Type.String()] = true
  1802  				}
  1803  			}
  1804  
  1805  			newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
  1806  			newValue = append(newValue, atvSet.Value[0]...)
  1807  
  1808  			for _, e := range extensions {
  1809  				if specifiedExtensions[e.Id.String()] {
  1810  					// Attributes already contained a value for
  1811  					// this extension and it takes priority.
  1812  					continue
  1813  				}
  1814  
  1815  				newValue = append(newValue, pkix.AttributeTypeAndValue{
  1816  					// There is no place for the critical
  1817  					// flag in an AttributeTypeAndValue.
  1818  					Type:  e.Id,
  1819  					Value: e.Value,
  1820  				})
  1821  			}
  1822  
  1823  			atvSet.Value[0] = newValue
  1824  			extensionsAppended = true
  1825  			break
  1826  		}
  1827  	}
  1828  
  1829  	rawAttributes, err := newRawAttributes(attributes)
  1830  	if err != nil {
  1831  		return nil, err
  1832  	}
  1833  
  1834  	// If not included in attributes, add a new attribute for the
  1835  	// extensions.
  1836  	if len(extensions) > 0 && !extensionsAppended {
  1837  		attr := struct {
  1838  			Type  asn1.ObjectIdentifier
  1839  			Value [][]pkix.Extension `asn1:"set"`
  1840  		}{
  1841  			Type:  oidExtensionRequest,
  1842  			Value: [][]pkix.Extension{extensions},
  1843  		}
  1844  
  1845  		b, err := asn1.Marshal(attr)
  1846  		if err != nil {
  1847  			return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
  1848  		}
  1849  
  1850  		var rawValue asn1.RawValue
  1851  		if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
  1852  			return nil, err
  1853  		}
  1854  
  1855  		rawAttributes = append(rawAttributes, rawValue)
  1856  	}
  1857  
  1858  	asn1Subject := template.RawSubject
  1859  	if len(asn1Subject) == 0 {
  1860  		asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
  1861  		if err != nil {
  1862  			return nil, err
  1863  		}
  1864  	}
  1865  
  1866  	tbsCSR := tbsCertificateRequest{
  1867  		Version: 0, // PKCS #10, RFC 2986
  1868  		Subject: asn1.RawValue{FullBytes: asn1Subject},
  1869  		PublicKey: publicKeyInfo{
  1870  			Algorithm: publicKeyAlgorithm,
  1871  			PublicKey: asn1.BitString{
  1872  				Bytes:     publicKeyBytes,
  1873  				BitLength: len(publicKeyBytes) * 8,
  1874  			},
  1875  		},
  1876  		RawAttributes: rawAttributes,
  1877  	}
  1878  
  1879  	tbsCSRContents, err := asn1.Marshal(tbsCSR)
  1880  	if err != nil {
  1881  		return nil, err
  1882  	}
  1883  	tbsCSR.Raw = tbsCSRContents
  1884  
  1885  	signature, err := signTBS(tbsCSRContents, key, signatureAlgorithm, rand)
  1886  	if err != nil {
  1887  		return nil, err
  1888  	}
  1889  
  1890  	return asn1.Marshal(certificateRequest{
  1891  		TBSCSR:             tbsCSR,
  1892  		SignatureAlgorithm: algorithmIdentifier,
  1893  		SignatureValue: asn1.BitString{
  1894  			Bytes:     signature,
  1895  			BitLength: len(signature) * 8,
  1896  		},
  1897  	})
  1898  }
  1899  
  1900  // ParseCertificateRequest parses a single certificate request from the
  1901  // given ASN.1 DER data.
  1902  func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
  1903  	var csr certificateRequest
  1904  
  1905  	rest, err := asn1.Unmarshal(asn1Data, &csr)
  1906  	if err != nil {
  1907  		return nil, err
  1908  	} else if len(rest) != 0 {
  1909  		return nil, asn1.SyntaxError{Msg: "trailing data"}
  1910  	}
  1911  
  1912  	return parseCertificateRequest(&csr)
  1913  }
  1914  
  1915  // ParseCertificateRequestPEM parses a single certificate request from the
  1916  // given PEM data.
  1917  func ParseCertificateRequestPEM(data []byte) (*CertificateRequest, error) {
  1918  	block, _ := pem.Decode(data)
  1919  	if block == nil {
  1920  		return nil, errors.New("failed to decode PEM block containing CSR")
  1921  	}
  1922  	return ParseCertificateRequest(block.Bytes)
  1923  }
  1924  
  1925  func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
  1926  	out := &CertificateRequest{
  1927  		Raw:                      in.Raw,
  1928  		RawTBSCertificateRequest: in.TBSCSR.Raw,
  1929  		RawSubjectPublicKeyInfo:  in.TBSCSR.PublicKey.Raw,
  1930  		RawSubject:               in.TBSCSR.Subject.FullBytes,
  1931  
  1932  		Signature:          in.SignatureValue.RightAlign(),
  1933  		SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
  1934  
  1935  		PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
  1936  
  1937  		Version:    in.TBSCSR.Version,
  1938  		Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
  1939  	}
  1940  
  1941  	var err error
  1942  	if out.PublicKeyAlgorithm != UnknownPublicKeyAlgorithm {
  1943  		out.PublicKey, err = parsePublicKey(&in.TBSCSR.PublicKey)
  1944  		if err != nil {
  1945  			return nil, err
  1946  		}
  1947  	}
  1948  
  1949  	var subject pkix.RDNSequence
  1950  	if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
  1951  		return nil, err
  1952  	} else if len(rest) != 0 {
  1953  		return nil, errors.New("x509: trailing data after X.509 Subject")
  1954  	}
  1955  
  1956  	out.Subject.FillFromRDNSequence(&subject)
  1957  
  1958  	if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
  1959  		return nil, err
  1960  	}
  1961  
  1962  	for _, extension := range out.Extensions {
  1963  		switch {
  1964  		case extension.Id.Equal(oidExtensionSubjectAltName):
  1965  			out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
  1966  			if err != nil {
  1967  				return nil, err
  1968  			}
  1969  		}
  1970  	}
  1971  
  1972  	return out, nil
  1973  }
  1974  
  1975  // CheckSignature reports whether the signature on c is valid.
  1976  func (c *CertificateRequest) CheckSignature() error {
  1977  	return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey, true)
  1978  }
  1979  
  1980  // These structures reflect the ASN.1 structure of X.509 CRLs better than
  1981  // the existing crypto/x509/pkix variants do. These mirror the existing
  1982  // certificate structs in this file.
  1983  //
  1984  // Notably, we include issuer as an asn1.RawValue, mirroring the behavior of
  1985  // tbsCertificate and allowing raw (unparsed) subjects to be passed cleanly.
  1986  type certificateList struct {
  1987  	TBSCertList        tbsCertificateList
  1988  	SignatureAlgorithm pkix.AlgorithmIdentifier
  1989  	SignatureValue     asn1.BitString
  1990  }
  1991  
  1992  type tbsCertificateList struct {
  1993  	Raw                 asn1.RawContent
  1994  	Version             int `asn1:"optional,default:0"`
  1995  	Signature           pkix.AlgorithmIdentifier
  1996  	Issuer              asn1.RawValue
  1997  	ThisUpdate          time.Time
  1998  	NextUpdate          time.Time                 `asn1:"optional"`
  1999  	RevokedCertificates []pkix.RevokedCertificate `asn1:"optional"`
  2000  	Extensions          []pkix.Extension          `asn1:"tag:0,optional,explicit"`
  2001  }
  2002  
  2003  // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
  2004  // according to RFC 5280, based on template.
  2005  //
  2006  // The CRL is signed by priv which should be the private key associated with
  2007  // the public key in the issuer certificate.
  2008  //
  2009  // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
  2010  // order to use it as a CRL issuer.
  2011  //
  2012  // The issuer distinguished name CRL field and authority key identifier
  2013  // extension are populated using the issuer certificate. issuer must have
  2014  // SubjectKeyId set.
  2015  func CreateRevocationList(rand io.Reader, template *x509.RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
  2016  	if template == nil {
  2017  		return nil, errors.New("x509: template can not be nil")
  2018  	}
  2019  	if issuer == nil {
  2020  		return nil, errors.New("x509: issuer can not be nil")
  2021  	}
  2022  	if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
  2023  		return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
  2024  	}
  2025  	if len(issuer.SubjectKeyId) == 0 {
  2026  		return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
  2027  	}
  2028  	if template.NextUpdate.Before(template.ThisUpdate) {
  2029  		return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
  2030  	}
  2031  	if template.Number == nil {
  2032  		return nil, errors.New("x509: template contains nil Number field")
  2033  	}
  2034  
  2035  	signatureAlgorithm, algorithmIdentifier, err := signingParamsForKey(priv, template.SignatureAlgorithm)
  2036  	if err != nil {
  2037  		return nil, err
  2038  	}
  2039  
  2040  	var revokedCerts []pkix.RevokedCertificate
  2041  	revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
  2042  	for i, rc := range template.RevokedCertificates {
  2043  		rc.RevocationTime = rc.RevocationTime.UTC()
  2044  		revokedCerts[i] = rc
  2045  	}
  2046  	/*
  2047  		// Only process the deprecated RevokedCertificates field if it is populated
  2048  		// and the new RevokedCertificateEntries field is not populated.
  2049  		if len(template.RevokedCertificates) > 0 && len(template.RevokedCertificateEntries) == 0 {
  2050  			// Force revocation times to UTC per RFC 5280.
  2051  			revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
  2052  			for i, rc := range template.RevokedCertificates {
  2053  				rc.RevocationTime = rc.RevocationTime.UTC()
  2054  				revokedCerts[i] = rc
  2055  			}
  2056  		} else {
  2057  			// Convert the ReasonCode field to a proper extension, and force revocation
  2058  			// times to UTC per RFC 5280.
  2059  			revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificateEntries))
  2060  			for i, rce := range template.RevokedCertificateEntries {
  2061  				if rce.SerialNumber == nil {
  2062  					return nil, errors.New("x509: template contains entry with nil SerialNumber field")
  2063  				}
  2064  				if rce.RevocationTime.IsZero() {
  2065  					return nil, errors.New("x509: template contains entry with zero RevocationTime field")
  2066  				}
  2067  
  2068  				rc := pkix.RevokedCertificate{
  2069  					SerialNumber:   rce.SerialNumber,
  2070  					RevocationTime: rce.RevocationTime.UTC(),
  2071  				}
  2072  
  2073  				// Copy over any extra extensions, except for a Reason Code extension,
  2074  				// because we'll synthesize that ourselves to ensure it is correct.
  2075  				exts := make([]pkix.Extension, 0, len(rce.ExtraExtensions))
  2076  				for _, ext := range rce.ExtraExtensions {
  2077  					if ext.Id.Equal(oidExtensionReasonCode) {
  2078  						return nil, errors.New("x509: template contains entry with ReasonCode ExtraExtension; use ReasonCode field instead")
  2079  					}
  2080  					exts = append(exts, ext)
  2081  				}
  2082  
  2083  				// Only add a reasonCode extension if the reason is non-zero, as per
  2084  				// RFC 5280 Section 5.3.1.
  2085  				if rce.ReasonCode != 0 {
  2086  					reasonBytes, err := asn1.Marshal(asn1.Enumerated(rce.ReasonCode))
  2087  					if err != nil {
  2088  						return nil, err
  2089  					}
  2090  
  2091  					exts = append(exts, pkix.Extension{
  2092  						Id:    oidExtensionReasonCode,
  2093  						Value: reasonBytes,
  2094  					})
  2095  				}
  2096  
  2097  				if len(exts) > 0 {
  2098  					rc.Extensions = exts
  2099  				}
  2100  				revokedCerts[i] = rc
  2101  			}
  2102  		}
  2103  	*/
  2104  
  2105  	aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
  2106  	if err != nil {
  2107  		return nil, err
  2108  	}
  2109  	if numBytes := template.Number.Bytes(); len(numBytes) > 20 || (len(numBytes) == 20 && numBytes[0]&0x80 != 0) {
  2110  		return nil, errors.New("x509: CRL number exceeds 20 octets")
  2111  	}
  2112  	crlNum, err := asn1.Marshal(template.Number)
  2113  	if err != nil {
  2114  		return nil, err
  2115  	}
  2116  
  2117  	// Correctly use the issuer's subject sequence if one is specified.
  2118  	issuerSubject, err := subjectBytes(issuer.asX509())
  2119  	if err != nil {
  2120  		return nil, err
  2121  	}
  2122  
  2123  	tbsCertList := tbsCertificateList{
  2124  		Version:    1, // v2
  2125  		Signature:  algorithmIdentifier,
  2126  		Issuer:     asn1.RawValue{FullBytes: issuerSubject},
  2127  		ThisUpdate: template.ThisUpdate.UTC(),
  2128  		NextUpdate: template.NextUpdate.UTC(),
  2129  		Extensions: []pkix.Extension{
  2130  			{
  2131  				Id:    oidExtensionAuthorityKeyId,
  2132  				Value: aki,
  2133  			},
  2134  			{
  2135  				Id:    oidExtensionCRLNumber,
  2136  				Value: crlNum,
  2137  			},
  2138  		},
  2139  	}
  2140  	if len(revokedCerts) > 0 {
  2141  		tbsCertList.RevokedCertificates = revokedCerts
  2142  	}
  2143  
  2144  	if len(template.ExtraExtensions) > 0 {
  2145  		tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
  2146  	}
  2147  
  2148  	tbsCertListContents, err := asn1.Marshal(tbsCertList)
  2149  	if err != nil {
  2150  		return nil, err
  2151  	}
  2152  
  2153  	// Optimization to only marshal this struct once, when signing and
  2154  	// then embedding in certificateList below.
  2155  	tbsCertList.Raw = tbsCertListContents
  2156  
  2157  	signature, err := signTBS(tbsCertListContents, priv, signatureAlgorithm, rand)
  2158  	if err != nil {
  2159  		return nil, err
  2160  	}
  2161  
  2162  	return asn1.Marshal(certificateList{
  2163  		TBSCertList:        tbsCertList,
  2164  		SignatureAlgorithm: algorithmIdentifier,
  2165  		SignatureValue:     asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  2166  	})
  2167  }