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.
5 // Package x509 parses X.509-encoded keys and certificates.
35 "golang.org/x/crypto/cryptobyte"
36 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
39 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
41 type pkixPublicKey struct {
42 Algo pkix.AlgorithmIdentifier
43 BitString asn1.BitString
46 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
47 // The encoded public key is a SubjectPublicKeyInfo structure
48 // (see RFC 5280, Section 4.1).
50 // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
51 // ed25519.PublicKey. More types might be supported in the future.
53 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
54 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
56 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
57 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
58 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
61 } else if len(rest) != 0 {
62 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
64 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
65 if algo == UnknownPublicKeyAlgorithm {
66 return nil, errors.New("x509: unknown public key algorithm")
68 return parsePublicKey(algo, &pki)
71 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
72 switch pub := pub.(type) {
74 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
79 return nil, pkix.AlgorithmIdentifier{}, err
81 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
82 // This is a NULL parameters value which is required by
83 // RFC 3279, Section 2.3.1.
84 publicKeyAlgorithm.Parameters = asn1.NullRawValue
85 case *ecdsa.PublicKey:
86 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
87 oid, ok := oidFromNamedCurve(pub.Curve)
89 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
91 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
93 paramBytes, err = asn1.Marshal(oid)
97 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
98 case ed25519.PublicKey:
100 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
102 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
105 return publicKeyBytes, publicKeyAlgorithm, nil
108 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
109 // The encoded public key is a SubjectPublicKeyInfo structure
110 // (see RFC 5280, Section 4.1).
112 // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
113 // and ed25519.PublicKey. Unsupported key types result in an error.
115 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
116 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
117 var publicKeyBytes []byte
118 var publicKeyAlgorithm pkix.AlgorithmIdentifier
121 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
125 pkix := pkixPublicKey{
126 Algo: publicKeyAlgorithm,
127 BitString: asn1.BitString{
128 Bytes: publicKeyBytes,
129 BitLength: 8 * len(publicKeyBytes),
133 ret, _ := asn1.Marshal(pkix)
137 // These structures reflect the ASN.1 structure of X.509 certificates.:
139 type certificate struct {
141 TBSCertificate tbsCertificate
142 SignatureAlgorithm pkix.AlgorithmIdentifier
143 SignatureValue asn1.BitString
146 type tbsCertificate struct {
148 Version int `asn1:"optional,explicit,default:0,tag:0"`
149 SerialNumber *big.Int
150 SignatureAlgorithm pkix.AlgorithmIdentifier
153 Subject asn1.RawValue
154 PublicKey publicKeyInfo
155 UniqueId asn1.BitString `asn1:"optional,tag:1"`
156 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
157 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
160 type dsaAlgorithmParameters struct {
164 type validity struct {
165 NotBefore, NotAfter time.Time
168 type publicKeyInfo struct {
170 Algorithm pkix.AlgorithmIdentifier
171 PublicKey asn1.BitString
175 type authKeyId struct {
176 Id []byte `asn1:"optional,tag:0"`
179 type SignatureAlgorithm int
182 UnknownSignatureAlgorithm SignatureAlgorithm = iota
184 MD2WithRSA // Unsupported.
185 MD5WithRSA // Only supported for signing, not verification.
190 DSAWithSHA1 // Unsupported.
191 DSAWithSHA256 // Unsupported.
202 func (algo SignatureAlgorithm) isRSAPSS() bool {
204 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
211 func (algo SignatureAlgorithm) String() string {
212 for _, details := range signatureAlgorithmDetails {
213 if details.algo == algo {
217 return strconv.Itoa(int(algo))
220 type PublicKeyAlgorithm int
223 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
230 var publicKeyAlgoName = [...]string{
237 func (algo PublicKeyAlgorithm) String() string {
238 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
239 return publicKeyAlgoName[algo]
241 return strconv.Itoa(int(algo))
244 // OIDs for signature algorithms
246 // pkcs-1 OBJECT IDENTIFIER ::= {
247 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
250 // RFC 3279 2.2.1 RSA Signature Algorithms
252 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
254 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
256 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
258 // dsaWithSha1 OBJECT IDENTIFIER ::= {
259 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
261 // RFC 3279 2.2.3 ECDSA Signature Algorithm
263 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
264 // iso(1) member-body(2) us(840) ansi-x962(10045)
265 // signatures(4) ecdsa-with-SHA1(1)}
268 // RFC 4055 5 PKCS #1 Version 1.5
270 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
272 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
274 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
277 // RFC 5758 3.1 DSA Signature Algorithms
279 // dsaWithSha256 OBJECT IDENTIFIER ::= {
280 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
281 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
283 // RFC 5758 3.2 ECDSA Signature Algorithm
285 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
286 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
288 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
289 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
291 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
292 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
295 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
297 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
300 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
301 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
302 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
303 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
304 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
305 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
306 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
307 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
308 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
309 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
310 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
311 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
312 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
313 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
315 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
316 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
317 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
319 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
321 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
322 // but it's specified by ISO. Microsoft's makecert.exe has been known
323 // to produce certificates with this OID.
324 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
327 var signatureAlgorithmDetails = []struct {
328 algo SignatureAlgorithm
330 oid asn1.ObjectIdentifier
331 pubKeyAlgo PublicKeyAlgorithm
334 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
335 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
336 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
337 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
338 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
339 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
340 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
341 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
342 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
343 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
344 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
345 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
346 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
347 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
348 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
349 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
350 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
353 // hashToPSSParameters contains the DER encoded RSA PSS parameters for the
354 // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
355 // The parameters contain the following values:
356 // * hashAlgorithm contains the associated hash identifier with NULL parameters
357 // * maskGenAlgorithm always contains the default mgf1SHA1 identifier
358 // * saltLength contains the length of the associated hash
359 // * trailerField always contains the default trailerFieldBC value
360 var hashToPSSParameters = map[crypto.Hash]asn1.RawValue{
361 crypto.SHA256: 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}},
362 crypto.SHA384: 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}},
363 crypto.SHA512: 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}},
366 // pssParameters reflects the parameters in an AlgorithmIdentifier that
367 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
368 type pssParameters struct {
369 // The following three fields are not marked as
370 // optional because the default values specify SHA-1,
371 // which is no longer suitable for use in signatures.
372 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
373 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
374 SaltLength int `asn1:"explicit,tag:2"`
375 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
378 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
379 if ai.Algorithm.Equal(oidSignatureEd25519) {
380 // RFC 8410, Section 3
381 // > For all of the OIDs, the parameters MUST be absent.
382 if len(ai.Parameters.FullBytes) != 0 {
383 return UnknownSignatureAlgorithm
387 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
388 for _, details := range signatureAlgorithmDetails {
389 if ai.Algorithm.Equal(details.oid) {
393 return UnknownSignatureAlgorithm
396 // RSA PSS is special because it encodes important parameters
397 // in the Parameters.
399 var params pssParameters
400 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
401 return UnknownSignatureAlgorithm
404 var mgf1HashFunc pkix.AlgorithmIdentifier
405 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
406 return UnknownSignatureAlgorithm
409 // PSS is greatly overburdened with options. This code forces them into
410 // three buckets by requiring that the MGF1 hash function always match the
411 // message hash function (as recommended in RFC 3447, Section 8.1), that the
412 // salt length matches the hash length, and that the trailer field has the
414 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
415 !params.MGF.Algorithm.Equal(oidMGF1) ||
416 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
417 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
418 params.TrailerField != 1 {
419 return UnknownSignatureAlgorithm
423 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
424 return SHA256WithRSAPSS
425 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
426 return SHA384WithRSAPSS
427 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
428 return SHA512WithRSAPSS
431 return UnknownSignatureAlgorithm
434 // RFC 3279, 2.3 Public Key Algorithms
436 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
437 // rsadsi(113549) pkcs(1) 1 }
439 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
441 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
442 // x9-57(10040) x9cm(4) 1 }
444 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
446 // id-ecPublicKey OBJECT IDENTIFIER ::= {
447 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
449 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
450 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
451 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
452 oidPublicKeyEd25519 = oidSignatureEd25519
455 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
457 case oid.Equal(oidPublicKeyRSA):
459 case oid.Equal(oidPublicKeyDSA):
461 case oid.Equal(oidPublicKeyECDSA):
463 case oid.Equal(oidPublicKeyEd25519):
466 return UnknownPublicKeyAlgorithm
469 // RFC 5480, 2.1.1.1. Named Curve
471 // secp224r1 OBJECT IDENTIFIER ::= {
472 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
474 // secp256r1 OBJECT IDENTIFIER ::= {
475 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
478 // secp384r1 OBJECT IDENTIFIER ::= {
479 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
481 // secp521r1 OBJECT IDENTIFIER ::= {
482 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
484 // NB: secp256r1 is equivalent to prime256v1
486 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
487 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
488 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
489 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
492 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
494 case oid.Equal(oidNamedCurveP224):
495 return elliptic.P224()
496 case oid.Equal(oidNamedCurveP256):
497 return elliptic.P256()
498 case oid.Equal(oidNamedCurveP384):
499 return elliptic.P384()
500 case oid.Equal(oidNamedCurveP521):
501 return elliptic.P521()
506 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
508 case elliptic.P224():
509 return oidNamedCurveP224, true
510 case elliptic.P256():
511 return oidNamedCurveP256, true
512 case elliptic.P384():
513 return oidNamedCurveP384, true
514 case elliptic.P521():
515 return oidNamedCurveP521, true
521 // KeyUsage represents the set of actions that are valid for a given key. It's
522 // a bitmap of the KeyUsage* constants.
526 KeyUsageDigitalSignature KeyUsage = 1 << iota
527 KeyUsageContentCommitment
528 KeyUsageKeyEncipherment
529 KeyUsageDataEncipherment
537 // RFC 5280, 4.2.1.12 Extended Key Usage
539 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
541 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
543 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
544 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
545 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
546 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
547 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
548 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
550 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
551 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
552 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
553 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
554 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
555 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
556 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
557 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
558 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
559 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
560 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
561 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
562 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
563 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
566 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
567 // Each of the ExtKeyUsage* constants define a unique action.
571 ExtKeyUsageAny ExtKeyUsage = iota
572 ExtKeyUsageServerAuth
573 ExtKeyUsageClientAuth
574 ExtKeyUsageCodeSigning
575 ExtKeyUsageEmailProtection
576 ExtKeyUsageIPSECEndSystem
577 ExtKeyUsageIPSECTunnel
579 ExtKeyUsageTimeStamping
580 ExtKeyUsageOCSPSigning
581 ExtKeyUsageMicrosoftServerGatedCrypto
582 ExtKeyUsageNetscapeServerGatedCrypto
583 ExtKeyUsageMicrosoftCommercialCodeSigning
584 ExtKeyUsageMicrosoftKernelCodeSigning
587 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
588 var extKeyUsageOIDs = []struct {
589 extKeyUsage ExtKeyUsage
590 oid asn1.ObjectIdentifier
592 {ExtKeyUsageAny, oidExtKeyUsageAny},
593 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
594 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
595 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
596 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
597 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
598 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
599 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
600 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
601 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
602 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
603 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
604 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
605 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
608 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
609 for _, pair := range extKeyUsageOIDs {
610 if oid.Equal(pair.oid) {
611 return pair.extKeyUsage, true
617 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
618 for _, pair := range extKeyUsageOIDs {
619 if eku == pair.extKeyUsage {
620 return pair.oid, true
626 // A Certificate represents an X.509 certificate.
627 type Certificate struct {
628 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
629 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
630 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
631 RawSubject []byte // DER encoded Subject
632 RawIssuer []byte // DER encoded Issuer
635 SignatureAlgorithm SignatureAlgorithm
637 PublicKeyAlgorithm PublicKeyAlgorithm
638 PublicKey interface{}
641 SerialNumber *big.Int
644 NotBefore, NotAfter time.Time // Validity bounds.
647 // Extensions contains raw X.509 extensions. When parsing certificates,
648 // this can be used to extract non-critical extensions that are not
649 // parsed by this package. When marshaling certificates, the Extensions
650 // field is ignored, see ExtraExtensions.
651 Extensions []pkix.Extension
653 // ExtraExtensions contains extensions to be copied, raw, into any
654 // marshaled certificates. Values override any extensions that would
655 // otherwise be produced based on the other fields. The ExtraExtensions
656 // field is not populated when parsing certificates, see Extensions.
657 ExtraExtensions []pkix.Extension
659 // UnhandledCriticalExtensions contains a list of extension IDs that
660 // were not (fully) processed when parsing. Verify will fail if this
661 // slice is non-empty, unless verification is delegated to an OS
662 // library which understands all the critical extensions.
664 // Users can access these extensions using Extensions and can remove
665 // elements from this slice if they believe that they have been
667 UnhandledCriticalExtensions []asn1.ObjectIdentifier
669 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
670 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
672 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
673 // and MaxPathLenZero are valid.
674 BasicConstraintsValid bool
677 // MaxPathLen and MaxPathLenZero indicate the presence and
678 // value of the BasicConstraints' "pathLenConstraint".
680 // When parsing a certificate, a positive non-zero MaxPathLen
681 // means that the field was specified, -1 means it was unset,
682 // and MaxPathLenZero being true mean that the field was
683 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
684 // should be treated equivalent to -1 (unset).
686 // When generating a certificate, an unset pathLenConstraint
687 // can be requested with either MaxPathLen == -1 or using the
688 // zero value for both MaxPathLen and MaxPathLenZero.
690 // MaxPathLenZero indicates that BasicConstraintsValid==true
691 // and MaxPathLen==0 should be interpreted as an actual
692 // maximum path length of zero. Otherwise, that combination is
693 // interpreted as MaxPathLen not being set.
697 AuthorityKeyId []byte
699 // RFC 5280, 4.2.2.1 (Authority Information Access)
701 IssuingCertificateURL []string
703 // Subject Alternate Name values. (Note that these values may not be valid
704 // if invalid values were contained within a parsed certificate. For
705 // example, an element of DNSNames may not be a valid DNS domain name.)
707 EmailAddresses []string
712 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
713 PermittedDNSDomains []string
714 ExcludedDNSDomains []string
715 PermittedIPRanges []*net.IPNet
716 ExcludedIPRanges []*net.IPNet
717 PermittedEmailAddresses []string
718 ExcludedEmailAddresses []string
719 PermittedURIDomains []string
720 ExcludedURIDomains []string
722 // CRL Distribution Points
723 CRLDistributionPoints []string
725 PolicyIdentifiers []asn1.ObjectIdentifier
728 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
729 // involves algorithms that are not currently implemented.
730 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
732 // An InsecureAlgorithmError
733 type InsecureAlgorithmError SignatureAlgorithm
735 func (e InsecureAlgorithmError) Error() string {
736 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
739 // ConstraintViolationError results when a requested usage is not permitted by
740 // a certificate. For example: checking a signature when the public key isn't a
741 // certificate signing key.
742 type ConstraintViolationError struct{}
744 func (ConstraintViolationError) Error() string {
745 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
748 func (c *Certificate) Equal(other *Certificate) bool {
749 if c == nil || other == nil {
752 return bytes.Equal(c.Raw, other.Raw)
755 func (c *Certificate) hasSANExtension() bool {
756 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
759 // CheckSignatureFrom verifies that the signature on c is a valid signature
761 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
762 // RFC 5280, 4.2.1.9:
763 // "If the basic constraints extension is not present in a version 3
764 // certificate, or the extension is present but the cA boolean is not
765 // asserted, then the certified public key MUST NOT be used to verify
766 // certificate signatures."
767 if parent.Version == 3 && !parent.BasicConstraintsValid ||
768 parent.BasicConstraintsValid && !parent.IsCA {
769 return ConstraintViolationError{}
772 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
773 return ConstraintViolationError{}
776 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
777 return ErrUnsupportedAlgorithm
780 // TODO(agl): don't ignore the path length constraint.
782 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
785 // CheckSignature verifies that signature is a valid signature over signed from
787 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
788 return checkSignature(algo, signed, signature, c.PublicKey)
791 func (c *Certificate) hasNameConstraints() bool {
792 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
795 func (c *Certificate) getSANExtension() []byte {
796 for _, e := range c.Extensions {
797 if e.Id.Equal(oidExtensionSubjectAltName) {
804 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
805 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
808 // CheckSignature verifies that signature is a valid signature over signed from
809 // a crypto.PublicKey.
810 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
811 var hashType crypto.Hash
812 var pubKeyAlgo PublicKeyAlgorithm
814 for _, details := range signatureAlgorithmDetails {
815 if details.algo == algo {
816 hashType = details.hash
817 pubKeyAlgo = details.pubKeyAlgo
823 if pubKeyAlgo != Ed25519 {
824 return ErrUnsupportedAlgorithm
827 return InsecureAlgorithmError(algo)
829 if !hashType.Available() {
830 return ErrUnsupportedAlgorithm
837 switch pub := publicKey.(type) {
839 if pubKeyAlgo != RSA {
840 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
843 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
845 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
847 case *ecdsa.PublicKey:
848 if pubKeyAlgo != ECDSA {
849 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
851 if !ecdsa.VerifyASN1(pub, signed, signature) {
852 return errors.New("x509: ECDSA verification failure")
855 case ed25519.PublicKey:
856 if pubKeyAlgo != Ed25519 {
857 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
859 if !ed25519.Verify(pub, signed, signature) {
860 return errors.New("x509: Ed25519 verification failure")
864 return ErrUnsupportedAlgorithm
867 // CheckCRLSignature checks that the signature in crl is from c.
868 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
869 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
870 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
873 type UnhandledCriticalExtension struct{}
875 func (h UnhandledCriticalExtension) Error() string {
876 return "x509: unhandled critical extension"
879 type basicConstraints struct {
880 IsCA bool `asn1:"optional"`
881 MaxPathLen int `asn1:"optional,default:-1"`
885 type policyInformation struct {
886 Policy asn1.ObjectIdentifier
887 // policyQualifiers omitted
898 type authorityInfoAccess struct {
899 Method asn1.ObjectIdentifier
900 Location asn1.RawValue
903 // RFC 5280, 4.2.1.14
904 type distributionPoint struct {
905 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
906 Reason asn1.BitString `asn1:"optional,tag:1"`
907 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
910 type distributionPointName struct {
911 FullName []asn1.RawValue `asn1:"optional,tag:0"`
912 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
915 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
916 asn1Data := keyData.PublicKey.RightAlign()
919 // RSA public keys must have a NULL in the parameters.
920 // See RFC 3279, Section 2.3.1.
921 if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
922 return nil, errors.New("x509: RSA key missing NULL parameters")
925 p := new(pkcs1PublicKey)
926 rest, err := asn1.Unmarshal(asn1Data, p)
931 return nil, errors.New("x509: trailing data after RSA public key")
935 return nil, errors.New("x509: RSA modulus is not a positive number")
938 return nil, errors.New("x509: RSA public exponent is not a positive number")
941 pub := &rsa.PublicKey{
948 rest, err := asn1.Unmarshal(asn1Data, &p)
953 return nil, errors.New("x509: trailing data after DSA public key")
955 paramsData := keyData.Algorithm.Parameters.FullBytes
956 params := new(dsaAlgorithmParameters)
957 rest, err = asn1.Unmarshal(paramsData, params)
962 return nil, errors.New("x509: trailing data after DSA parameters")
964 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
965 return nil, errors.New("x509: zero or negative DSA parameter")
967 pub := &dsa.PublicKey{
968 Parameters: dsa.Parameters{
977 paramsData := keyData.Algorithm.Parameters.FullBytes
978 namedCurveOID := new(asn1.ObjectIdentifier)
979 rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
981 return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
984 return nil, errors.New("x509: trailing data after ECDSA parameters")
986 namedCurve := namedCurveFromOID(*namedCurveOID)
987 if namedCurve == nil {
988 return nil, errors.New("x509: unsupported elliptic curve")
990 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
992 return nil, errors.New("x509: failed to unmarshal elliptic curve point")
994 pub := &ecdsa.PublicKey{
1001 // RFC 8410, Section 3
1002 // > For all of the OIDs, the parameters MUST be absent.
1003 if len(keyData.Algorithm.Parameters.FullBytes) != 0 {
1004 return nil, errors.New("x509: Ed25519 key encoded with illegal parameters")
1006 if len(asn1Data) != ed25519.PublicKeySize {
1007 return nil, errors.New("x509: wrong Ed25519 public key size")
1009 pub := make([]byte, ed25519.PublicKeySize)
1011 return ed25519.PublicKey(pub), nil
1017 func forEachSAN(extension []byte, callback func(tag int, data []byte) error) error {
1018 // RFC 5280, 4.2.1.6
1020 // SubjectAltName ::= GeneralNames
1022 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1024 // GeneralName ::= CHOICE {
1025 // otherName [0] OtherName,
1026 // rfc822Name [1] IA5String,
1027 // dNSName [2] IA5String,
1028 // x400Address [3] ORAddress,
1029 // directoryName [4] Name,
1030 // ediPartyName [5] EDIPartyName,
1031 // uniformResourceIdentifier [6] IA5String,
1032 // iPAddress [7] OCTET STRING,
1033 // registeredID [8] OBJECT IDENTIFIER }
1034 var seq asn1.RawValue
1035 rest, err := asn1.Unmarshal(extension, &seq)
1038 } else if len(rest) != 0 {
1039 return errors.New("x509: trailing data after X.509 extension")
1041 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
1042 return asn1.StructuralError{Msg: "bad SAN sequence"}
1048 rest, err = asn1.Unmarshal(rest, &v)
1053 if err := callback(v.Tag, v.Bytes); err != nil {
1061 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
1062 err = forEachSAN(value, func(tag int, data []byte) error {
1065 email := string(data)
1066 if err := isIA5String(email); err != nil {
1067 return errors.New("x509: SAN rfc822Name is malformed")
1069 emailAddresses = append(emailAddresses, email)
1071 name := string(data)
1072 if err := isIA5String(name); err != nil {
1073 return errors.New("x509: SAN dNSName is malformed")
1075 dnsNames = append(dnsNames, string(name))
1077 uriStr := string(data)
1078 if err := isIA5String(uriStr); err != nil {
1079 return errors.New("x509: SAN uniformResourceIdentifier is malformed")
1081 uri, err := url.Parse(uriStr)
1083 return fmt.Errorf("x509: cannot parse URI %q: %s", uriStr, err)
1085 if len(uri.Host) > 0 {
1086 if _, ok := domainToReverseLabels(uri.Host); !ok {
1087 return fmt.Errorf("x509: cannot parse URI %q: invalid domain", uriStr)
1090 uris = append(uris, uri)
1093 case net.IPv4len, net.IPv6len:
1094 ipAddresses = append(ipAddresses, data)
1096 return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
1106 // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
1107 func isValidIPMask(mask []byte) bool {
1110 for _, b := range mask {
1120 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
1131 func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) {
1132 // RFC 5280, 4.2.1.10
1134 // NameConstraints ::= SEQUENCE {
1135 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
1136 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
1138 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
1140 // GeneralSubtree ::= SEQUENCE {
1141 // base GeneralName,
1142 // minimum [0] BaseDistance DEFAULT 0,
1143 // maximum [1] BaseDistance OPTIONAL }
1145 // BaseDistance ::= INTEGER (0..MAX)
1147 outer := cryptobyte.String(e.Value)
1148 var toplevel, permitted, excluded cryptobyte.String
1149 var havePermitted, haveExcluded bool
1150 if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
1152 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
1153 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
1155 return false, errors.New("x509: invalid NameConstraints extension")
1158 if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
1159 // From RFC 5280, Section 4.2.1.10:
1160 // “either the permittedSubtrees field
1161 // or the excludedSubtrees MUST be
1163 return false, errors.New("x509: empty name constraints extension")
1166 getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
1167 for !subtrees.Empty() {
1168 var seq, value cryptobyte.String
1169 var tag cryptobyte_asn1.Tag
1170 if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
1171 !seq.ReadAnyASN1(&value, &tag) {
1172 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
1176 dnsTag = cryptobyte_asn1.Tag(2).ContextSpecific()
1177 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
1178 ipTag = cryptobyte_asn1.Tag(7).ContextSpecific()
1179 uriTag = cryptobyte_asn1.Tag(6).ContextSpecific()
1184 domain := string(value)
1185 if err := isIA5String(domain); err != nil {
1186 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1189 trimmedDomain := domain
1190 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1191 // constraints can have a leading
1192 // period to exclude the domain
1193 // itself, but that's not valid in a
1194 // normal domain name.
1195 trimmedDomain = trimmedDomain[1:]
1197 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1198 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
1200 dnsNames = append(dnsNames, domain)
1216 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
1219 if !isValidIPMask(mask) {
1220 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
1223 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
1226 constraint := string(value)
1227 if err := isIA5String(constraint); err != nil {
1228 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1231 // If the constraint contains an @ then
1232 // it specifies an exact mailbox name.
1233 if strings.Contains(constraint, "@") {
1234 if _, ok := parseRFC2821Mailbox(constraint); !ok {
1235 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1238 // Otherwise it's a domain name.
1239 domain := constraint
1240 if len(domain) > 0 && domain[0] == '.' {
1243 if _, ok := domainToReverseLabels(domain); !ok {
1244 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1247 emails = append(emails, constraint)
1250 domain := string(value)
1251 if err := isIA5String(domain); err != nil {
1252 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1255 if net.ParseIP(domain) != nil {
1256 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
1259 trimmedDomain := domain
1260 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1261 // constraints can have a leading
1262 // period to exclude the domain itself,
1263 // but that's not valid in a normal
1265 trimmedDomain = trimmedDomain[1:]
1267 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1268 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain)
1270 uriDomains = append(uriDomains, domain)
1277 return dnsNames, ips, emails, uriDomains, nil
1280 if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
1283 if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
1286 out.PermittedDNSDomainsCritical = e.Critical
1288 return unhandled, nil
1291 func parseCertificate(in *certificate) (*Certificate, error) {
1292 out := new(Certificate)
1294 out.RawTBSCertificate = in.TBSCertificate.Raw
1295 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
1296 out.RawSubject = in.TBSCertificate.Subject.FullBytes
1297 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
1299 out.Signature = in.SignatureValue.RightAlign()
1300 out.SignatureAlgorithm =
1301 getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
1303 out.PublicKeyAlgorithm =
1304 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
1306 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
1311 out.Version = in.TBSCertificate.Version + 1
1312 out.SerialNumber = in.TBSCertificate.SerialNumber
1314 var issuer, subject pkix.RDNSequence
1315 if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
1317 } else if len(rest) != 0 {
1318 return nil, errors.New("x509: trailing data after X.509 subject")
1320 if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
1322 } else if len(rest) != 0 {
1323 return nil, errors.New("x509: trailing data after X.509 issuer")
1326 out.Issuer.FillFromRDNSequence(&issuer)
1327 out.Subject.FillFromRDNSequence(&subject)
1329 out.NotBefore = in.TBSCertificate.Validity.NotBefore
1330 out.NotAfter = in.TBSCertificate.Validity.NotAfter
1332 for _, e := range in.TBSCertificate.Extensions {
1333 out.Extensions = append(out.Extensions, e)
1336 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
1339 // RFC 5280, 4.2.1.3
1340 var usageBits asn1.BitString
1341 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
1343 } else if len(rest) != 0 {
1344 return nil, errors.New("x509: trailing data after X.509 KeyUsage")
1348 for i := 0; i < 9; i++ {
1349 if usageBits.At(i) != 0 {
1350 usage |= 1 << uint(i)
1353 out.KeyUsage = KeyUsage(usage)
1356 // RFC 5280, 4.2.1.9
1357 var constraints basicConstraints
1358 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1360 } else if len(rest) != 0 {
1361 return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
1364 out.BasicConstraintsValid = true
1365 out.IsCA = constraints.IsCA
1366 out.MaxPathLen = constraints.MaxPathLen
1367 out.MaxPathLenZero = out.MaxPathLen == 0
1368 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
1370 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value)
1375 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
1376 // If we didn't parse anything then we do the critical check, below.
1381 unhandled, err = parseNameConstraintsExtension(out, e)
1387 // RFC 5280, 4.2.1.13
1389 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1391 // DistributionPoint ::= SEQUENCE {
1392 // distributionPoint [0] DistributionPointName OPTIONAL,
1393 // reasons [1] ReasonFlags OPTIONAL,
1394 // cRLIssuer [2] GeneralNames OPTIONAL }
1396 // DistributionPointName ::= CHOICE {
1397 // fullName [0] GeneralNames,
1398 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
1400 var cdp []distributionPoint
1401 if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
1403 } else if len(rest) != 0 {
1404 return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
1407 for _, dp := range cdp {
1408 // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
1409 if len(dp.DistributionPoint.FullName) == 0 {
1413 for _, fullName := range dp.DistributionPoint.FullName {
1414 if fullName.Tag == 6 {
1415 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(fullName.Bytes))
1421 // RFC 5280, 4.2.1.1
1423 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
1425 } else if len(rest) != 0 {
1426 return nil, errors.New("x509: trailing data after X.509 authority key-id")
1428 out.AuthorityKeyId = a.Id
1431 // RFC 5280, 4.2.1.12. Extended Key Usage
1433 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1435 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1437 // KeyPurposeId ::= OBJECT IDENTIFIER
1439 var keyUsage []asn1.ObjectIdentifier
1440 if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
1442 } else if len(rest) != 0 {
1443 return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
1446 for _, u := range keyUsage {
1447 if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1448 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1450 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1455 // RFC 5280, 4.2.1.2
1457 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
1459 } else if len(rest) != 0 {
1460 return nil, errors.New("x509: trailing data after X.509 key-id")
1462 out.SubjectKeyId = keyid
1465 // RFC 5280 4.2.1.4: Certificate Policies
1466 var policies []policyInformation
1467 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
1469 } else if len(rest) != 0 {
1470 return nil, errors.New("x509: trailing data after X.509 certificate policies")
1472 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1473 for i, policy := range policies {
1474 out.PolicyIdentifiers[i] = policy.Policy
1478 // Unknown extensions are recorded if critical.
1481 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
1482 // RFC 5280 4.2.2.1: Authority Information Access
1483 var aia []authorityInfoAccess
1484 if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
1486 } else if len(rest) != 0 {
1487 return nil, errors.New("x509: trailing data after X.509 authority information")
1490 for _, v := range aia {
1491 // GeneralName: uniformResourceIdentifier [6] IA5String
1492 if v.Location.Tag != 6 {
1495 if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
1496 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
1497 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
1498 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
1502 // Unknown extensions are recorded if critical.
1506 if e.Critical && unhandled {
1507 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
1514 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1515 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
1516 var cert certificate
1517 rest, err := asn1.Unmarshal(asn1Data, &cert)
1522 return nil, asn1.SyntaxError{Msg: "trailing data"}
1525 return parseCertificate(&cert)
1528 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1529 // data. The certificates must be concatenated with no intermediate padding.
1530 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
1531 var v []*certificate
1533 for len(asn1Data) > 0 {
1534 cert := new(certificate)
1536 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
1543 ret := make([]*Certificate, len(v))
1544 for i, ci := range v {
1545 cert, err := parseCertificate(ci)
1555 func reverseBitsInAByte(in byte) byte {
1557 b2 := b1>>2&0x33 | b1<<2&0xcc
1558 b3 := b2>>1&0x55 | b2<<1&0xaa
1562 // asn1BitLength returns the bit-length of bitString by considering the
1563 // most-significant bit in a byte to be the "first" bit. This convention
1564 // matches ASN.1, but differs from almost everything else.
1565 func asn1BitLength(bitString []byte) int {
1566 bitLen := len(bitString) * 8
1568 for i := range bitString {
1569 b := bitString[len(bitString)-i-1]
1571 for bit := uint(0); bit < 8; bit++ {
1572 if (b>>bit)&1 == 1 {
1583 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1584 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1585 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1586 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1587 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1588 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1589 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1590 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1591 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1592 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1593 oidExtensionCRLNumber = []int{2, 5, 29, 20}
1597 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1598 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1601 // oidNotInExtensions reports whether an extension with the given oid exists in
1603 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1604 for _, e := range extensions {
1605 if e.Id.Equal(oid) {
1612 // marshalSANs marshals a list of addresses into a the contents of an X.509
1613 // SubjectAlternativeName extension.
1614 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1615 var rawValues []asn1.RawValue
1616 for _, name := range dnsNames {
1617 if err := isIA5String(name); err != nil {
1620 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1622 for _, email := range emailAddresses {
1623 if err := isIA5String(email); err != nil {
1626 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1628 for _, rawIP := range ipAddresses {
1629 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1634 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1636 for _, uri := range uris {
1637 uriStr := uri.String()
1638 if err := isIA5String(uriStr); err != nil {
1641 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1643 return asn1.Marshal(rawValues)
1646 func isIA5String(s string) error {
1647 for _, r := range s {
1648 // Per RFC5280 "IA5String is limited to the set of ASCII characters"
1649 if r > unicode.MaxASCII {
1650 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1657 func buildExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1658 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1661 if template.KeyUsage != 0 &&
1662 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1663 ret[n].Id = oidExtensionKeyUsage
1664 ret[n].Critical = true
1667 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1668 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1676 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1683 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1684 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1685 ret[n].Id = oidExtensionExtendedKeyUsage
1687 var oids []asn1.ObjectIdentifier
1688 for _, u := range template.ExtKeyUsage {
1689 if oid, ok := oidFromExtKeyUsage(u); ok {
1690 oids = append(oids, oid)
1692 err = errors.New("x509: unknown extended key usage")
1697 oids = append(oids, template.UnknownExtKeyUsage...)
1699 ret[n].Value, err = asn1.Marshal(oids)
1706 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1707 // Leaving MaxPathLen as zero indicates that no maximum path
1708 // length is desired, unless MaxPathLenZero is set. A value of
1709 // -1 causes encoding/asn1 to omit the value as desired.
1710 maxPathLen := template.MaxPathLen
1711 if maxPathLen == 0 && !template.MaxPathLenZero {
1714 ret[n].Id = oidExtensionBasicConstraints
1715 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
1716 ret[n].Critical = true
1723 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1724 ret[n].Id = oidExtensionSubjectKeyId
1725 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1732 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1733 ret[n].Id = oidExtensionAuthorityKeyId
1734 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1741 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1742 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1743 ret[n].Id = oidExtensionAuthorityInfoAccess
1744 var aiaValues []authorityInfoAccess
1745 for _, name := range template.OCSPServer {
1746 aiaValues = append(aiaValues, authorityInfoAccess{
1747 Method: oidAuthorityInfoAccessOcsp,
1748 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1751 for _, name := range template.IssuingCertificateURL {
1752 aiaValues = append(aiaValues, authorityInfoAccess{
1753 Method: oidAuthorityInfoAccessIssuers,
1754 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1757 ret[n].Value, err = asn1.Marshal(aiaValues)
1764 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1765 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1766 ret[n].Id = oidExtensionSubjectAltName
1767 // From RFC 5280, Section 4.2.1.6:
1768 // “If the subject field contains an empty sequence ... then
1769 // subjectAltName extension ... is marked as critical”
1770 ret[n].Critical = subjectIsEmpty
1771 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1778 if len(template.PolicyIdentifiers) > 0 &&
1779 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1780 ret[n].Id = oidExtensionCertificatePolicies
1781 policies := make([]policyInformation, len(template.PolicyIdentifiers))
1782 for i, policy := range template.PolicyIdentifiers {
1783 policies[i].Policy = policy
1785 ret[n].Value, err = asn1.Marshal(policies)
1792 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1793 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1794 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1795 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1796 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1797 ret[n].Id = oidExtensionNameConstraints
1798 ret[n].Critical = template.PermittedDNSDomainsCritical
1800 ipAndMask := func(ipNet *net.IPNet) []byte {
1801 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1802 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1803 ipAndMask = append(ipAndMask, maskedIP...)
1804 ipAndMask = append(ipAndMask, ipNet.Mask...)
1808 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1809 var b cryptobyte.Builder
1811 for _, name := range dns {
1812 if err = isIA5String(name); err != nil {
1816 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1817 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1818 b.AddBytes([]byte(name))
1823 for _, ipNet := range ips {
1824 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1825 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1826 b.AddBytes(ipAndMask(ipNet))
1831 for _, email := range emails {
1832 if err = isIA5String(email); err != nil {
1836 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1837 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1838 b.AddBytes([]byte(email))
1843 for _, uriDomain := range uriDomains {
1844 if err = isIA5String(uriDomain); err != nil {
1848 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1849 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1850 b.AddBytes([]byte(uriDomain))
1858 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1863 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1868 var b cryptobyte.Builder
1869 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1870 if len(permitted) > 0 {
1871 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1872 b.AddBytes(permitted)
1876 if len(excluded) > 0 {
1877 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1878 b.AddBytes(excluded)
1883 ret[n].Value, err = b.Bytes()
1890 if len(template.CRLDistributionPoints) > 0 &&
1891 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1892 ret[n].Id = oidExtensionCRLDistributionPoints
1894 var crlDp []distributionPoint
1895 for _, name := range template.CRLDistributionPoints {
1896 dp := distributionPoint{
1897 DistributionPoint: distributionPointName{
1898 FullName: []asn1.RawValue{
1899 {Tag: 6, Class: 2, Bytes: []byte(name)},
1903 crlDp = append(crlDp, dp)
1906 ret[n].Value, err = asn1.Marshal(crlDp)
1913 // Adding another extension here? Remember to update the maximum number
1914 // of elements in the make() at the top of the function and the list of
1915 // template fields used in CreateCertificate documentation.
1917 return append(ret[:n], template.ExtraExtensions...), nil
1920 func subjectBytes(cert *Certificate) ([]byte, error) {
1921 if len(cert.RawSubject) > 0 {
1922 return cert.RawSubject, nil
1925 return asn1.Marshal(cert.Subject.ToRDNSequence())
1928 // signingParamsForPublicKey returns the parameters to use for signing with
1929 // priv. If requestedSigAlgo is not zero then it overrides the default
1930 // signature algorithm.
1931 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1932 var pubType PublicKeyAlgorithm
1934 switch pub := pub.(type) {
1935 case *rsa.PublicKey:
1937 hashFunc = crypto.SHA256
1938 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1939 sigAlgo.Parameters = asn1.NullRawValue
1941 case *ecdsa.PublicKey:
1945 case elliptic.P224(), elliptic.P256():
1946 hashFunc = crypto.SHA256
1947 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1948 case elliptic.P384():
1949 hashFunc = crypto.SHA384
1950 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1951 case elliptic.P521():
1952 hashFunc = crypto.SHA512
1953 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1955 err = errors.New("x509: unknown elliptic curve")
1958 case ed25519.PublicKey:
1960 sigAlgo.Algorithm = oidSignatureEd25519
1963 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
1970 if requestedSigAlgo == 0 {
1975 for _, details := range signatureAlgorithmDetails {
1976 if details.algo == requestedSigAlgo {
1977 if details.pubKeyAlgo != pubType {
1978 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
1981 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
1982 if hashFunc == 0 && pubType != Ed25519 {
1983 err = errors.New("x509: cannot sign with hash function requested")
1986 if requestedSigAlgo.isRSAPSS() {
1987 sigAlgo.Parameters = hashToPSSParameters[hashFunc]
1995 err = errors.New("x509: unknown SignatureAlgorithm")
2001 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
2002 // just an empty SEQUENCE.
2003 var emptyASN1Subject = []byte{0x30, 0}
2005 // CreateCertificate creates a new X.509v3 certificate based on a template.
2006 // The following members of template are used:
2009 // - BasicConstraintsValid
2010 // - CRLDistributionPoints
2013 // - ExcludedDNSDomains
2014 // - ExcludedEmailAddresses
2015 // - ExcludedIPRanges
2016 // - ExcludedURIDomains
2018 // - ExtraExtensions
2021 // - IssuingCertificateURL
2028 // - PermittedDNSDomains
2029 // - PermittedDNSDomainsCritical
2030 // - PermittedEmailAddresses
2031 // - PermittedIPRanges
2032 // - PermittedURIDomains
2033 // - PolicyIdentifiers
2035 // - SignatureAlgorithm
2039 // - UnknownExtKeyUsage
2041 // The certificate is signed by parent. If parent is equal to template then the
2042 // certificate is self-signed. The parameter pub is the public key of the
2043 // signee and priv is the private key of the signer.
2045 // The returned slice is the certificate in DER encoding.
2047 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
2048 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
2049 // crypto.Signer with a supported public key.
2051 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
2052 // unless the resulting certificate is self-signed. Otherwise the value from
2053 // template will be used.
2055 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
2056 // will be generated from the hash of the public key.
2057 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
2058 key, ok := priv.(crypto.Signer)
2060 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2063 if template.SerialNumber == nil {
2064 return nil, errors.New("x509: no SerialNumber given")
2067 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
2068 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
2071 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2076 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
2081 asn1Issuer, err := subjectBytes(parent)
2086 asn1Subject, err := subjectBytes(template)
2091 authorityKeyId := template.AuthorityKeyId
2092 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
2093 authorityKeyId = parent.SubjectKeyId
2096 subjectKeyId := template.SubjectKeyId
2097 if len(subjectKeyId) == 0 && template.IsCA {
2098 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
2099 // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
2100 // value of the BIT STRING subjectPublicKey (excluding the tag,
2101 // length, and number of unused bits).
2102 h := sha1.Sum(publicKeyBytes)
2106 extensions, err := buildExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
2111 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
2112 c := tbsCertificate{
2114 SerialNumber: template.SerialNumber,
2115 SignatureAlgorithm: signatureAlgorithm,
2116 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
2117 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
2118 Subject: asn1.RawValue{FullBytes: asn1Subject},
2119 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
2120 Extensions: extensions,
2123 tbsCertContents, err := asn1.Marshal(c)
2127 c.Raw = tbsCertContents
2129 signed := tbsCertContents
2136 var signerOpts crypto.SignerOpts = hashFunc
2137 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
2138 signerOpts = &rsa.PSSOptions{
2139 SaltLength: rsa.PSSSaltLengthEqualsHash,
2144 var signature []byte
2145 signature, err = key.Sign(rand, signed, signerOpts)
2150 signedCert, err := asn1.Marshal(certificate{
2154 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2160 // Check the signature to ensure the crypto.Signer behaved correctly.
2161 // We skip this check if the signature algorithm is MD5WithRSA as we
2162 // only support this algorithm for signing, and not verification.
2163 if sigAlg := getSignatureAlgorithmFromAI(signatureAlgorithm); sigAlg != MD5WithRSA {
2164 if err := checkSignature(sigAlg, c.Raw, signature, key.Public()); err != nil {
2165 return nil, fmt.Errorf("x509: signature over certificate returned by signer is invalid: %w", err)
2169 return signedCert, nil
2172 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
2174 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
2176 // pemType is the type of a PEM encoded CRL.
2177 var pemType = "X509 CRL"
2179 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
2180 // encoded CRLs will appear where they should be DER encoded, so this function
2181 // will transparently handle PEM encoding as long as there isn't any leading
2183 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
2184 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
2185 block, _ := pem.Decode(crlBytes)
2186 if block != nil && block.Type == pemType {
2187 crlBytes = block.Bytes
2190 return ParseDERCRL(crlBytes)
2193 // ParseDERCRL parses a DER encoded CRL from the given bytes.
2194 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
2195 certList := new(pkix.CertificateList)
2196 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
2198 } else if len(rest) != 0 {
2199 return nil, errors.New("x509: trailing data after CRL")
2201 return certList, nil
2204 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
2205 // contains the given list of revoked certificates.
2207 // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
2208 // To generate a standards compliant CRL, use CreateRevocationList instead.
2209 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
2210 key, ok := priv.(crypto.Signer)
2212 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2215 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
2220 // Force revocation times to UTC per RFC 5280.
2221 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
2222 for i, rc := range revokedCerts {
2223 rc.RevocationTime = rc.RevocationTime.UTC()
2224 revokedCertsUTC[i] = rc
2227 tbsCertList := pkix.TBSCertificateList{
2229 Signature: signatureAlgorithm,
2230 Issuer: c.Subject.ToRDNSequence(),
2231 ThisUpdate: now.UTC(),
2232 NextUpdate: expiry.UTC(),
2233 RevokedCertificates: revokedCertsUTC,
2237 if len(c.SubjectKeyId) > 0 {
2238 var aki pkix.Extension
2239 aki.Id = oidExtensionAuthorityKeyId
2240 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
2244 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
2247 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2252 signed := tbsCertListContents
2259 var signature []byte
2260 signature, err = key.Sign(rand, signed, hashFunc)
2265 return asn1.Marshal(pkix.CertificateList{
2266 TBSCertList: tbsCertList,
2267 SignatureAlgorithm: signatureAlgorithm,
2268 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2272 // CertificateRequest represents a PKCS #10, certificate signature request.
2273 type CertificateRequest struct {
2274 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
2275 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
2276 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
2277 RawSubject []byte // DER encoded Subject.
2281 SignatureAlgorithm SignatureAlgorithm
2283 PublicKeyAlgorithm PublicKeyAlgorithm
2284 PublicKey interface{}
2288 // Attributes contains the CSR attributes that can parse as
2289 // pkix.AttributeTypeAndValueSET.
2291 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
2292 // generating the requestedExtensions attribute.
2293 Attributes []pkix.AttributeTypeAndValueSET
2295 // Extensions contains all requested extensions, in raw form. When parsing
2296 // CSRs, this can be used to extract extensions that are not parsed by this
2298 Extensions []pkix.Extension
2300 // ExtraExtensions contains extensions to be copied, raw, into any CSR
2301 // marshaled by CreateCertificateRequest. Values override any extensions
2302 // that would otherwise be produced based on the other fields but are
2303 // overridden by any extensions specified in Attributes.
2305 // The ExtraExtensions field is not populated by ParseCertificateRequest,
2306 // see Extensions instead.
2307 ExtraExtensions []pkix.Extension
2309 // Subject Alternate Name values.
2311 EmailAddresses []string
2312 IPAddresses []net.IP
2316 // These structures reflect the ASN.1 structure of X.509 certificate
2317 // signature requests (see RFC 2986):
2319 type tbsCertificateRequest struct {
2322 Subject asn1.RawValue
2323 PublicKey publicKeyInfo
2324 RawAttributes []asn1.RawValue `asn1:"tag:0"`
2327 type certificateRequest struct {
2329 TBSCSR tbsCertificateRequest
2330 SignatureAlgorithm pkix.AlgorithmIdentifier
2331 SignatureValue asn1.BitString
2334 // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
2335 // extensions in a CSR.
2336 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2338 // newRawAttributes converts AttributeTypeAndValueSETs from a template
2339 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
2340 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2341 var rawAttributes []asn1.RawValue
2342 b, err := asn1.Marshal(attributes)
2346 rest, err := asn1.Unmarshal(b, &rawAttributes)
2351 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2353 return rawAttributes, nil
2356 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
2357 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2358 var attributes []pkix.AttributeTypeAndValueSET
2359 for _, rawAttr := range rawAttributes {
2360 var attr pkix.AttributeTypeAndValueSET
2361 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2362 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2363 // (i.e.: challengePassword or unstructuredName).
2364 if err == nil && len(rest) == 0 {
2365 attributes = append(attributes, attr)
2371 // parseCSRExtensions parses the attributes from a CSR and extracts any
2372 // requested extensions.
2373 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2374 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
2375 type pkcs10Attribute struct {
2376 Id asn1.ObjectIdentifier
2377 Values []asn1.RawValue `asn1:"set"`
2380 var ret []pkix.Extension
2381 for _, rawAttr := range rawAttributes {
2382 var attr pkcs10Attribute
2383 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2384 // Ignore attributes that don't parse.
2388 if !attr.Id.Equal(oidExtensionRequest) {
2392 var extensions []pkix.Extension
2393 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2396 ret = append(ret, extensions...)
2402 // CreateCertificateRequest creates a new certificate request based on a
2403 // template. The following members of template are used:
2405 // - SignatureAlgorithm
2411 // - ExtraExtensions
2412 // - Attributes (deprecated)
2414 // priv is the private key to sign the CSR with, and the corresponding public
2415 // key will be included in the CSR. It must implement crypto.Signer and its
2416 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
2417 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
2418 // ed25519.PrivateKey satisfies this.)
2420 // The returned slice is the certificate request in DER encoding.
2421 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
2422 key, ok := priv.(crypto.Signer)
2424 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2427 var hashFunc crypto.Hash
2428 var sigAlgo pkix.AlgorithmIdentifier
2429 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2434 var publicKeyBytes []byte
2435 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2436 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2441 var extensions []pkix.Extension
2443 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
2444 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
2445 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
2450 extensions = append(extensions, pkix.Extension{
2451 Id: oidExtensionSubjectAltName,
2456 extensions = append(extensions, template.ExtraExtensions...)
2458 // Make a copy of template.Attributes because we may alter it below.
2459 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2460 for _, attr := range template.Attributes {
2461 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2462 copy(values, attr.Value)
2463 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2469 extensionsAppended := false
2470 if len(extensions) > 0 {
2471 // Append the extensions to an existing attribute if possible.
2472 for _, atvSet := range attributes {
2473 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2477 // specifiedExtensions contains all the extensions that we
2478 // found specified via template.Attributes.
2479 specifiedExtensions := make(map[string]bool)
2481 for _, atvs := range atvSet.Value {
2482 for _, atv := range atvs {
2483 specifiedExtensions[atv.Type.String()] = true
2487 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2488 newValue = append(newValue, atvSet.Value[0]...)
2490 for _, e := range extensions {
2491 if specifiedExtensions[e.Id.String()] {
2492 // Attributes already contained a value for
2493 // this extension and it takes priority.
2497 newValue = append(newValue, pkix.AttributeTypeAndValue{
2498 // There is no place for the critical
2499 // flag in an AttributeTypeAndValue.
2505 atvSet.Value[0] = newValue
2506 extensionsAppended = true
2511 rawAttributes, err := newRawAttributes(attributes)
2516 // If not included in attributes, add a new attribute for the
2518 if len(extensions) > 0 && !extensionsAppended {
2520 Type asn1.ObjectIdentifier
2521 Value [][]pkix.Extension `asn1:"set"`
2523 Type: oidExtensionRequest,
2524 Value: [][]pkix.Extension{extensions},
2527 b, err := asn1.Marshal(attr)
2529 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2532 var rawValue asn1.RawValue
2533 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2537 rawAttributes = append(rawAttributes, rawValue)
2540 asn1Subject := template.RawSubject
2541 if len(asn1Subject) == 0 {
2542 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2548 tbsCSR := tbsCertificateRequest{
2549 Version: 0, // PKCS #10, RFC 2986
2550 Subject: asn1.RawValue{FullBytes: asn1Subject},
2551 PublicKey: publicKeyInfo{
2552 Algorithm: publicKeyAlgorithm,
2553 PublicKey: asn1.BitString{
2554 Bytes: publicKeyBytes,
2555 BitLength: len(publicKeyBytes) * 8,
2558 RawAttributes: rawAttributes,
2561 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2565 tbsCSR.Raw = tbsCSRContents
2567 signed := tbsCSRContents
2574 var signature []byte
2575 signature, err = key.Sign(rand, signed, hashFunc)
2580 return asn1.Marshal(certificateRequest{
2582 SignatureAlgorithm: sigAlgo,
2583 SignatureValue: asn1.BitString{
2585 BitLength: len(signature) * 8,
2590 // ParseCertificateRequest parses a single certificate request from the
2591 // given ASN.1 DER data.
2592 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2593 var csr certificateRequest
2595 rest, err := asn1.Unmarshal(asn1Data, &csr)
2598 } else if len(rest) != 0 {
2599 return nil, asn1.SyntaxError{Msg: "trailing data"}
2602 return parseCertificateRequest(&csr)
2605 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2606 out := &CertificateRequest{
2608 RawTBSCertificateRequest: in.TBSCSR.Raw,
2609 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2610 RawSubject: in.TBSCSR.Subject.FullBytes,
2612 Signature: in.SignatureValue.RightAlign(),
2613 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2615 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2617 Version: in.TBSCSR.Version,
2618 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2622 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2627 var subject pkix.RDNSequence
2628 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2630 } else if len(rest) != 0 {
2631 return nil, errors.New("x509: trailing data after X.509 Subject")
2634 out.Subject.FillFromRDNSequence(&subject)
2636 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2640 for _, extension := range out.Extensions {
2641 if extension.Id.Equal(oidExtensionSubjectAltName) {
2642 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2652 // CheckSignature reports whether the signature on c is valid.
2653 func (c *CertificateRequest) CheckSignature() error {
2654 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
2657 // RevocationList contains the fields used to create an X.509 v2 Certificate
2658 // Revocation list with CreateRevocationList.
2659 type RevocationList struct {
2660 // SignatureAlgorithm is used to determine the signature algorithm to be
2661 // used when signing the CRL. If 0 the default algorithm for the signing
2662 // key will be used.
2663 SignatureAlgorithm SignatureAlgorithm
2665 // RevokedCertificates is used to populate the revokedCertificates
2666 // sequence in the CRL, it may be empty. RevokedCertificates may be nil,
2667 // in which case an empty CRL will be created.
2668 RevokedCertificates []pkix.RevokedCertificate
2670 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2671 // which should be a monotonically increasing sequence number for a given
2672 // CRL scope and CRL issuer.
2674 // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2675 // indicates the issuance date of the CRL.
2676 ThisUpdate time.Time
2677 // NextUpdate is used to populate the nextUpdate field in the CRL, which
2678 // indicates the date by which the next CRL will be issued. NextUpdate
2679 // must be greater than ThisUpdate.
2680 NextUpdate time.Time
2681 // ExtraExtensions contains any additional extensions to add directly to
2683 ExtraExtensions []pkix.Extension
2686 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
2687 // according to RFC 5280, based on template.
2689 // The CRL is signed by priv which should be the private key associated with
2690 // the public key in the issuer certificate.
2692 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
2693 // order to use it as a CRL issuer.
2695 // The issuer distinguished name CRL field and authority key identifier
2696 // extension are populated using the issuer certificate. issuer must have
2697 // SubjectKeyId set.
2698 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2699 if template == nil {
2700 return nil, errors.New("x509: template can not be nil")
2703 return nil, errors.New("x509: issuer can not be nil")
2705 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2706 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2708 if len(issuer.SubjectKeyId) == 0 {
2709 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2711 if template.NextUpdate.Before(template.ThisUpdate) {
2712 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2714 if template.Number == nil {
2715 return nil, errors.New("x509: template contains nil Number field")
2718 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2723 // Force revocation times to UTC per RFC 5280.
2724 revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2725 for i, rc := range template.RevokedCertificates {
2726 rc.RevocationTime = rc.RevocationTime.UTC()
2727 revokedCertsUTC[i] = rc
2730 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2734 crlNum, err := asn1.Marshal(template.Number)
2739 tbsCertList := pkix.TBSCertificateList{
2741 Signature: signatureAlgorithm,
2742 Issuer: issuer.Subject.ToRDNSequence(),
2743 ThisUpdate: template.ThisUpdate.UTC(),
2744 NextUpdate: template.NextUpdate.UTC(),
2745 Extensions: []pkix.Extension{
2747 Id: oidExtensionAuthorityKeyId,
2751 Id: oidExtensionCRLNumber,
2756 if len(revokedCertsUTC) > 0 {
2757 tbsCertList.RevokedCertificates = revokedCertsUTC
2760 if len(template.ExtraExtensions) > 0 {
2761 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2764 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2769 input := tbsCertListContents
2772 h.Write(tbsCertListContents)
2775 var signerOpts crypto.SignerOpts = hashFunc
2776 if template.SignatureAlgorithm.isRSAPSS() {
2777 signerOpts = &rsa.PSSOptions{
2778 SaltLength: rsa.PSSSaltLengthEqualsHash,
2783 signature, err := priv.Sign(rand, input, signerOpts)
2788 return asn1.Marshal(pkix.CertificateList{
2789 TBSCertList: tbsCertList,
2790 SignatureAlgorithm: signatureAlgorithm,
2791 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},