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 implements a subset of the X.509 standard.
7 // It allows parsing and generating certificates, certificate signing
8 // requests, certificate revocation lists, and encoded public and private keys.
9 // It provides a certificate verifier, complete with a chain builder.
11 // The package targets the X.509 technical profile defined by the IETF (RFC
12 // 2459/3280/5280), and as further restricted by the CA/Browser Forum Baseline
13 // Requirements. There is minimal support for features outside of these
14 // profiles, as the primary goal of the package is to provide compatibility
15 // with the publicly trusted TLS certificate ecosystem and its policies and
18 // On macOS and Windows, certificate verification is handled by system APIs, but
19 // the package aims to apply consistent validation rules across operating
46 // Explicitly import these for their crypto.RegisterHash init side-effects.
47 // Keep these as blank imports, even if they're imported above.
52 "golang.org/x/crypto/cryptobyte"
53 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
56 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
58 type pkixPublicKey struct {
59 Algo pkix.AlgorithmIdentifier
60 BitString asn1.BitString
63 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded
64 // public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).
66 // It returns a *[rsa.PublicKey], *[dsa.PublicKey], *[ecdsa.PublicKey],
67 // [ed25519.PublicKey] (not a pointer), or *[ecdh.PublicKey] (for X25519).
68 // More types might be supported in the future.
70 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
71 func ParsePKIXPublicKey(derBytes []byte) (pub any, err error) {
73 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
74 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
75 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
78 } else if len(rest) != 0 {
79 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
81 return parsePublicKey(&pki)
84 func marshalPublicKey(pub any) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
85 switch pub := pub.(type) {
87 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
92 return nil, pkix.AlgorithmIdentifier{}, err
94 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
95 // This is a NULL parameters value which is required by
96 // RFC 3279, Section 2.3.1.
97 publicKeyAlgorithm.Parameters = asn1.NullRawValue
98 case *ecdsa.PublicKey:
99 oid, ok := oidFromNamedCurve(pub.Curve)
101 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
103 if !pub.Curve.IsOnCurve(pub.X, pub.Y) {
104 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: invalid elliptic curve public key")
106 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
107 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
108 var paramBytes []byte
109 paramBytes, err = asn1.Marshal(oid)
113 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
114 case ed25519.PublicKey:
116 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
117 case *ecdh.PublicKey:
118 publicKeyBytes = pub.Bytes()
119 if pub.Curve() == ecdh.X25519() {
120 publicKeyAlgorithm.Algorithm = oidPublicKeyX25519
122 oid, ok := oidFromECDHCurve(pub.Curve())
124 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
126 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
127 var paramBytes []byte
128 paramBytes, err = asn1.Marshal(oid)
132 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
135 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
138 return publicKeyBytes, publicKeyAlgorithm, nil
141 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
142 // The encoded public key is a SubjectPublicKeyInfo structure
143 // (see RFC 5280, Section 4.1).
145 // The following key types are currently supported: *[rsa.PublicKey],
146 // *[ecdsa.PublicKey], [ed25519.PublicKey] (not a pointer), and *[ecdh.PublicKey].
147 // Unsupported key types result in an error.
149 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
150 func MarshalPKIXPublicKey(pub any) ([]byte, error) {
151 var publicKeyBytes []byte
152 var publicKeyAlgorithm pkix.AlgorithmIdentifier
155 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
159 pkix := pkixPublicKey{
160 Algo: publicKeyAlgorithm,
161 BitString: asn1.BitString{
162 Bytes: publicKeyBytes,
163 BitLength: 8 * len(publicKeyBytes),
167 ret, _ := asn1.Marshal(pkix)
171 // These structures reflect the ASN.1 structure of X.509 certificates.:
173 type certificate struct {
174 TBSCertificate tbsCertificate
175 SignatureAlgorithm pkix.AlgorithmIdentifier
176 SignatureValue asn1.BitString
179 type tbsCertificate struct {
181 Version int `asn1:"optional,explicit,default:0,tag:0"`
182 SerialNumber *big.Int
183 SignatureAlgorithm pkix.AlgorithmIdentifier
186 Subject asn1.RawValue
187 PublicKey publicKeyInfo
188 UniqueId asn1.BitString `asn1:"optional,tag:1"`
189 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
190 Extensions []pkix.Extension `asn1:"omitempty,optional,explicit,tag:3"`
193 type dsaAlgorithmParameters struct {
197 type validity struct {
198 NotBefore, NotAfter time.Time
201 type publicKeyInfo struct {
203 Algorithm pkix.AlgorithmIdentifier
204 PublicKey asn1.BitString
208 type authKeyId struct {
209 Id []byte `asn1:"optional,tag:0"`
212 type SignatureAlgorithm int
215 UnknownSignatureAlgorithm SignatureAlgorithm = iota
217 MD2WithRSA // Unsupported.
218 MD5WithRSA // Only supported for signing, not verification.
219 SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
223 DSAWithSHA1 // Unsupported.
224 DSAWithSHA256 // Unsupported.
225 ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
235 func (algo SignatureAlgorithm) isRSAPSS() bool {
237 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
244 func (algo SignatureAlgorithm) String() string {
245 for _, details := range signatureAlgorithmDetails {
246 if details.algo == algo {
250 return strconv.Itoa(int(algo))
253 type PublicKeyAlgorithm int
256 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
258 DSA // Only supported for parsing.
263 var publicKeyAlgoName = [...]string{
270 func (algo PublicKeyAlgorithm) String() string {
271 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
272 return publicKeyAlgoName[algo]
274 return strconv.Itoa(int(algo))
277 // OIDs for signature algorithms
279 // pkcs-1 OBJECT IDENTIFIER ::= {
280 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
282 // RFC 3279 2.2.1 RSA Signature Algorithms
284 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
286 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
288 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
290 // dsaWithSha1 OBJECT IDENTIFIER ::= {
291 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
293 // RFC 3279 2.2.3 ECDSA Signature Algorithm
295 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
296 // iso(1) member-body(2) us(840) ansi-x962(10045)
297 // signatures(4) ecdsa-with-SHA1(1)}
299 // RFC 4055 5 PKCS #1 Version 1.5
301 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
303 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
305 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
307 // RFC 5758 3.1 DSA Signature Algorithms
309 // dsaWithSha256 OBJECT IDENTIFIER ::= {
310 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
311 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
313 // RFC 5758 3.2 ECDSA Signature Algorithm
315 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
316 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
318 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
319 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
321 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
322 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
324 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
326 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
328 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
329 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
330 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
331 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
332 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
333 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
334 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
335 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
336 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
337 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
338 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
339 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
340 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
341 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
343 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
344 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
345 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
347 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
349 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
350 // but it's specified by ISO. Microsoft's makecert.exe has been known
351 // to produce certificates with this OID.
352 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
355 var signatureAlgorithmDetails = []struct {
356 algo SignatureAlgorithm
358 oid asn1.ObjectIdentifier
359 pubKeyAlgo PublicKeyAlgorithm
362 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
363 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
364 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
365 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
366 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
367 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
368 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
369 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
370 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
371 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
372 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
373 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
374 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
375 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
376 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
377 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
378 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
381 // hashToPSSParameters contains the DER encoded RSA PSS parameters for the
382 // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
383 // The parameters contain the following values:
384 // - hashAlgorithm contains the associated hash identifier with NULL parameters
385 // - maskGenAlgorithm always contains the default mgf1SHA1 identifier
386 // - saltLength contains the length of the associated hash
387 // - trailerField always contains the default trailerFieldBC value
388 var hashToPSSParameters = map[crypto.Hash]asn1.RawValue{
389 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}},
390 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}},
391 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}},
394 // pssParameters reflects the parameters in an AlgorithmIdentifier that
395 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
396 type pssParameters struct {
397 // The following three fields are not marked as
398 // optional because the default values specify SHA-1,
399 // which is no longer suitable for use in signatures.
400 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
401 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
402 SaltLength int `asn1:"explicit,tag:2"`
403 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
406 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
407 if ai.Algorithm.Equal(oidSignatureEd25519) {
408 // RFC 8410, Section 3
409 // > For all of the OIDs, the parameters MUST be absent.
410 if len(ai.Parameters.FullBytes) != 0 {
411 return UnknownSignatureAlgorithm
415 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
416 for _, details := range signatureAlgorithmDetails {
417 if ai.Algorithm.Equal(details.oid) {
421 return UnknownSignatureAlgorithm
424 // RSA PSS is special because it encodes important parameters
425 // in the Parameters.
427 var params pssParameters
428 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
429 return UnknownSignatureAlgorithm
432 var mgf1HashFunc pkix.AlgorithmIdentifier
433 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
434 return UnknownSignatureAlgorithm
437 // PSS is greatly overburdened with options. This code forces them into
438 // three buckets by requiring that the MGF1 hash function always match the
439 // message hash function (as recommended in RFC 3447, Section 8.1), that the
440 // salt length matches the hash length, and that the trailer field has the
442 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
443 !params.MGF.Algorithm.Equal(oidMGF1) ||
444 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
445 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
446 params.TrailerField != 1 {
447 return UnknownSignatureAlgorithm
451 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
452 return SHA256WithRSAPSS
453 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
454 return SHA384WithRSAPSS
455 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
456 return SHA512WithRSAPSS
459 return UnknownSignatureAlgorithm
463 // RFC 3279, 2.3 Public Key Algorithms
465 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
466 // rsadsi(113549) pkcs(1) 1 }
468 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
470 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
471 // x9-57(10040) x9cm(4) 1 }
472 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
473 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
474 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
476 // id-ecPublicKey OBJECT IDENTIFIER ::= {
477 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
478 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
479 // RFC 8410, Section 3
481 // id-X25519 OBJECT IDENTIFIER ::= { 1 3 101 110 }
482 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
483 oidPublicKeyX25519 = asn1.ObjectIdentifier{1, 3, 101, 110}
484 oidPublicKeyEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
487 // getPublicKeyAlgorithmFromOID returns the exposed PublicKeyAlgorithm
488 // identifier for public key types supported in certificates and CSRs. Marshal
489 // and Parse functions may support a different set of public key types.
490 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
492 case oid.Equal(oidPublicKeyRSA):
494 case oid.Equal(oidPublicKeyDSA):
496 case oid.Equal(oidPublicKeyECDSA):
498 case oid.Equal(oidPublicKeyEd25519):
501 return UnknownPublicKeyAlgorithm
504 // RFC 5480, 2.1.1.1. Named Curve
506 // secp224r1 OBJECT IDENTIFIER ::= {
507 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
509 // secp256r1 OBJECT IDENTIFIER ::= {
510 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
513 // secp384r1 OBJECT IDENTIFIER ::= {
514 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
516 // secp521r1 OBJECT IDENTIFIER ::= {
517 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
519 // NB: secp256r1 is equivalent to prime256v1
521 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
522 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
523 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
524 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
527 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
529 case oid.Equal(oidNamedCurveP224):
530 return elliptic.P224()
531 case oid.Equal(oidNamedCurveP256):
532 return elliptic.P256()
533 case oid.Equal(oidNamedCurveP384):
534 return elliptic.P384()
535 case oid.Equal(oidNamedCurveP521):
536 return elliptic.P521()
541 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
543 case elliptic.P224():
544 return oidNamedCurveP224, true
545 case elliptic.P256():
546 return oidNamedCurveP256, true
547 case elliptic.P384():
548 return oidNamedCurveP384, true
549 case elliptic.P521():
550 return oidNamedCurveP521, true
556 func oidFromECDHCurve(curve ecdh.Curve) (asn1.ObjectIdentifier, bool) {
559 return oidPublicKeyX25519, true
561 return oidNamedCurveP256, true
563 return oidNamedCurveP384, true
565 return oidNamedCurveP521, true
571 // KeyUsage represents the set of actions that are valid for a given key. It's
572 // a bitmap of the KeyUsage* constants.
576 KeyUsageDigitalSignature KeyUsage = 1 << iota
577 KeyUsageContentCommitment
578 KeyUsageKeyEncipherment
579 KeyUsageDataEncipherment
587 // RFC 5280, 4.2.1.12 Extended Key Usage
589 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
591 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
593 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
594 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
595 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
596 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
597 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
598 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
600 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
601 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
602 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
603 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
604 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
605 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
606 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
607 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
608 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
609 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
610 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
611 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
612 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
613 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
616 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
617 // Each of the ExtKeyUsage* constants define a unique action.
621 ExtKeyUsageAny ExtKeyUsage = iota
622 ExtKeyUsageServerAuth
623 ExtKeyUsageClientAuth
624 ExtKeyUsageCodeSigning
625 ExtKeyUsageEmailProtection
626 ExtKeyUsageIPSECEndSystem
627 ExtKeyUsageIPSECTunnel
629 ExtKeyUsageTimeStamping
630 ExtKeyUsageOCSPSigning
631 ExtKeyUsageMicrosoftServerGatedCrypto
632 ExtKeyUsageNetscapeServerGatedCrypto
633 ExtKeyUsageMicrosoftCommercialCodeSigning
634 ExtKeyUsageMicrosoftKernelCodeSigning
637 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
638 var extKeyUsageOIDs = []struct {
639 extKeyUsage ExtKeyUsage
640 oid asn1.ObjectIdentifier
642 {ExtKeyUsageAny, oidExtKeyUsageAny},
643 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
644 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
645 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
646 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
647 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
648 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
649 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
650 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
651 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
652 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
653 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
654 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
655 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
658 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
659 for _, pair := range extKeyUsageOIDs {
660 if oid.Equal(pair.oid) {
661 return pair.extKeyUsage, true
667 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
668 for _, pair := range extKeyUsageOIDs {
669 if eku == pair.extKeyUsage {
670 return pair.oid, true
676 // A Certificate represents an X.509 certificate.
677 type Certificate struct {
678 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
679 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
680 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
681 RawSubject []byte // DER encoded Subject
682 RawIssuer []byte // DER encoded Issuer
685 SignatureAlgorithm SignatureAlgorithm
687 PublicKeyAlgorithm PublicKeyAlgorithm
691 SerialNumber *big.Int
694 NotBefore, NotAfter time.Time // Validity bounds.
697 // Extensions contains raw X.509 extensions. When parsing certificates,
698 // this can be used to extract non-critical extensions that are not
699 // parsed by this package. When marshaling certificates, the Extensions
700 // field is ignored, see ExtraExtensions.
701 Extensions []pkix.Extension
703 // ExtraExtensions contains extensions to be copied, raw, into any
704 // marshaled certificates. Values override any extensions that would
705 // otherwise be produced based on the other fields. The ExtraExtensions
706 // field is not populated when parsing certificates, see Extensions.
707 ExtraExtensions []pkix.Extension
709 // UnhandledCriticalExtensions contains a list of extension IDs that
710 // were not (fully) processed when parsing. Verify will fail if this
711 // slice is non-empty, unless verification is delegated to an OS
712 // library which understands all the critical extensions.
714 // Users can access these extensions using Extensions and can remove
715 // elements from this slice if they believe that they have been
717 UnhandledCriticalExtensions []asn1.ObjectIdentifier
719 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
720 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
722 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
723 // and MaxPathLenZero are valid.
724 BasicConstraintsValid bool
727 // MaxPathLen and MaxPathLenZero indicate the presence and
728 // value of the BasicConstraints' "pathLenConstraint".
730 // When parsing a certificate, a positive non-zero MaxPathLen
731 // means that the field was specified, -1 means it was unset,
732 // and MaxPathLenZero being true mean that the field was
733 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
734 // should be treated equivalent to -1 (unset).
736 // When generating a certificate, an unset pathLenConstraint
737 // can be requested with either MaxPathLen == -1 or using the
738 // zero value for both MaxPathLen and MaxPathLenZero.
740 // MaxPathLenZero indicates that BasicConstraintsValid==true
741 // and MaxPathLen==0 should be interpreted as an actual
742 // maximum path length of zero. Otherwise, that combination is
743 // interpreted as MaxPathLen not being set.
747 AuthorityKeyId []byte
749 // RFC 5280, 4.2.2.1 (Authority Information Access)
751 IssuingCertificateURL []string
753 // Subject Alternate Name values. (Note that these values may not be valid
754 // if invalid values were contained within a parsed certificate. For
755 // example, an element of DNSNames may not be a valid DNS domain name.)
757 EmailAddresses []string
762 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
763 PermittedDNSDomains []string
764 ExcludedDNSDomains []string
765 PermittedIPRanges []*net.IPNet
766 ExcludedIPRanges []*net.IPNet
767 PermittedEmailAddresses []string
768 ExcludedEmailAddresses []string
769 PermittedURIDomains []string
770 ExcludedURIDomains []string
772 // CRL Distribution Points
773 CRLDistributionPoints []string
775 // PolicyIdentifiers contains asn1.ObjectIdentifiers, the components
776 // of which are limited to int32. If a certificate contains a policy which
777 // cannot be represented by asn1.ObjectIdentifier, it will not be included in
778 // PolicyIdentifiers, but will be present in Policies, which contains all parsed
780 PolicyIdentifiers []asn1.ObjectIdentifier
782 // Policies contains all policy identifiers included in the certificate.
786 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
787 // involves algorithms that are not currently implemented.
788 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
790 // An InsecureAlgorithmError indicates that the [SignatureAlgorithm] used to
791 // generate the signature is not secure, and the signature has been rejected.
793 // To temporarily restore support for SHA-1 signatures, include the value
794 // "x509sha1=1" in the GODEBUG environment variable. Note that this option will
795 // be removed in a future release.
796 type InsecureAlgorithmError SignatureAlgorithm
798 func (e InsecureAlgorithmError) Error() string {
800 if SignatureAlgorithm(e) == SHA1WithRSA || SignatureAlgorithm(e) == ECDSAWithSHA1 {
801 override = " (temporarily override with GODEBUG=x509sha1=1)"
803 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e)) + override
806 // ConstraintViolationError results when a requested usage is not permitted by
807 // a certificate. For example: checking a signature when the public key isn't a
808 // certificate signing key.
809 type ConstraintViolationError struct{}
811 func (ConstraintViolationError) Error() string {
812 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
815 func (c *Certificate) Equal(other *Certificate) bool {
816 if c == nil || other == nil {
819 return bytes.Equal(c.Raw, other.Raw)
822 func (c *Certificate) hasSANExtension() bool {
823 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
826 // CheckSignatureFrom verifies that the signature on c is a valid signature from parent.
828 // This is a low-level API that performs very limited checks, and not a full
829 // path verifier. Most users should use [Certificate.Verify] instead.
830 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
831 // RFC 5280, 4.2.1.9:
832 // "If the basic constraints extension is not present in a version 3
833 // certificate, or the extension is present but the cA boolean is not
834 // asserted, then the certified public key MUST NOT be used to verify
835 // certificate signatures."
836 if parent.Version == 3 && !parent.BasicConstraintsValid ||
837 parent.BasicConstraintsValid && !parent.IsCA {
838 return ConstraintViolationError{}
841 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
842 return ConstraintViolationError{}
845 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
846 return ErrUnsupportedAlgorithm
849 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature, parent.PublicKey, false)
852 // CheckSignature verifies that signature is a valid signature over signed from
855 // This is a low-level API that performs no validity checks on the certificate.
857 // [MD5WithRSA] signatures are rejected, while [SHA1WithRSA] and [ECDSAWithSHA1]
858 // signatures are currently accepted.
859 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
860 return checkSignature(algo, signed, signature, c.PublicKey, true)
863 func (c *Certificate) hasNameConstraints() bool {
864 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
867 func (c *Certificate) getSANExtension() []byte {
868 for _, e := range c.Extensions {
869 if e.Id.Equal(oidExtensionSubjectAltName) {
876 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {
877 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
880 var x509sha1 = godebug.New("x509sha1")
882 // checkSignature verifies that signature is a valid signature over signed from
883 // a crypto.PublicKey.
884 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error) {
885 var hashType crypto.Hash
886 var pubKeyAlgo PublicKeyAlgorithm
888 for _, details := range signatureAlgorithmDetails {
889 if details.algo == algo {
890 hashType = details.hash
891 pubKeyAlgo = details.pubKeyAlgo
898 if pubKeyAlgo != Ed25519 {
899 return ErrUnsupportedAlgorithm
902 return InsecureAlgorithmError(algo)
904 // SHA-1 signatures are mostly disabled. See go.dev/issue/41682.
906 if x509sha1.Value() != "1" {
907 return InsecureAlgorithmError(algo)
909 x509sha1.IncNonDefault()
913 if !hashType.Available() {
914 return ErrUnsupportedAlgorithm
921 switch pub := publicKey.(type) {
923 if pubKeyAlgo != RSA {
924 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
927 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
929 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
931 case *ecdsa.PublicKey:
932 if pubKeyAlgo != ECDSA {
933 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
935 if !ecdsa.VerifyASN1(pub, signed, signature) {
936 return errors.New("x509: ECDSA verification failure")
939 case ed25519.PublicKey:
940 if pubKeyAlgo != Ed25519 {
941 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
943 if !ed25519.Verify(pub, signed, signature) {
944 return errors.New("x509: Ed25519 verification failure")
948 return ErrUnsupportedAlgorithm
951 // CheckCRLSignature checks that the signature in crl is from c.
953 // Deprecated: Use [RevocationList.CheckSignatureFrom] instead.
954 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
955 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
956 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
959 type UnhandledCriticalExtension struct{}
961 func (h UnhandledCriticalExtension) Error() string {
962 return "x509: unhandled critical extension"
965 type basicConstraints struct {
966 IsCA bool `asn1:"optional"`
967 MaxPathLen int `asn1:"optional,default:-1"`
971 type policyInformation struct {
972 Policy asn1.ObjectIdentifier
973 // policyQualifiers omitted
984 type authorityInfoAccess struct {
985 Method asn1.ObjectIdentifier
986 Location asn1.RawValue
989 // RFC 5280, 4.2.1.14
990 type distributionPoint struct {
991 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
992 Reason asn1.BitString `asn1:"optional,tag:1"`
993 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
996 type distributionPointName struct {
997 FullName []asn1.RawValue `asn1:"optional,tag:0"`
998 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
1001 func reverseBitsInAByte(in byte) byte {
1003 b2 := b1>>2&0x33 | b1<<2&0xcc
1004 b3 := b2>>1&0x55 | b2<<1&0xaa
1008 // asn1BitLength returns the bit-length of bitString by considering the
1009 // most-significant bit in a byte to be the "first" bit. This convention
1010 // matches ASN.1, but differs from almost everything else.
1011 func asn1BitLength(bitString []byte) int {
1012 bitLen := len(bitString) * 8
1014 for i := range bitString {
1015 b := bitString[len(bitString)-i-1]
1017 for bit := uint(0); bit < 8; bit++ {
1018 if (b>>bit)&1 == 1 {
1029 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1030 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1031 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1032 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1033 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1034 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1035 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1036 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1037 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1038 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1039 oidExtensionCRLNumber = []int{2, 5, 29, 20}
1040 oidExtensionReasonCode = []int{2, 5, 29, 21}
1044 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1045 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1048 // oidInExtensions reports whether an extension with the given oid exists in
1050 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1051 for _, e := range extensions {
1052 if e.Id.Equal(oid) {
1059 // marshalSANs marshals a list of addresses into a the contents of an X.509
1060 // SubjectAlternativeName extension.
1061 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1062 var rawValues []asn1.RawValue
1063 for _, name := range dnsNames {
1064 if err := isIA5String(name); err != nil {
1067 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1069 for _, email := range emailAddresses {
1070 if err := isIA5String(email); err != nil {
1073 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1075 for _, rawIP := range ipAddresses {
1076 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1081 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1083 for _, uri := range uris {
1084 uriStr := uri.String()
1085 if err := isIA5String(uriStr); err != nil {
1088 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1090 return asn1.Marshal(rawValues)
1093 func isIA5String(s string) error {
1094 for _, r := range s {
1095 // Per RFC5280 "IA5String is limited to the set of ASCII characters"
1096 if r > unicode.MaxASCII {
1097 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1104 func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1105 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1108 if template.KeyUsage != 0 &&
1109 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1110 ret[n], err = marshalKeyUsage(template.KeyUsage)
1117 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1118 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1119 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
1126 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1127 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
1134 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1135 ret[n].Id = oidExtensionSubjectKeyId
1136 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1143 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1144 ret[n].Id = oidExtensionAuthorityKeyId
1145 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1152 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1153 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1154 ret[n].Id = oidExtensionAuthorityInfoAccess
1155 var aiaValues []authorityInfoAccess
1156 for _, name := range template.OCSPServer {
1157 aiaValues = append(aiaValues, authorityInfoAccess{
1158 Method: oidAuthorityInfoAccessOcsp,
1159 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1162 for _, name := range template.IssuingCertificateURL {
1163 aiaValues = append(aiaValues, authorityInfoAccess{
1164 Method: oidAuthorityInfoAccessIssuers,
1165 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1168 ret[n].Value, err = asn1.Marshal(aiaValues)
1175 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1176 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1177 ret[n].Id = oidExtensionSubjectAltName
1178 // From RFC 5280, Section 4.2.1.6:
1179 // “If the subject field contains an empty sequence ... then
1180 // subjectAltName extension ... is marked as critical”
1181 ret[n].Critical = subjectIsEmpty
1182 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1189 if len(template.PolicyIdentifiers) > 0 &&
1190 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1191 ret[n], err = marshalCertificatePolicies(template.Policies, template.PolicyIdentifiers)
1198 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1199 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1200 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1201 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1202 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1203 ret[n].Id = oidExtensionNameConstraints
1204 ret[n].Critical = template.PermittedDNSDomainsCritical
1206 ipAndMask := func(ipNet *net.IPNet) []byte {
1207 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1208 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1209 ipAndMask = append(ipAndMask, maskedIP...)
1210 ipAndMask = append(ipAndMask, ipNet.Mask...)
1214 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1215 var b cryptobyte.Builder
1217 for _, name := range dns {
1218 if err = isIA5String(name); err != nil {
1222 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1223 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1224 b.AddBytes([]byte(name))
1229 for _, ipNet := range ips {
1230 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1231 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1232 b.AddBytes(ipAndMask(ipNet))
1237 for _, email := range emails {
1238 if err = isIA5String(email); err != nil {
1242 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1243 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1244 b.AddBytes([]byte(email))
1249 for _, uriDomain := range uriDomains {
1250 if err = isIA5String(uriDomain); err != nil {
1254 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1255 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1256 b.AddBytes([]byte(uriDomain))
1264 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1269 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1274 var b cryptobyte.Builder
1275 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1276 if len(permitted) > 0 {
1277 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1278 b.AddBytes(permitted)
1282 if len(excluded) > 0 {
1283 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1284 b.AddBytes(excluded)
1289 ret[n].Value, err = b.Bytes()
1296 if len(template.CRLDistributionPoints) > 0 &&
1297 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1298 ret[n].Id = oidExtensionCRLDistributionPoints
1300 var crlDp []distributionPoint
1301 for _, name := range template.CRLDistributionPoints {
1302 dp := distributionPoint{
1303 DistributionPoint: distributionPointName{
1304 FullName: []asn1.RawValue{
1305 {Tag: 6, Class: 2, Bytes: []byte(name)},
1309 crlDp = append(crlDp, dp)
1312 ret[n].Value, err = asn1.Marshal(crlDp)
1319 // Adding another extension here? Remember to update the maximum number
1320 // of elements in the make() at the top of the function and the list of
1321 // template fields used in CreateCertificate documentation.
1323 return append(ret[:n], template.ExtraExtensions...), nil
1326 func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
1327 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
1330 a[0] = reverseBitsInAByte(byte(ku))
1331 a[1] = reverseBitsInAByte(byte(ku >> 8))
1340 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1344 func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
1345 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
1347 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
1348 for i, u := range extUsages {
1349 if oid, ok := oidFromExtKeyUsage(u); ok {
1352 return ext, errors.New("x509: unknown extended key usage")
1356 copy(oids[len(extUsages):], unknownUsages)
1359 ext.Value, err = asn1.Marshal(oids)
1363 func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
1364 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
1365 // Leaving MaxPathLen as zero indicates that no maximum path
1366 // length is desired, unless MaxPathLenZero is set. A value of
1367 // -1 causes encoding/asn1 to omit the value as desired.
1368 if maxPathLen == 0 && !maxPathLenZero {
1372 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
1376 func marshalCertificatePolicies(policies []OID, policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
1377 ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
1379 b := cryptobyte.NewBuilder(make([]byte, 0, 128))
1380 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1381 for _, v := range policies {
1382 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1383 child.AddASN1(cryptobyte_asn1.OBJECT_IDENTIFIER, func(child *cryptobyte.Builder) {
1384 child.AddBytes(v.der)
1388 for _, v := range policyIdentifiers {
1389 child.AddASN1(cryptobyte_asn1.SEQUENCE, func(child *cryptobyte.Builder) {
1390 child.AddASN1ObjectIdentifier(v)
1396 ext.Value, err = b.Bytes()
1400 func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
1401 var ret []pkix.Extension
1403 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1404 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1405 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1410 ret = append(ret, pkix.Extension{
1411 Id: oidExtensionSubjectAltName,
1416 return append(ret, template.ExtraExtensions...), nil
1419 func subjectBytes(cert *Certificate) ([]byte, error) {
1420 if len(cert.RawSubject) > 0 {
1421 return cert.RawSubject, nil
1424 return asn1.Marshal(cert.Subject.ToRDNSequence())
1427 // signingParamsForPublicKey returns the parameters to use for signing with
1428 // priv. If requestedSigAlgo is not zero then it overrides the default
1429 // signature algorithm.
1430 func signingParamsForPublicKey(pub any, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1431 var pubType PublicKeyAlgorithm
1433 switch pub := pub.(type) {
1434 case *rsa.PublicKey:
1436 hashFunc = crypto.SHA256
1437 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1438 sigAlgo.Parameters = asn1.NullRawValue
1440 case *ecdsa.PublicKey:
1444 case elliptic.P224(), elliptic.P256():
1445 hashFunc = crypto.SHA256
1446 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1447 case elliptic.P384():
1448 hashFunc = crypto.SHA384
1449 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1450 case elliptic.P521():
1451 hashFunc = crypto.SHA512
1452 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1454 err = errors.New("x509: unknown elliptic curve")
1457 case ed25519.PublicKey:
1459 sigAlgo.Algorithm = oidSignatureEd25519
1462 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
1469 if requestedSigAlgo == 0 {
1474 for _, details := range signatureAlgorithmDetails {
1475 if details.algo == requestedSigAlgo {
1476 if details.pubKeyAlgo != pubType {
1477 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
1480 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
1481 if hashFunc == 0 && pubType != Ed25519 {
1482 err = errors.New("x509: cannot sign with hash function requested")
1485 if hashFunc == crypto.MD5 {
1486 err = errors.New("x509: signing with MD5 is not supported")
1489 if requestedSigAlgo.isRSAPSS() {
1490 sigAlgo.Parameters = hashToPSSParameters[hashFunc]
1498 err = errors.New("x509: unknown SignatureAlgorithm")
1504 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
1505 // just an empty SEQUENCE.
1506 var emptyASN1Subject = []byte{0x30, 0}
1508 // CreateCertificate creates a new X.509 v3 certificate based on a template.
1509 // The following members of template are currently used:
1512 // - BasicConstraintsValid
1513 // - CRLDistributionPoints
1516 // - ExcludedDNSDomains
1517 // - ExcludedEmailAddresses
1518 // - ExcludedIPRanges
1519 // - ExcludedURIDomains
1521 // - ExtraExtensions
1524 // - IssuingCertificateURL
1531 // - PermittedDNSDomains
1532 // - PermittedDNSDomainsCritical
1533 // - PermittedEmailAddresses
1534 // - PermittedIPRanges
1535 // - PermittedURIDomains
1536 // - PolicyIdentifiers
1538 // - SignatureAlgorithm
1542 // - UnknownExtKeyUsage
1544 // The certificate is signed by parent. If parent is equal to template then the
1545 // certificate is self-signed. The parameter pub is the public key of the
1546 // certificate to be generated and priv is the private key of the signer.
1548 // The returned slice is the certificate in DER encoding.
1550 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
1551 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
1552 // crypto.Signer with a supported public key.
1554 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
1555 // unless the resulting certificate is self-signed. Otherwise the value from
1556 // template will be used.
1558 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
1559 // will be generated from the hash of the public key.
1560 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) {
1561 key, ok := priv.(crypto.Signer)
1563 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1566 if template.SerialNumber == nil {
1567 return nil, errors.New("x509: no SerialNumber given")
1570 // RFC 5280 Section 4.1.2.2: serial number must positive
1572 // We _should_ also restrict serials to <= 20 octets, but it turns out a lot of people
1573 // get this wrong, in part because the encoding can itself alter the length of the
1574 // serial. For now we accept these non-conformant serials.
1575 if template.SerialNumber.Sign() == -1 {
1576 return nil, errors.New("x509: serial number must be positive")
1579 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
1580 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
1583 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1588 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1592 if getPublicKeyAlgorithmFromOID(publicKeyAlgorithm.Algorithm) == UnknownPublicKeyAlgorithm {
1593 return nil, fmt.Errorf("x509: unsupported public key type: %T", pub)
1596 asn1Issuer, err := subjectBytes(parent)
1601 asn1Subject, err := subjectBytes(template)
1606 authorityKeyId := template.AuthorityKeyId
1607 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1608 authorityKeyId = parent.SubjectKeyId
1611 subjectKeyId := template.SubjectKeyId
1612 if len(subjectKeyId) == 0 && template.IsCA {
1613 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
1614 // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
1615 // value of the BIT STRING subjectPublicKey (excluding the tag,
1616 // length, and number of unused bits).
1617 h := sha1.Sum(publicKeyBytes)
1621 // Check that the signer's public key matches the private key, if available.
1622 type privateKey interface {
1623 Equal(crypto.PublicKey) bool
1625 if privPub, ok := key.Public().(privateKey); !ok {
1626 return nil, errors.New("x509: internal error: supported public key does not implement Equal")
1627 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
1628 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
1631 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
1636 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1637 c := tbsCertificate{
1639 SerialNumber: template.SerialNumber,
1640 SignatureAlgorithm: signatureAlgorithm,
1641 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1642 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1643 Subject: asn1.RawValue{FullBytes: asn1Subject},
1644 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1645 Extensions: extensions,
1648 tbsCertContents, err := asn1.Marshal(c)
1652 c.Raw = tbsCertContents
1654 signed := tbsCertContents
1661 var signerOpts crypto.SignerOpts = hashFunc
1662 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
1663 signerOpts = &rsa.PSSOptions{
1664 SaltLength: rsa.PSSSaltLengthEqualsHash,
1669 var signature []byte
1670 signature, err = key.Sign(rand, signed, signerOpts)
1675 signedCert, err := asn1.Marshal(certificate{
1678 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1684 // Check the signature to ensure the crypto.Signer behaved correctly.
1685 if err := checkSignature(getSignatureAlgorithmFromAI(signatureAlgorithm), c.Raw, signature, key.Public(), true); err != nil {
1686 return nil, fmt.Errorf("x509: signature over certificate returned by signer is invalid: %w", err)
1689 return signedCert, nil
1692 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1694 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1696 // pemType is the type of a PEM encoded CRL.
1697 var pemType = "X509 CRL"
1699 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1700 // encoded CRLs will appear where they should be DER encoded, so this function
1701 // will transparently handle PEM encoding as long as there isn't any leading
1704 // Deprecated: Use [ParseRevocationList] instead.
1705 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1706 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1707 block, _ := pem.Decode(crlBytes)
1708 if block != nil && block.Type == pemType {
1709 crlBytes = block.Bytes
1712 return ParseDERCRL(crlBytes)
1715 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1717 // Deprecated: Use [ParseRevocationList] instead.
1718 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1719 certList := new(pkix.CertificateList)
1720 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
1722 } else if len(rest) != 0 {
1723 return nil, errors.New("x509: trailing data after CRL")
1725 return certList, nil
1728 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1729 // contains the given list of revoked certificates.
1731 // Deprecated: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
1732 // To generate a standards compliant CRL, use [CreateRevocationList] instead.
1733 func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1734 key, ok := priv.(crypto.Signer)
1736 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1739 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
1744 // Force revocation times to UTC per RFC 5280.
1745 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
1746 for i, rc := range revokedCerts {
1747 rc.RevocationTime = rc.RevocationTime.UTC()
1748 revokedCertsUTC[i] = rc
1751 tbsCertList := pkix.TBSCertificateList{
1753 Signature: signatureAlgorithm,
1754 Issuer: c.Subject.ToRDNSequence(),
1755 ThisUpdate: now.UTC(),
1756 NextUpdate: expiry.UTC(),
1757 RevokedCertificates: revokedCertsUTC,
1761 if len(c.SubjectKeyId) > 0 {
1762 var aki pkix.Extension
1763 aki.Id = oidExtensionAuthorityKeyId
1764 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
1768 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
1771 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1776 signed := tbsCertListContents
1783 var signature []byte
1784 signature, err = key.Sign(rand, signed, hashFunc)
1789 return asn1.Marshal(pkix.CertificateList{
1790 TBSCertList: tbsCertList,
1791 SignatureAlgorithm: signatureAlgorithm,
1792 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1796 // CertificateRequest represents a PKCS #10, certificate signature request.
1797 type CertificateRequest struct {
1798 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
1799 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
1800 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
1801 RawSubject []byte // DER encoded Subject.
1805 SignatureAlgorithm SignatureAlgorithm
1807 PublicKeyAlgorithm PublicKeyAlgorithm
1812 // Attributes contains the CSR attributes that can parse as
1813 // pkix.AttributeTypeAndValueSET.
1815 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
1816 // generating the requestedExtensions attribute.
1817 Attributes []pkix.AttributeTypeAndValueSET
1819 // Extensions contains all requested extensions, in raw form. When parsing
1820 // CSRs, this can be used to extract extensions that are not parsed by this
1822 Extensions []pkix.Extension
1824 // ExtraExtensions contains extensions to be copied, raw, into any CSR
1825 // marshaled by CreateCertificateRequest. Values override any extensions
1826 // that would otherwise be produced based on the other fields but are
1827 // overridden by any extensions specified in Attributes.
1829 // The ExtraExtensions field is not populated by ParseCertificateRequest,
1830 // see Extensions instead.
1831 ExtraExtensions []pkix.Extension
1833 // Subject Alternate Name values.
1835 EmailAddresses []string
1836 IPAddresses []net.IP
1840 // These structures reflect the ASN.1 structure of X.509 certificate
1841 // signature requests (see RFC 2986):
1843 type tbsCertificateRequest struct {
1846 Subject asn1.RawValue
1847 PublicKey publicKeyInfo
1848 RawAttributes []asn1.RawValue `asn1:"tag:0"`
1851 type certificateRequest struct {
1853 TBSCSR tbsCertificateRequest
1854 SignatureAlgorithm pkix.AlgorithmIdentifier
1855 SignatureValue asn1.BitString
1858 // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
1859 // extensions in a CSR.
1860 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
1862 // newRawAttributes converts AttributeTypeAndValueSETs from a template
1863 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
1864 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
1865 var rawAttributes []asn1.RawValue
1866 b, err := asn1.Marshal(attributes)
1870 rest, err := asn1.Unmarshal(b, &rawAttributes)
1875 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
1877 return rawAttributes, nil
1880 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
1881 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
1882 var attributes []pkix.AttributeTypeAndValueSET
1883 for _, rawAttr := range rawAttributes {
1884 var attr pkix.AttributeTypeAndValueSET
1885 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
1886 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
1887 // (i.e.: challengePassword or unstructuredName).
1888 if err == nil && len(rest) == 0 {
1889 attributes = append(attributes, attr)
1895 // parseCSRExtensions parses the attributes from a CSR and extracts any
1896 // requested extensions.
1897 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
1898 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
1899 type pkcs10Attribute struct {
1900 Id asn1.ObjectIdentifier
1901 Values []asn1.RawValue `asn1:"set"`
1904 var ret []pkix.Extension
1905 requestedExts := make(map[string]bool)
1906 for _, rawAttr := range rawAttributes {
1907 var attr pkcs10Attribute
1908 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
1909 // Ignore attributes that don't parse.
1913 if !attr.Id.Equal(oidExtensionRequest) {
1917 var extensions []pkix.Extension
1918 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
1921 for _, ext := range extensions {
1922 oidStr := ext.Id.String()
1923 if requestedExts[oidStr] {
1924 return nil, errors.New("x509: certificate request contains duplicate requested extensions")
1926 requestedExts[oidStr] = true
1928 ret = append(ret, extensions...)
1934 // CreateCertificateRequest creates a new certificate request based on a
1935 // template. The following members of template are used:
1937 // - SignatureAlgorithm
1943 // - ExtraExtensions
1944 // - Attributes (deprecated)
1946 // priv is the private key to sign the CSR with, and the corresponding public
1947 // key will be included in the CSR. It must implement crypto.Signer and its
1948 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
1949 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
1950 // ed25519.PrivateKey satisfies this.)
1952 // The returned slice is the certificate request in DER encoding.
1953 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error) {
1954 key, ok := priv.(crypto.Signer)
1956 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1959 var hashFunc crypto.Hash
1960 var sigAlgo pkix.AlgorithmIdentifier
1961 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1966 var publicKeyBytes []byte
1967 var publicKeyAlgorithm pkix.AlgorithmIdentifier
1968 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
1973 extensions, err := buildCSRExtensions(template)
1978 // Make a copy of template.Attributes because we may alter it below.
1979 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
1980 for _, attr := range template.Attributes {
1981 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
1982 copy(values, attr.Value)
1983 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
1989 extensionsAppended := false
1990 if len(extensions) > 0 {
1991 // Append the extensions to an existing attribute if possible.
1992 for _, atvSet := range attributes {
1993 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
1997 // specifiedExtensions contains all the extensions that we
1998 // found specified via template.Attributes.
1999 specifiedExtensions := make(map[string]bool)
2001 for _, atvs := range atvSet.Value {
2002 for _, atv := range atvs {
2003 specifiedExtensions[atv.Type.String()] = true
2007 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2008 newValue = append(newValue, atvSet.Value[0]...)
2010 for _, e := range extensions {
2011 if specifiedExtensions[e.Id.String()] {
2012 // Attributes already contained a value for
2013 // this extension and it takes priority.
2017 newValue = append(newValue, pkix.AttributeTypeAndValue{
2018 // There is no place for the critical
2019 // flag in an AttributeTypeAndValue.
2025 atvSet.Value[0] = newValue
2026 extensionsAppended = true
2031 rawAttributes, err := newRawAttributes(attributes)
2036 // If not included in attributes, add a new attribute for the
2038 if len(extensions) > 0 && !extensionsAppended {
2040 Type asn1.ObjectIdentifier
2041 Value [][]pkix.Extension `asn1:"set"`
2043 Type: oidExtensionRequest,
2044 Value: [][]pkix.Extension{extensions},
2047 b, err := asn1.Marshal(attr)
2049 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2052 var rawValue asn1.RawValue
2053 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2057 rawAttributes = append(rawAttributes, rawValue)
2060 asn1Subject := template.RawSubject
2061 if len(asn1Subject) == 0 {
2062 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2068 tbsCSR := tbsCertificateRequest{
2069 Version: 0, // PKCS #10, RFC 2986
2070 Subject: asn1.RawValue{FullBytes: asn1Subject},
2071 PublicKey: publicKeyInfo{
2072 Algorithm: publicKeyAlgorithm,
2073 PublicKey: asn1.BitString{
2074 Bytes: publicKeyBytes,
2075 BitLength: len(publicKeyBytes) * 8,
2078 RawAttributes: rawAttributes,
2081 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2085 tbsCSR.Raw = tbsCSRContents
2087 signed := tbsCSRContents
2094 var signature []byte
2095 signature, err = key.Sign(rand, signed, hashFunc)
2100 return asn1.Marshal(certificateRequest{
2102 SignatureAlgorithm: sigAlgo,
2103 SignatureValue: asn1.BitString{
2105 BitLength: len(signature) * 8,
2110 // ParseCertificateRequest parses a single certificate request from the
2111 // given ASN.1 DER data.
2112 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2113 var csr certificateRequest
2115 rest, err := asn1.Unmarshal(asn1Data, &csr)
2118 } else if len(rest) != 0 {
2119 return nil, asn1.SyntaxError{Msg: "trailing data"}
2122 return parseCertificateRequest(&csr)
2125 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2126 out := &CertificateRequest{
2128 RawTBSCertificateRequest: in.TBSCSR.Raw,
2129 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2130 RawSubject: in.TBSCSR.Subject.FullBytes,
2132 Signature: in.SignatureValue.RightAlign(),
2133 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2135 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2137 Version: in.TBSCSR.Version,
2138 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2142 if out.PublicKeyAlgorithm != UnknownPublicKeyAlgorithm {
2143 out.PublicKey, err = parsePublicKey(&in.TBSCSR.PublicKey)
2149 var subject pkix.RDNSequence
2150 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2152 } else if len(rest) != 0 {
2153 return nil, errors.New("x509: trailing data after X.509 Subject")
2156 out.Subject.FillFromRDNSequence(&subject)
2158 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2162 for _, extension := range out.Extensions {
2164 case extension.Id.Equal(oidExtensionSubjectAltName):
2165 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2175 // CheckSignature reports whether the signature on c is valid.
2176 func (c *CertificateRequest) CheckSignature() error {
2177 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey, true)
2180 // RevocationListEntry represents an entry in the revokedCertificates
2181 // sequence of a CRL.
2182 type RevocationListEntry struct {
2183 // Raw contains the raw bytes of the revokedCertificates entry. It is set when
2184 // parsing a CRL; it is ignored when generating a CRL.
2187 // SerialNumber represents the serial number of a revoked certificate. It is
2188 // both used when creating a CRL and populated when parsing a CRL. It must not
2190 SerialNumber *big.Int
2191 // RevocationTime represents the time at which the certificate was revoked. It
2192 // is both used when creating a CRL and populated when parsing a CRL. It must
2193 // not be the zero time.
2194 RevocationTime time.Time
2195 // ReasonCode represents the reason for revocation, using the integer enum
2196 // values specified in RFC 5280 Section 5.3.1. When creating a CRL, the zero
2197 // value will result in the reasonCode extension being omitted. When parsing a
2198 // CRL, the zero value may represent either the reasonCode extension being
2199 // absent (which implies the default revocation reason of 0/Unspecified), or
2200 // it may represent the reasonCode extension being present and explicitly
2201 // containing a value of 0/Unspecified (which should not happen according to
2202 // the DER encoding rules, but can and does happen anyway).
2205 // Extensions contains raw X.509 extensions. When parsing CRL entries,
2206 // this can be used to extract non-critical extensions that are not
2207 // parsed by this package. When marshaling CRL entries, the Extensions
2208 // field is ignored, see ExtraExtensions.
2209 Extensions []pkix.Extension
2210 // ExtraExtensions contains extensions to be copied, raw, into any
2211 // marshaled CRL entries. Values override any extensions that would
2212 // otherwise be produced based on the other fields. The ExtraExtensions
2213 // field is not populated when parsing CRL entries, see Extensions.
2214 ExtraExtensions []pkix.Extension
2217 // RevocationList represents a [Certificate] Revocation List (CRL) as specified
2219 type RevocationList struct {
2220 // Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,
2221 // signatureAlgorithm, and signatureValue.)
2223 // RawTBSRevocationList contains just the tbsCertList portion of the ASN.1
2225 RawTBSRevocationList []byte
2226 // RawIssuer contains the DER encoded Issuer.
2229 // Issuer contains the DN of the issuing certificate.
2231 // AuthorityKeyId is used to identify the public key associated with the
2232 // issuing certificate. It is populated from the authorityKeyIdentifier
2233 // extension when parsing a CRL. It is ignored when creating a CRL; the
2234 // extension is populated from the issuing certificate itself.
2235 AuthorityKeyId []byte
2238 // SignatureAlgorithm is used to determine the signature algorithm to be
2239 // used when signing the CRL. If 0 the default algorithm for the signing
2240 // key will be used.
2241 SignatureAlgorithm SignatureAlgorithm
2243 // RevokedCertificateEntries represents the revokedCertificates sequence in
2244 // the CRL. It is used when creating a CRL and also populated when parsing a
2245 // CRL. When creating a CRL, it may be empty or nil, in which case the
2246 // revokedCertificates ASN.1 sequence will be omitted from the CRL entirely.
2247 RevokedCertificateEntries []RevocationListEntry
2249 // RevokedCertificates is used to populate the revokedCertificates
2250 // sequence in the CRL if RevokedCertificateEntries is empty. It may be empty
2251 // or nil, in which case an empty CRL will be created.
2253 // Deprecated: Use RevokedCertificateEntries instead.
2254 RevokedCertificates []pkix.RevokedCertificate
2256 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2257 // which should be a monotonically increasing sequence number for a given
2258 // CRL scope and CRL issuer. It is also populated from the cRLNumber
2259 // extension when parsing a CRL.
2262 // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2263 // indicates the issuance date of the CRL.
2264 ThisUpdate time.Time
2265 // NextUpdate is used to populate the nextUpdate field in the CRL, which
2266 // indicates the date by which the next CRL will be issued. NextUpdate
2267 // must be greater than ThisUpdate.
2268 NextUpdate time.Time
2270 // Extensions contains raw X.509 extensions. When creating a CRL,
2271 // the Extensions field is ignored, see ExtraExtensions.
2272 Extensions []pkix.Extension
2274 // ExtraExtensions contains any additional extensions to add directly to
2276 ExtraExtensions []pkix.Extension
2279 // These structures reflect the ASN.1 structure of X.509 CRLs better than
2280 // the existing crypto/x509/pkix variants do. These mirror the existing
2281 // certificate structs in this file.
2283 // Notably, we include issuer as an asn1.RawValue, mirroring the behavior of
2284 // tbsCertificate and allowing raw (unparsed) subjects to be passed cleanly.
2285 type certificateList struct {
2286 TBSCertList tbsCertificateList
2287 SignatureAlgorithm pkix.AlgorithmIdentifier
2288 SignatureValue asn1.BitString
2291 type tbsCertificateList struct {
2293 Version int `asn1:"optional,default:0"`
2294 Signature pkix.AlgorithmIdentifier
2295 Issuer asn1.RawValue
2296 ThisUpdate time.Time
2297 NextUpdate time.Time `asn1:"optional"`
2298 RevokedCertificates []pkix.RevokedCertificate `asn1:"optional"`
2299 Extensions []pkix.Extension `asn1:"tag:0,optional,explicit"`
2302 // CreateRevocationList creates a new X.509 v2 [Certificate] Revocation List,
2303 // according to RFC 5280, based on template.
2305 // The CRL is signed by priv which should be the private key associated with
2306 // the public key in the issuer certificate.
2308 // The issuer may not be nil, and the crlSign bit must be set in [KeyUsage] in
2309 // order to use it as a CRL issuer.
2311 // The issuer distinguished name CRL field and authority key identifier
2312 // extension are populated using the issuer certificate. issuer must have
2313 // SubjectKeyId set.
2314 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2315 if template == nil {
2316 return nil, errors.New("x509: template can not be nil")
2319 return nil, errors.New("x509: issuer can not be nil")
2321 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2322 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2324 if len(issuer.SubjectKeyId) == 0 {
2325 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2327 if template.NextUpdate.Before(template.ThisUpdate) {
2328 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2330 if template.Number == nil {
2331 return nil, errors.New("x509: template contains nil Number field")
2334 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2339 var revokedCerts []pkix.RevokedCertificate
2340 // Only process the deprecated RevokedCertificates field if it is populated
2341 // and the new RevokedCertificateEntries field is not populated.
2342 if len(template.RevokedCertificates) > 0 && len(template.RevokedCertificateEntries) == 0 {
2343 // Force revocation times to UTC per RFC 5280.
2344 revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2345 for i, rc := range template.RevokedCertificates {
2346 rc.RevocationTime = rc.RevocationTime.UTC()
2347 revokedCerts[i] = rc
2350 // Convert the ReasonCode field to a proper extension, and force revocation
2351 // times to UTC per RFC 5280.
2352 revokedCerts = make([]pkix.RevokedCertificate, len(template.RevokedCertificateEntries))
2353 for i, rce := range template.RevokedCertificateEntries {
2354 if rce.SerialNumber == nil {
2355 return nil, errors.New("x509: template contains entry with nil SerialNumber field")
2357 if rce.RevocationTime.IsZero() {
2358 return nil, errors.New("x509: template contains entry with zero RevocationTime field")
2361 rc := pkix.RevokedCertificate{
2362 SerialNumber: rce.SerialNumber,
2363 RevocationTime: rce.RevocationTime.UTC(),
2366 // Copy over any extra extensions, except for a Reason Code extension,
2367 // because we'll synthesize that ourselves to ensure it is correct.
2368 exts := make([]pkix.Extension, 0, len(rce.ExtraExtensions))
2369 for _, ext := range rce.ExtraExtensions {
2370 if ext.Id.Equal(oidExtensionReasonCode) {
2371 return nil, errors.New("x509: template contains entry with ReasonCode ExtraExtension; use ReasonCode field instead")
2373 exts = append(exts, ext)
2376 // Only add a reasonCode extension if the reason is non-zero, as per
2377 // RFC 5280 Section 5.3.1.
2378 if rce.ReasonCode != 0 {
2379 reasonBytes, err := asn1.Marshal(asn1.Enumerated(rce.ReasonCode))
2384 exts = append(exts, pkix.Extension{
2385 Id: oidExtensionReasonCode,
2391 rc.Extensions = exts
2393 revokedCerts[i] = rc
2397 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2402 if numBytes := template.Number.Bytes(); len(numBytes) > 20 || (len(numBytes) == 20 && numBytes[0]&0x80 != 0) {
2403 return nil, errors.New("x509: CRL number exceeds 20 octets")
2405 crlNum, err := asn1.Marshal(template.Number)
2410 // Correctly use the issuer's subject sequence if one is specified.
2411 issuerSubject, err := subjectBytes(issuer)
2416 tbsCertList := tbsCertificateList{
2418 Signature: signatureAlgorithm,
2419 Issuer: asn1.RawValue{FullBytes: issuerSubject},
2420 ThisUpdate: template.ThisUpdate.UTC(),
2421 NextUpdate: template.NextUpdate.UTC(),
2422 Extensions: []pkix.Extension{
2424 Id: oidExtensionAuthorityKeyId,
2428 Id: oidExtensionCRLNumber,
2433 if len(revokedCerts) > 0 {
2434 tbsCertList.RevokedCertificates = revokedCerts
2437 if len(template.ExtraExtensions) > 0 {
2438 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2441 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2446 // Optimization to only marshal this struct once, when signing and
2447 // then embedding in certificateList below.
2448 tbsCertList.Raw = tbsCertListContents
2450 input := tbsCertListContents
2453 h.Write(tbsCertListContents)
2456 var signerOpts crypto.SignerOpts = hashFunc
2457 if template.SignatureAlgorithm.isRSAPSS() {
2458 signerOpts = &rsa.PSSOptions{
2459 SaltLength: rsa.PSSSaltLengthEqualsHash,
2464 signature, err := priv.Sign(rand, input, signerOpts)
2469 return asn1.Marshal(certificateList{
2470 TBSCertList: tbsCertList,
2471 SignatureAlgorithm: signatureAlgorithm,
2472 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2476 // CheckSignatureFrom verifies that the signature on rl is a valid signature
2478 func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error {
2479 if parent.Version == 3 && !parent.BasicConstraintsValid ||
2480 parent.BasicConstraintsValid && !parent.IsCA {
2481 return ConstraintViolationError{}
2484 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCRLSign == 0 {
2485 return ConstraintViolationError{}
2488 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
2489 return ErrUnsupportedAlgorithm
2492 return parent.CheckSignature(rl.SignatureAlgorithm, rl.RawTBSRevocationList, rl.Signature)