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 "crypto/go.cypherpunks.ru/gogost/v5/gost3410"
53 "golang.org/x/crypto/cryptobyte"
54 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
57 func reverseBytes(d []byte) {
58 for i, j := 0, len(d)-1; i < j; i, j = i+1, j-1 {
59 d[i], d[j] = d[j], d[i]
63 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
65 type pkixPublicKey struct {
66 Algo pkix.AlgorithmIdentifier
67 BitString asn1.BitString
70 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form. The encoded
71 // public key is a SubjectPublicKeyInfo structure (see RFC 5280, Section 4.1).
73 // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey,
74 // ed25519.PublicKey (not a pointer), or *ecdh.PublicKey (for X25519).
75 // More types might be supported in the future.
77 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
78 func ParsePKIXPublicKey(derBytes []byte) (pub any, err error) {
80 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
81 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
82 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
85 } else if len(rest) != 0 {
86 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
88 return parsePublicKey(&pki)
91 func marshalPublicKey(pub any) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
92 switch pub := pub.(type) {
94 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
99 return nil, pkix.AlgorithmIdentifier{}, err
101 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
102 // This is a NULL parameters value which is required by
103 // RFC 3279, Section 2.3.1.
104 publicKeyAlgorithm.Parameters = asn1.NullRawValue
105 case *ecdsa.PublicKey:
106 oid, ok := oidFromNamedCurve(pub.Curve)
108 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
110 if !pub.Curve.IsOnCurve(pub.X, pub.Y) {
111 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: invalid elliptic curve public key")
113 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
114 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
115 var paramBytes []byte
116 paramBytes, err = asn1.Marshal(oid)
120 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
121 case ed25519.PublicKey:
123 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
124 case *ecdh.PublicKey:
125 publicKeyBytes = pub.Bytes()
126 if pub.Curve() == ecdh.X25519() {
127 publicKeyAlgorithm.Algorithm = oidPublicKeyX25519
129 oid, ok := oidFromECDHCurve(pub.Curve())
131 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
133 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
134 var paramBytes []byte
135 paramBytes, err = asn1.Marshal(oid)
139 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
141 case *gost3410.PublicKey:
142 builder := cryptobyte.NewBuilder(nil)
143 builder.AddASN1OctetString(pub.Raw())
144 publicKeyBytes, err = builder.Bytes()
148 params := GostR341012PublicKeyParameters{}
150 case "id-GostR3410-2001-CryptoPro-A-ParamSet":
151 publicKeyAlgorithm.Algorithm = oidTc26Gost341012256
152 params.PublicKeyParamSet = oidGostR34102001CryptoProAParamSet
153 params.DigestParamSet = oidTc26Gost34112012256
154 case "id-GostR3410-2001-CryptoPro-B-ParamSet":
155 publicKeyAlgorithm.Algorithm = oidTc26Gost341012256
156 params.PublicKeyParamSet = oidGostR34102001CryptoProBParamSet
157 params.DigestParamSet = oidTc26Gost34112012256
158 case "id-GostR3410-2001-CryptoPro-C-ParamSet":
159 publicKeyAlgorithm.Algorithm = oidTc26Gost341012256
160 params.PublicKeyParamSet = oidGostR34102001CryptoProCParamSet
161 params.DigestParamSet = oidTc26Gost34112012256
162 case "id-GostR3410-2001-CryptoPro-XchA-ParamSet":
163 publicKeyAlgorithm.Algorithm = oidTc26Gost341012256
164 params.PublicKeyParamSet = oidGostR34102001CryptoProXchAParamSet
165 params.DigestParamSet = oidTc26Gost34112012256
166 case "id-GostR3410-2001-CryptoPro-XchB-ParamSet":
167 publicKeyAlgorithm.Algorithm = oidTc26Gost341012256
168 params.PublicKeyParamSet = oidGostR34102001CryptoProXchBParamSet
169 params.DigestParamSet = oidTc26Gost34112012256
170 case "id-tc26-gost-3410-12-256-paramSetA":
171 publicKeyAlgorithm.Algorithm = oidTc26Gost341012256
172 params.PublicKeyParamSet = oidTc26Gost341012256ParamSetA
173 case "id-tc26-gost-3410-12-256-paramSetB":
174 publicKeyAlgorithm.Algorithm = oidTc26Gost341012256
175 params.PublicKeyParamSet = oidTc26Gost341012256ParamSetB
176 case "id-tc26-gost-3410-12-256-paramSetC":
177 publicKeyAlgorithm.Algorithm = oidTc26Gost341012256
178 params.PublicKeyParamSet = oidTc26Gost341012256ParamSetC
179 case "id-tc26-gost-3410-12-256-paramSetD":
180 publicKeyAlgorithm.Algorithm = oidTc26Gost341012256
181 params.PublicKeyParamSet = oidTc26Gost341012256ParamSetD
182 case "id-tc26-gost-3410-12-512-paramSetA":
183 publicKeyAlgorithm.Algorithm = oidTc26Gost341012512
184 params.PublicKeyParamSet = oidTc26Gost341012512ParamSetA
185 case "id-tc26-gost-3410-12-512-paramSetB":
186 publicKeyAlgorithm.Algorithm = oidTc26Gost341012512
187 params.PublicKeyParamSet = oidTc26Gost341012512ParamSetB
188 case "id-tc26-gost-3410-12-512-paramSetC":
189 publicKeyAlgorithm.Algorithm = oidTc26Gost341012512
190 params.PublicKeyParamSet = oidTc26Gost341012512ParamSetC
192 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported GOST elliptic curve")
194 publicKeyAlgorithm.Parameters.FullBytes, err = asn1.Marshal(params)
199 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
202 return publicKeyBytes, publicKeyAlgorithm, nil
205 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
206 // The encoded public key is a SubjectPublicKeyInfo structure
207 // (see RFC 5280, Section 4.1).
209 // The following key types are currently supported: *rsa.PublicKey,
210 // *ecdsa.PublicKey, ed25519.PublicKey (not a pointer), and *ecdh.PublicKey.
211 // Unsupported key types result in an error.
213 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
214 func MarshalPKIXPublicKey(pub any) ([]byte, error) {
215 var publicKeyBytes []byte
216 var publicKeyAlgorithm pkix.AlgorithmIdentifier
219 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
223 pkix := pkixPublicKey{
224 Algo: publicKeyAlgorithm,
225 BitString: asn1.BitString{
226 Bytes: publicKeyBytes,
227 BitLength: 8 * len(publicKeyBytes),
231 ret, _ := asn1.Marshal(pkix)
235 // These structures reflect the ASN.1 structure of X.509 certificates.:
237 type certificate struct {
238 TBSCertificate tbsCertificate
239 SignatureAlgorithm pkix.AlgorithmIdentifier
240 SignatureValue asn1.BitString
243 type tbsCertificate struct {
245 Version int `asn1:"optional,explicit,default:0,tag:0"`
246 SerialNumber *big.Int
247 SignatureAlgorithm pkix.AlgorithmIdentifier
250 Subject asn1.RawValue
251 PublicKey publicKeyInfo
252 UniqueId asn1.BitString `asn1:"optional,tag:1"`
253 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
254 Extensions []pkix.Extension `asn1:"omitempty,optional,explicit,tag:3"`
257 type dsaAlgorithmParameters struct {
261 type validity struct {
262 NotBefore, NotAfter time.Time
265 type publicKeyInfo struct {
267 Algorithm pkix.AlgorithmIdentifier
268 PublicKey asn1.BitString
272 type authKeyId struct {
273 Id []byte `asn1:"optional,tag:0"`
276 type SignatureAlgorithm int
279 UnknownSignatureAlgorithm SignatureAlgorithm = iota
281 MD2WithRSA // Unsupported.
282 MD5WithRSA // Only supported for signing, not verification.
283 SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
287 DSAWithSHA1 // Unsupported.
288 DSAWithSHA256 // Unsupported.
289 ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
301 func (algo SignatureAlgorithm) isRSAPSS() bool {
303 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
310 func (algo SignatureAlgorithm) String() string {
311 for _, details := range signatureAlgorithmDetails {
312 if details.algo == algo {
316 return strconv.Itoa(int(algo))
319 type PublicKeyAlgorithm int
322 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
324 DSA // Only supported for parsing.
330 var publicKeyAlgoName = [...]string{
338 func (algo PublicKeyAlgorithm) String() string {
339 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
340 return publicKeyAlgoName[algo]
342 return strconv.Itoa(int(algo))
345 // OIDs for signature algorithms
347 // pkcs-1 OBJECT IDENTIFIER ::= {
348 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
350 // RFC 3279 2.2.1 RSA Signature Algorithms
352 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
354 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
356 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
358 // dsaWithSha1 OBJECT IDENTIFIER ::= {
359 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
361 // RFC 3279 2.2.3 ECDSA Signature Algorithm
363 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
364 // iso(1) member-body(2) us(840) ansi-x962(10045)
365 // signatures(4) ecdsa-with-SHA1(1)}
367 // RFC 4055 5 PKCS #1 Version 1.5
369 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
371 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
373 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
375 // RFC 5758 3.1 DSA Signature Algorithms
377 // dsaWithSha256 OBJECT IDENTIFIER ::= {
378 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
379 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
381 // RFC 5758 3.2 ECDSA Signature Algorithm
383 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
384 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
386 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
387 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
389 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
390 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
392 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
394 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
396 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
397 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
398 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
399 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
400 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
401 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
402 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
403 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
404 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
405 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
406 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
407 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
408 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
409 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
411 oidTc26Gost341012256 = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 1, 1, 1}
412 oidTc26Gost341012512 = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 1, 1, 2}
413 oidTc26Gost34112012256 = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 1, 2, 2}
414 oidTc26Gost34112012512 = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 1, 2, 3}
415 oidTc26Gost341012256Signature = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 1, 3, 2}
416 oidTc26Gost341012512Signature = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 1, 3, 3}
417 oidGostR34102001CryptoProAParamSet = asn1.ObjectIdentifier{1, 2, 643, 2, 2, 35, 1}
418 oidGostR34102001CryptoProBParamSet = asn1.ObjectIdentifier{1, 2, 643, 2, 2, 35, 2}
419 oidGostR34102001CryptoProCParamSet = asn1.ObjectIdentifier{1, 2, 643, 2, 2, 35, 3}
420 oidGostR34102001CryptoProXchAParamSet = asn1.ObjectIdentifier{1, 2, 643, 2, 2, 36, 0}
421 oidGostR34102001CryptoProXchBParamSet = asn1.ObjectIdentifier{1, 2, 643, 2, 2, 36, 1}
422 oidTc26Gost341012256ParamSetA = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 2, 1, 1, 1}
423 oidTc26Gost341012256ParamSetB = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 2, 1, 1, 2}
424 oidTc26Gost341012256ParamSetC = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 2, 1, 1, 3}
425 oidTc26Gost341012256ParamSetD = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 2, 1, 1, 4}
426 oidTc26Gost341012512ParamSetA = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 2, 1, 2, 1}
427 oidTc26Gost341012512ParamSetB = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 2, 1, 2, 2}
428 oidTc26Gost341012512ParamSetC = asn1.ObjectIdentifier{1, 2, 643, 7, 1, 2, 1, 2, 3}
430 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
431 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
432 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
434 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
436 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
437 // but it's specified by ISO. Microsoft's makecert.exe has been known
438 // to produce certificates with this OID.
439 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
442 var signatureAlgorithmDetails = []struct {
443 algo SignatureAlgorithm
445 oid asn1.ObjectIdentifier
446 pubKeyAlgo PublicKeyAlgorithm
449 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
450 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
451 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
452 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
453 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
454 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
455 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
456 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
457 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
458 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
459 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
460 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
461 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
462 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
463 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
464 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
465 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
466 {GOST256, "GOST256", oidTc26Gost341012256Signature, GOST, crypto.GOSTR34112012256},
467 {GOST512, "GOST512", oidTc26Gost341012512Signature, GOST, crypto.GOSTR34112012512},
470 // hashToPSSParameters contains the DER encoded RSA PSS parameters for the
471 // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
472 // The parameters contain the following values:
473 // - hashAlgorithm contains the associated hash identifier with NULL parameters
474 // - maskGenAlgorithm always contains the default mgf1SHA1 identifier
475 // - saltLength contains the length of the associated hash
476 // - trailerField always contains the default trailerFieldBC value
477 var hashToPSSParameters = map[crypto.Hash]asn1.RawValue{
478 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}},
479 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}},
480 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}},
483 // pssParameters reflects the parameters in an AlgorithmIdentifier that
484 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
485 type pssParameters struct {
486 // The following three fields are not marked as
487 // optional because the default values specify SHA-1,
488 // which is no longer suitable for use in signatures.
489 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
490 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
491 SaltLength int `asn1:"explicit,tag:2"`
492 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
495 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
496 if ai.Algorithm.Equal(oidSignatureEd25519) {
497 // RFC 8410, Section 3
498 // > For all of the OIDs, the parameters MUST be absent.
499 if len(ai.Parameters.FullBytes) != 0 {
500 return UnknownSignatureAlgorithm
504 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
505 for _, details := range signatureAlgorithmDetails {
506 if ai.Algorithm.Equal(details.oid) {
510 return UnknownSignatureAlgorithm
513 // RSA PSS is special because it encodes important parameters
514 // in the Parameters.
516 var params pssParameters
517 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
518 return UnknownSignatureAlgorithm
521 var mgf1HashFunc pkix.AlgorithmIdentifier
522 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
523 return UnknownSignatureAlgorithm
526 // PSS is greatly overburdened with options. This code forces them into
527 // three buckets by requiring that the MGF1 hash function always match the
528 // message hash function (as recommended in RFC 3447, Section 8.1), that the
529 // salt length matches the hash length, and that the trailer field has the
531 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
532 !params.MGF.Algorithm.Equal(oidMGF1) ||
533 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
534 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
535 params.TrailerField != 1 {
536 return UnknownSignatureAlgorithm
540 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
541 return SHA256WithRSAPSS
542 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
543 return SHA384WithRSAPSS
544 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
545 return SHA512WithRSAPSS
548 return UnknownSignatureAlgorithm
552 // RFC 3279, 2.3 Public Key Algorithms
554 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
555 // rsadsi(113549) pkcs(1) 1 }
557 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
559 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
560 // x9-57(10040) x9cm(4) 1 }
561 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
562 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
563 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
565 // id-ecPublicKey OBJECT IDENTIFIER ::= {
566 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
567 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
568 // RFC 8410, Section 3
570 // id-X25519 OBJECT IDENTIFIER ::= { 1 3 101 110 }
571 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
572 oidPublicKeyX25519 = asn1.ObjectIdentifier{1, 3, 101, 110}
573 oidPublicKeyEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
575 oidPublicKeyGOST256 = oidTc26Gost341012256
576 oidPublicKeyGOST512 = oidTc26Gost341012512
579 // getPublicKeyAlgorithmFromOID returns the exposed PublicKeyAlgorithm
580 // identifier for public key types supported in certificates and CSRs. Marshal
581 // and Parse functions may support a different set of public key types.
582 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
584 case oid.Equal(oidPublicKeyRSA):
586 case oid.Equal(oidPublicKeyDSA):
588 case oid.Equal(oidPublicKeyECDSA):
590 case oid.Equal(oidPublicKeyEd25519):
592 case oid.Equal(oidPublicKeyGOST256):
594 case oid.Equal(oidPublicKeyGOST512):
597 return UnknownPublicKeyAlgorithm
600 // RFC 5480, 2.1.1.1. Named Curve
602 // secp224r1 OBJECT IDENTIFIER ::= {
603 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
605 // secp256r1 OBJECT IDENTIFIER ::= {
606 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
609 // secp384r1 OBJECT IDENTIFIER ::= {
610 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
612 // secp521r1 OBJECT IDENTIFIER ::= {
613 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
615 // NB: secp256r1 is equivalent to prime256v1
617 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
618 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
619 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
620 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
623 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
625 case oid.Equal(oidNamedCurveP224):
626 return elliptic.P224()
627 case oid.Equal(oidNamedCurveP256):
628 return elliptic.P256()
629 case oid.Equal(oidNamedCurveP384):
630 return elliptic.P384()
631 case oid.Equal(oidNamedCurveP521):
632 return elliptic.P521()
637 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
639 case elliptic.P224():
640 return oidNamedCurveP224, true
641 case elliptic.P256():
642 return oidNamedCurveP256, true
643 case elliptic.P384():
644 return oidNamedCurveP384, true
645 case elliptic.P521():
646 return oidNamedCurveP521, true
652 func oidFromECDHCurve(curve ecdh.Curve) (asn1.ObjectIdentifier, bool) {
655 return oidPublicKeyX25519, true
657 return oidNamedCurveP256, true
659 return oidNamedCurveP384, true
661 return oidNamedCurveP521, true
667 // KeyUsage represents the set of actions that are valid for a given key. It's
668 // a bitmap of the KeyUsage* constants.
672 KeyUsageDigitalSignature KeyUsage = 1 << iota
673 KeyUsageContentCommitment
674 KeyUsageKeyEncipherment
675 KeyUsageDataEncipherment
683 // RFC 5280, 4.2.1.12 Extended Key Usage
685 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
687 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
689 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
690 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
691 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
692 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
693 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
694 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
696 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
697 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
698 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
699 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
700 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
701 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
702 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
703 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
704 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
705 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
706 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
707 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
708 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
709 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
712 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
713 // Each of the ExtKeyUsage* constants define a unique action.
717 ExtKeyUsageAny ExtKeyUsage = iota
718 ExtKeyUsageServerAuth
719 ExtKeyUsageClientAuth
720 ExtKeyUsageCodeSigning
721 ExtKeyUsageEmailProtection
722 ExtKeyUsageIPSECEndSystem
723 ExtKeyUsageIPSECTunnel
725 ExtKeyUsageTimeStamping
726 ExtKeyUsageOCSPSigning
727 ExtKeyUsageMicrosoftServerGatedCrypto
728 ExtKeyUsageNetscapeServerGatedCrypto
729 ExtKeyUsageMicrosoftCommercialCodeSigning
730 ExtKeyUsageMicrosoftKernelCodeSigning
733 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
734 var extKeyUsageOIDs = []struct {
735 extKeyUsage ExtKeyUsage
736 oid asn1.ObjectIdentifier
738 {ExtKeyUsageAny, oidExtKeyUsageAny},
739 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
740 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
741 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
742 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
743 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
744 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
745 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
746 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
747 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
748 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
749 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
750 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
751 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
754 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
755 for _, pair := range extKeyUsageOIDs {
756 if oid.Equal(pair.oid) {
757 return pair.extKeyUsage, true
763 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
764 for _, pair := range extKeyUsageOIDs {
765 if eku == pair.extKeyUsage {
766 return pair.oid, true
772 // A Certificate represents an X.509 certificate.
773 type Certificate struct {
774 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
775 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
776 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
777 RawSubject []byte // DER encoded Subject
778 RawIssuer []byte // DER encoded Issuer
781 SignatureAlgorithm SignatureAlgorithm
783 PublicKeyAlgorithm PublicKeyAlgorithm
787 SerialNumber *big.Int
790 NotBefore, NotAfter time.Time // Validity bounds.
793 // Extensions contains raw X.509 extensions. When parsing certificates,
794 // this can be used to extract non-critical extensions that are not
795 // parsed by this package. When marshaling certificates, the Extensions
796 // field is ignored, see ExtraExtensions.
797 Extensions []pkix.Extension
799 // ExtraExtensions contains extensions to be copied, raw, into any
800 // marshaled certificates. Values override any extensions that would
801 // otherwise be produced based on the other fields. The ExtraExtensions
802 // field is not populated when parsing certificates, see Extensions.
803 ExtraExtensions []pkix.Extension
805 // UnhandledCriticalExtensions contains a list of extension IDs that
806 // were not (fully) processed when parsing. Verify will fail if this
807 // slice is non-empty, unless verification is delegated to an OS
808 // library which understands all the critical extensions.
810 // Users can access these extensions using Extensions and can remove
811 // elements from this slice if they believe that they have been
813 UnhandledCriticalExtensions []asn1.ObjectIdentifier
815 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
816 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
818 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
819 // and MaxPathLenZero are valid.
820 BasicConstraintsValid bool
823 // MaxPathLen and MaxPathLenZero indicate the presence and
824 // value of the BasicConstraints' "pathLenConstraint".
826 // When parsing a certificate, a positive non-zero MaxPathLen
827 // means that the field was specified, -1 means it was unset,
828 // and MaxPathLenZero being true mean that the field was
829 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
830 // should be treated equivalent to -1 (unset).
832 // When generating a certificate, an unset pathLenConstraint
833 // can be requested with either MaxPathLen == -1 or using the
834 // zero value for both MaxPathLen and MaxPathLenZero.
836 // MaxPathLenZero indicates that BasicConstraintsValid==true
837 // and MaxPathLen==0 should be interpreted as an actual
838 // maximum path length of zero. Otherwise, that combination is
839 // interpreted as MaxPathLen not being set.
843 AuthorityKeyId []byte
845 // RFC 5280, 4.2.2.1 (Authority Information Access)
847 IssuingCertificateURL []string
849 // Subject Alternate Name values. (Note that these values may not be valid
850 // if invalid values were contained within a parsed certificate. For
851 // example, an element of DNSNames may not be a valid DNS domain name.)
853 EmailAddresses []string
858 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
859 PermittedDNSDomains []string
860 ExcludedDNSDomains []string
861 PermittedIPRanges []*net.IPNet
862 ExcludedIPRanges []*net.IPNet
863 PermittedEmailAddresses []string
864 ExcludedEmailAddresses []string
865 PermittedURIDomains []string
866 ExcludedURIDomains []string
868 // CRL Distribution Points
869 CRLDistributionPoints []string
871 PolicyIdentifiers []asn1.ObjectIdentifier
874 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
875 // involves algorithms that are not currently implemented.
876 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
878 // An InsecureAlgorithmError indicates that the SignatureAlgorithm used to
879 // generate the signature is not secure, and the signature has been rejected.
881 // To temporarily restore support for SHA-1 signatures, include the value
882 // "x509sha1=1" in the GODEBUG environment variable. Note that this option will
883 // be removed in a future release.
884 type InsecureAlgorithmError SignatureAlgorithm
886 func (e InsecureAlgorithmError) Error() string {
888 if SignatureAlgorithm(e) == SHA1WithRSA || SignatureAlgorithm(e) == ECDSAWithSHA1 {
889 override = " (temporarily override with GODEBUG=x509sha1=1)"
891 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e)) + override
894 // ConstraintViolationError results when a requested usage is not permitted by
895 // a certificate. For example: checking a signature when the public key isn't a
896 // certificate signing key.
897 type ConstraintViolationError struct{}
899 func (ConstraintViolationError) Error() string {
900 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
903 func (c *Certificate) Equal(other *Certificate) bool {
904 if c == nil || other == nil {
907 return bytes.Equal(c.Raw, other.Raw)
910 func (c *Certificate) hasSANExtension() bool {
911 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
914 // CheckSignatureFrom verifies that the signature on c is a valid signature from parent.
916 // This is a low-level API that performs very limited checks, and not a full
917 // path verifier. Most users should use [Certificate.Verify] instead.
918 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
919 // RFC 5280, 4.2.1.9:
920 // "If the basic constraints extension is not present in a version 3
921 // certificate, or the extension is present but the cA boolean is not
922 // asserted, then the certified public key MUST NOT be used to verify
923 // certificate signatures."
924 if parent.Version == 3 && !parent.BasicConstraintsValid ||
925 parent.BasicConstraintsValid && !parent.IsCA {
926 return ConstraintViolationError{}
929 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
930 return ConstraintViolationError{}
933 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
934 return ErrUnsupportedAlgorithm
937 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature, parent.PublicKey, false)
940 // CheckSignature verifies that signature is a valid signature over signed from
943 // This is a low-level API that performs no validity checks on the certificate.
945 // [MD5WithRSA] signatures are rejected, while [SHA1WithRSA] and [ECDSAWithSHA1]
946 // signatures are currently accepted.
947 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
948 return checkSignature(algo, signed, signature, c.PublicKey, true)
951 func (c *Certificate) hasNameConstraints() bool {
952 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
955 func (c *Certificate) getSANExtension() []byte {
956 for _, e := range c.Extensions {
957 if e.Id.Equal(oidExtensionSubjectAltName) {
964 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {
965 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
968 var x509sha1 = godebug.New("x509sha1")
970 // checkSignature verifies that signature is a valid signature over signed from
971 // a crypto.PublicKey.
972 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error) {
973 var hashType crypto.Hash
974 var pubKeyAlgo PublicKeyAlgorithm
976 for _, details := range signatureAlgorithmDetails {
977 if details.algo == algo {
978 hashType = details.hash
979 pubKeyAlgo = details.pubKeyAlgo
985 if pubKeyAlgo != Ed25519 {
986 return ErrUnsupportedAlgorithm
989 return InsecureAlgorithmError(algo)
991 // SHA-1 signatures are mostly disabled. See go.dev/issue/41682.
992 if !allowSHA1 && x509sha1.Value() != "1" {
993 return InsecureAlgorithmError(algo)
997 if !hashType.Available() {
998 return ErrUnsupportedAlgorithm
1005 switch pub := publicKey.(type) {
1006 case *rsa.PublicKey:
1007 if pubKeyAlgo != RSA {
1008 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1010 if algo.isRSAPSS() {
1011 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
1013 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
1015 case *ecdsa.PublicKey:
1016 if pubKeyAlgo != ECDSA {
1017 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1019 if !ecdsa.VerifyASN1(pub, signed, signature) {
1020 return errors.New("x509: ECDSA verification failure")
1023 case ed25519.PublicKey:
1024 if pubKeyAlgo != Ed25519 {
1025 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1027 if !ed25519.Verify(pub, signed, signature) {
1028 return errors.New("x509: Ed25519 verification failure")
1031 case *gost3410.PublicKey:
1032 if pubKeyAlgo != GOST {
1033 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
1035 reverseBytes(signed)
1036 ok, err := pub.VerifyDigest(signed, signature)
1037 reverseBytes(signed)
1042 return errors.New("x509: GOST verification failure")
1046 return ErrUnsupportedAlgorithm
1049 // CheckCRLSignature checks that the signature in crl is from c.
1051 // Deprecated: Use RevocationList.CheckSignatureFrom instead.
1052 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
1053 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
1054 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
1057 type UnhandledCriticalExtension struct{}
1059 func (h UnhandledCriticalExtension) Error() string {
1060 return "x509: unhandled critical extension"
1063 type basicConstraints struct {
1064 IsCA bool `asn1:"optional"`
1065 MaxPathLen int `asn1:"optional,default:-1"`
1069 type policyInformation struct {
1070 Policy asn1.ObjectIdentifier
1071 // policyQualifiers omitted
1081 // RFC 5280, 4.2.2.1
1082 type authorityInfoAccess struct {
1083 Method asn1.ObjectIdentifier
1084 Location asn1.RawValue
1087 // RFC 5280, 4.2.1.14
1088 type distributionPoint struct {
1089 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
1090 Reason asn1.BitString `asn1:"optional,tag:1"`
1091 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
1094 type distributionPointName struct {
1095 FullName []asn1.RawValue `asn1:"optional,tag:0"`
1096 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
1099 func reverseBitsInAByte(in byte) byte {
1101 b2 := b1>>2&0x33 | b1<<2&0xcc
1102 b3 := b2>>1&0x55 | b2<<1&0xaa
1106 // asn1BitLength returns the bit-length of bitString by considering the
1107 // most-significant bit in a byte to be the "first" bit. This convention
1108 // matches ASN.1, but differs from almost everything else.
1109 func asn1BitLength(bitString []byte) int {
1110 bitLen := len(bitString) * 8
1112 for i := range bitString {
1113 b := bitString[len(bitString)-i-1]
1115 for bit := uint(0); bit < 8; bit++ {
1116 if (b>>bit)&1 == 1 {
1127 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1128 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1129 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1130 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1131 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1132 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1133 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1134 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1135 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1136 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1137 oidExtensionCRLNumber = []int{2, 5, 29, 20}
1141 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1142 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1145 // oidInExtensions reports whether an extension with the given oid exists in
1147 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1148 for _, e := range extensions {
1149 if e.Id.Equal(oid) {
1156 // marshalSANs marshals a list of addresses into a the contents of an X.509
1157 // SubjectAlternativeName extension.
1158 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1159 var rawValues []asn1.RawValue
1160 for _, name := range dnsNames {
1161 if err := isIA5String(name); err != nil {
1164 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1166 for _, email := range emailAddresses {
1167 if err := isIA5String(email); err != nil {
1170 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1172 for _, rawIP := range ipAddresses {
1173 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1178 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1180 for _, uri := range uris {
1181 uriStr := uri.String()
1182 if err := isIA5String(uriStr); err != nil {
1185 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1187 return asn1.Marshal(rawValues)
1190 func isIA5String(s string) error {
1191 for _, r := range s {
1192 // Per RFC5280 "IA5String is limited to the set of ASCII characters"
1193 if r > unicode.MaxASCII {
1194 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1201 func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1202 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1205 if template.KeyUsage != 0 &&
1206 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1207 ret[n], err = marshalKeyUsage(template.KeyUsage)
1214 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1215 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1216 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
1223 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1224 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
1231 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1232 ret[n].Id = oidExtensionSubjectKeyId
1233 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1240 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1241 ret[n].Id = oidExtensionAuthorityKeyId
1242 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1249 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1250 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1251 ret[n].Id = oidExtensionAuthorityInfoAccess
1252 var aiaValues []authorityInfoAccess
1253 for _, name := range template.OCSPServer {
1254 aiaValues = append(aiaValues, authorityInfoAccess{
1255 Method: oidAuthorityInfoAccessOcsp,
1256 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1259 for _, name := range template.IssuingCertificateURL {
1260 aiaValues = append(aiaValues, authorityInfoAccess{
1261 Method: oidAuthorityInfoAccessIssuers,
1262 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1265 ret[n].Value, err = asn1.Marshal(aiaValues)
1272 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1273 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1274 ret[n].Id = oidExtensionSubjectAltName
1275 // From RFC 5280, Section 4.2.1.6:
1276 // “If the subject field contains an empty sequence ... then
1277 // subjectAltName extension ... is marked as critical”
1278 ret[n].Critical = subjectIsEmpty
1279 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1286 if len(template.PolicyIdentifiers) > 0 &&
1287 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1288 ret[n], err = marshalCertificatePolicies(template.PolicyIdentifiers)
1295 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1296 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1297 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1298 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1299 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1300 ret[n].Id = oidExtensionNameConstraints
1301 ret[n].Critical = template.PermittedDNSDomainsCritical
1303 ipAndMask := func(ipNet *net.IPNet) []byte {
1304 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1305 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1306 ipAndMask = append(ipAndMask, maskedIP...)
1307 ipAndMask = append(ipAndMask, ipNet.Mask...)
1311 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1312 var b cryptobyte.Builder
1314 for _, name := range dns {
1315 if err = isIA5String(name); err != nil {
1319 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1320 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1321 b.AddBytes([]byte(name))
1326 for _, ipNet := range ips {
1327 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1328 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1329 b.AddBytes(ipAndMask(ipNet))
1334 for _, email := range emails {
1335 if err = isIA5String(email); err != nil {
1339 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1340 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1341 b.AddBytes([]byte(email))
1346 for _, uriDomain := range uriDomains {
1347 if err = isIA5String(uriDomain); err != nil {
1351 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1352 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1353 b.AddBytes([]byte(uriDomain))
1361 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1366 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1371 var b cryptobyte.Builder
1372 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1373 if len(permitted) > 0 {
1374 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1375 b.AddBytes(permitted)
1379 if len(excluded) > 0 {
1380 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1381 b.AddBytes(excluded)
1386 ret[n].Value, err = b.Bytes()
1393 if len(template.CRLDistributionPoints) > 0 &&
1394 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1395 ret[n].Id = oidExtensionCRLDistributionPoints
1397 var crlDp []distributionPoint
1398 for _, name := range template.CRLDistributionPoints {
1399 dp := distributionPoint{
1400 DistributionPoint: distributionPointName{
1401 FullName: []asn1.RawValue{
1402 {Tag: 6, Class: 2, Bytes: []byte(name)},
1406 crlDp = append(crlDp, dp)
1409 ret[n].Value, err = asn1.Marshal(crlDp)
1416 // Adding another extension here? Remember to update the maximum number
1417 // of elements in the make() at the top of the function and the list of
1418 // template fields used in CreateCertificate documentation.
1420 return append(ret[:n], template.ExtraExtensions...), nil
1423 func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
1424 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
1427 a[0] = reverseBitsInAByte(byte(ku))
1428 a[1] = reverseBitsInAByte(byte(ku >> 8))
1437 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1441 func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
1442 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
1444 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
1445 for i, u := range extUsages {
1446 if oid, ok := oidFromExtKeyUsage(u); ok {
1449 return ext, errors.New("x509: unknown extended key usage")
1453 copy(oids[len(extUsages):], unknownUsages)
1456 ext.Value, err = asn1.Marshal(oids)
1460 func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
1461 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
1462 // Leaving MaxPathLen as zero indicates that no maximum path
1463 // length is desired, unless MaxPathLenZero is set. A value of
1464 // -1 causes encoding/asn1 to omit the value as desired.
1465 if maxPathLen == 0 && !maxPathLenZero {
1469 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
1473 func marshalCertificatePolicies(policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
1474 ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
1475 policies := make([]policyInformation, len(policyIdentifiers))
1476 for i, policy := range policyIdentifiers {
1477 policies[i].Policy = policy
1480 ext.Value, err = asn1.Marshal(policies)
1484 func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
1485 var ret []pkix.Extension
1487 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1488 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1489 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1494 ret = append(ret, pkix.Extension{
1495 Id: oidExtensionSubjectAltName,
1500 return append(ret, template.ExtraExtensions...), nil
1503 func subjectBytes(cert *Certificate) ([]byte, error) {
1504 if len(cert.RawSubject) > 0 {
1505 return cert.RawSubject, nil
1508 return asn1.Marshal(cert.Subject.ToRDNSequence())
1511 // signingParamsForPublicKey returns the parameters to use for signing with
1512 // priv. If requestedSigAlgo is not zero then it overrides the default
1513 // signature algorithm.
1514 func signingParamsForPublicKey(pub any, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1515 var pubType PublicKeyAlgorithm
1517 switch pub := pub.(type) {
1518 case *rsa.PublicKey:
1520 hashFunc = crypto.SHA256
1521 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1522 sigAlgo.Parameters = asn1.NullRawValue
1524 case *ecdsa.PublicKey:
1528 case elliptic.P224(), elliptic.P256():
1529 hashFunc = crypto.SHA256
1530 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1531 case elliptic.P384():
1532 hashFunc = crypto.SHA384
1533 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1534 case elliptic.P521():
1535 hashFunc = crypto.SHA512
1536 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1538 err = errors.New("x509: unknown elliptic curve")
1541 case ed25519.PublicKey:
1543 sigAlgo.Algorithm = oidSignatureEd25519
1545 case *gost3410.PublicKey:
1547 switch pub.C.PointSize() {
1549 hashFunc = crypto.GOSTR34112012256
1550 sigAlgo.Algorithm = oidTc26Gost341012256Signature
1552 hashFunc = crypto.GOSTR34112012512
1553 sigAlgo.Algorithm = oidTc26Gost341012512Signature
1557 err = errors.New("x509: only RSA, ECDSA, Ed25519 and GOST keys supported")
1564 if requestedSigAlgo == 0 {
1569 for _, details := range signatureAlgorithmDetails {
1570 if details.algo == requestedSigAlgo {
1571 if details.pubKeyAlgo != pubType {
1572 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
1575 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
1576 if hashFunc == 0 && pubType != Ed25519 {
1577 err = errors.New("x509: cannot sign with hash function requested")
1580 if hashFunc == crypto.MD5 {
1581 err = errors.New("x509: signing with MD5 is not supported")
1584 if requestedSigAlgo.isRSAPSS() {
1585 sigAlgo.Parameters = hashToPSSParameters[hashFunc]
1593 err = errors.New("x509: unknown SignatureAlgorithm")
1599 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
1600 // just an empty SEQUENCE.
1601 var emptyASN1Subject = []byte{0x30, 0}
1603 // CreateCertificate creates a new X.509 v3 certificate based on a template.
1604 // The following members of template are currently used:
1607 // - BasicConstraintsValid
1608 // - CRLDistributionPoints
1611 // - ExcludedDNSDomains
1612 // - ExcludedEmailAddresses
1613 // - ExcludedIPRanges
1614 // - ExcludedURIDomains
1616 // - ExtraExtensions
1619 // - IssuingCertificateURL
1626 // - PermittedDNSDomains
1627 // - PermittedDNSDomainsCritical
1628 // - PermittedEmailAddresses
1629 // - PermittedIPRanges
1630 // - PermittedURIDomains
1631 // - PolicyIdentifiers
1633 // - SignatureAlgorithm
1637 // - UnknownExtKeyUsage
1639 // The certificate is signed by parent. If parent is equal to template then the
1640 // certificate is self-signed. The parameter pub is the public key of the
1641 // certificate to be generated and priv is the private key of the signer.
1643 // The returned slice is the certificate in DER encoding.
1645 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
1646 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
1647 // crypto.Signer with a supported public key.
1649 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
1650 // unless the resulting certificate is self-signed. Otherwise the value from
1651 // template will be used.
1653 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
1654 // will be generated from the hash of the public key.
1655 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) {
1656 key, ok := priv.(crypto.Signer)
1658 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1661 if template.SerialNumber == nil {
1662 return nil, errors.New("x509: no SerialNumber given")
1665 // RFC 5280 Section 4.1.2.2: serial number must positive
1667 // We _should_ also restrict serials to <= 20 octets, but it turns out a lot of people
1668 // get this wrong, in part because the encoding can itself alter the length of the
1669 // serial. For now we accept these non-conformant serials.
1670 if template.SerialNumber.Sign() == -1 {
1671 return nil, errors.New("x509: serial number must be positive")
1674 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
1675 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
1678 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1683 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1687 if getPublicKeyAlgorithmFromOID(publicKeyAlgorithm.Algorithm) == UnknownPublicKeyAlgorithm {
1688 return nil, fmt.Errorf("x509: unsupported public key type: %T", pub)
1691 asn1Issuer, err := subjectBytes(parent)
1696 asn1Subject, err := subjectBytes(template)
1701 authorityKeyId := template.AuthorityKeyId
1702 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1703 authorityKeyId = parent.SubjectKeyId
1706 subjectKeyId := template.SubjectKeyId
1707 if len(subjectKeyId) == 0 && template.IsCA {
1708 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
1709 // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
1710 // value of the BIT STRING subjectPublicKey (excluding the tag,
1711 // length, and number of unused bits).
1712 h := sha1.Sum(publicKeyBytes)
1716 // Check that the signer's public key matches the private key, if available.
1717 type privateKey interface {
1718 Equal(crypto.PublicKey) bool
1720 if privPub, ok := key.Public().(privateKey); !ok {
1721 return nil, errors.New("x509: internal error: supported public key does not implement Equal")
1722 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
1723 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
1726 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
1731 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1732 c := tbsCertificate{
1734 SerialNumber: template.SerialNumber,
1735 SignatureAlgorithm: signatureAlgorithm,
1736 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1737 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1738 Subject: asn1.RawValue{FullBytes: asn1Subject},
1739 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1740 Extensions: extensions,
1743 tbsCertContents, err := asn1.Marshal(c)
1747 c.Raw = tbsCertContents
1749 signed := tbsCertContents
1756 var signerOpts crypto.SignerOpts = hashFunc
1757 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
1758 signerOpts = &rsa.PSSOptions{
1759 SaltLength: rsa.PSSSaltLengthEqualsHash,
1764 var signature []byte
1765 signature, err = key.Sign(rand, signed, signerOpts)
1770 signedCert, err := asn1.Marshal(certificate{
1773 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1779 // Check the signature to ensure the crypto.Signer behaved correctly.
1780 if err := checkSignature(getSignatureAlgorithmFromAI(signatureAlgorithm), c.Raw, signature, key.Public(), true); err != nil {
1781 return nil, fmt.Errorf("x509: signature over certificate returned by signer is invalid: %w", err)
1784 return signedCert, nil
1787 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1789 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1791 // pemType is the type of a PEM encoded CRL.
1792 var pemType = "X509 CRL"
1794 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1795 // encoded CRLs will appear where they should be DER encoded, so this function
1796 // will transparently handle PEM encoding as long as there isn't any leading
1799 // Deprecated: Use ParseRevocationList instead.
1800 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1801 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1802 block, _ := pem.Decode(crlBytes)
1803 if block != nil && block.Type == pemType {
1804 crlBytes = block.Bytes
1807 return ParseDERCRL(crlBytes)
1810 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1812 // Deprecated: Use ParseRevocationList instead.
1813 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1814 certList := new(pkix.CertificateList)
1815 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
1817 } else if len(rest) != 0 {
1818 return nil, errors.New("x509: trailing data after CRL")
1820 return certList, nil
1823 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1824 // contains the given list of revoked certificates.
1826 // Deprecated: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
1827 // To generate a standards compliant CRL, use CreateRevocationList instead.
1828 func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1829 key, ok := priv.(crypto.Signer)
1831 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1834 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
1839 // Force revocation times to UTC per RFC 5280.
1840 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
1841 for i, rc := range revokedCerts {
1842 rc.RevocationTime = rc.RevocationTime.UTC()
1843 revokedCertsUTC[i] = rc
1846 tbsCertList := pkix.TBSCertificateList{
1848 Signature: signatureAlgorithm,
1849 Issuer: c.Subject.ToRDNSequence(),
1850 ThisUpdate: now.UTC(),
1851 NextUpdate: expiry.UTC(),
1852 RevokedCertificates: revokedCertsUTC,
1856 if len(c.SubjectKeyId) > 0 {
1857 var aki pkix.Extension
1858 aki.Id = oidExtensionAuthorityKeyId
1859 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
1863 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
1866 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1871 signed := tbsCertListContents
1878 var signature []byte
1879 signature, err = key.Sign(rand, signed, hashFunc)
1884 return asn1.Marshal(pkix.CertificateList{
1885 TBSCertList: tbsCertList,
1886 SignatureAlgorithm: signatureAlgorithm,
1887 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1891 // CertificateRequest represents a PKCS #10, certificate signature request.
1892 type CertificateRequest struct {
1893 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
1894 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
1895 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
1896 RawSubject []byte // DER encoded Subject.
1900 SignatureAlgorithm SignatureAlgorithm
1902 PublicKeyAlgorithm PublicKeyAlgorithm
1907 // Attributes contains the CSR attributes that can parse as
1908 // pkix.AttributeTypeAndValueSET.
1910 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
1911 // generating the requestedExtensions attribute.
1912 Attributes []pkix.AttributeTypeAndValueSET
1914 // Extensions contains all requested extensions, in raw form. When parsing
1915 // CSRs, this can be used to extract extensions that are not parsed by this
1917 Extensions []pkix.Extension
1919 // ExtraExtensions contains extensions to be copied, raw, into any CSR
1920 // marshaled by CreateCertificateRequest. Values override any extensions
1921 // that would otherwise be produced based on the other fields but are
1922 // overridden by any extensions specified in Attributes.
1924 // The ExtraExtensions field is not populated by ParseCertificateRequest,
1925 // see Extensions instead.
1926 ExtraExtensions []pkix.Extension
1928 // Subject Alternate Name values.
1930 EmailAddresses []string
1931 IPAddresses []net.IP
1935 // These structures reflect the ASN.1 structure of X.509 certificate
1936 // signature requests (see RFC 2986):
1938 type tbsCertificateRequest struct {
1941 Subject asn1.RawValue
1942 PublicKey publicKeyInfo
1943 RawAttributes []asn1.RawValue `asn1:"tag:0"`
1946 type certificateRequest struct {
1948 TBSCSR tbsCertificateRequest
1949 SignatureAlgorithm pkix.AlgorithmIdentifier
1950 SignatureValue asn1.BitString
1953 // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
1954 // extensions in a CSR.
1955 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
1957 // newRawAttributes converts AttributeTypeAndValueSETs from a template
1958 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
1959 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
1960 var rawAttributes []asn1.RawValue
1961 b, err := asn1.Marshal(attributes)
1965 rest, err := asn1.Unmarshal(b, &rawAttributes)
1970 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
1972 return rawAttributes, nil
1975 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
1976 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
1977 var attributes []pkix.AttributeTypeAndValueSET
1978 for _, rawAttr := range rawAttributes {
1979 var attr pkix.AttributeTypeAndValueSET
1980 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
1981 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
1982 // (i.e.: challengePassword or unstructuredName).
1983 if err == nil && len(rest) == 0 {
1984 attributes = append(attributes, attr)
1990 // parseCSRExtensions parses the attributes from a CSR and extracts any
1991 // requested extensions.
1992 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
1993 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
1994 type pkcs10Attribute struct {
1995 Id asn1.ObjectIdentifier
1996 Values []asn1.RawValue `asn1:"set"`
1999 var ret []pkix.Extension
2000 requestedExts := make(map[string]bool)
2001 for _, rawAttr := range rawAttributes {
2002 var attr pkcs10Attribute
2003 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2004 // Ignore attributes that don't parse.
2008 if !attr.Id.Equal(oidExtensionRequest) {
2012 var extensions []pkix.Extension
2013 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2016 for _, ext := range extensions {
2017 oidStr := ext.Id.String()
2018 if requestedExts[oidStr] {
2019 return nil, errors.New("x509: certificate request contains duplicate requested extensions")
2021 requestedExts[oidStr] = true
2023 ret = append(ret, extensions...)
2029 // CreateCertificateRequest creates a new certificate request based on a
2030 // template. The following members of template are used:
2032 // - SignatureAlgorithm
2038 // - ExtraExtensions
2039 // - Attributes (deprecated)
2041 // priv is the private key to sign the CSR with, and the corresponding public
2042 // key will be included in the CSR. It must implement crypto.Signer and its
2043 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
2044 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
2045 // ed25519.PrivateKey satisfies this.)
2047 // The returned slice is the certificate request in DER encoding.
2048 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error) {
2049 key, ok := priv.(crypto.Signer)
2051 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2054 var hashFunc crypto.Hash
2055 var sigAlgo pkix.AlgorithmIdentifier
2056 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2061 var publicKeyBytes []byte
2062 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2063 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2068 extensions, err := buildCSRExtensions(template)
2073 // Make a copy of template.Attributes because we may alter it below.
2074 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2075 for _, attr := range template.Attributes {
2076 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2077 copy(values, attr.Value)
2078 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2084 extensionsAppended := false
2085 if len(extensions) > 0 {
2086 // Append the extensions to an existing attribute if possible.
2087 for _, atvSet := range attributes {
2088 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2092 // specifiedExtensions contains all the extensions that we
2093 // found specified via template.Attributes.
2094 specifiedExtensions := make(map[string]bool)
2096 for _, atvs := range atvSet.Value {
2097 for _, atv := range atvs {
2098 specifiedExtensions[atv.Type.String()] = true
2102 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2103 newValue = append(newValue, atvSet.Value[0]...)
2105 for _, e := range extensions {
2106 if specifiedExtensions[e.Id.String()] {
2107 // Attributes already contained a value for
2108 // this extension and it takes priority.
2112 newValue = append(newValue, pkix.AttributeTypeAndValue{
2113 // There is no place for the critical
2114 // flag in an AttributeTypeAndValue.
2120 atvSet.Value[0] = newValue
2121 extensionsAppended = true
2126 rawAttributes, err := newRawAttributes(attributes)
2131 // If not included in attributes, add a new attribute for the
2133 if len(extensions) > 0 && !extensionsAppended {
2135 Type asn1.ObjectIdentifier
2136 Value [][]pkix.Extension `asn1:"set"`
2138 Type: oidExtensionRequest,
2139 Value: [][]pkix.Extension{extensions},
2142 b, err := asn1.Marshal(attr)
2144 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2147 var rawValue asn1.RawValue
2148 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2152 rawAttributes = append(rawAttributes, rawValue)
2155 asn1Subject := template.RawSubject
2156 if len(asn1Subject) == 0 {
2157 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2163 tbsCSR := tbsCertificateRequest{
2164 Version: 0, // PKCS #10, RFC 2986
2165 Subject: asn1.RawValue{FullBytes: asn1Subject},
2166 PublicKey: publicKeyInfo{
2167 Algorithm: publicKeyAlgorithm,
2168 PublicKey: asn1.BitString{
2169 Bytes: publicKeyBytes,
2170 BitLength: len(publicKeyBytes) * 8,
2173 RawAttributes: rawAttributes,
2176 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2180 tbsCSR.Raw = tbsCSRContents
2182 signed := tbsCSRContents
2189 var signature []byte
2190 signature, err = key.Sign(rand, signed, hashFunc)
2195 return asn1.Marshal(certificateRequest{
2197 SignatureAlgorithm: sigAlgo,
2198 SignatureValue: asn1.BitString{
2200 BitLength: len(signature) * 8,
2205 // ParseCertificateRequest parses a single certificate request from the
2206 // given ASN.1 DER data.
2207 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2208 var csr certificateRequest
2210 rest, err := asn1.Unmarshal(asn1Data, &csr)
2213 } else if len(rest) != 0 {
2214 return nil, asn1.SyntaxError{Msg: "trailing data"}
2217 return parseCertificateRequest(&csr)
2220 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2221 out := &CertificateRequest{
2223 RawTBSCertificateRequest: in.TBSCSR.Raw,
2224 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2225 RawSubject: in.TBSCSR.Subject.FullBytes,
2227 Signature: in.SignatureValue.RightAlign(),
2228 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2230 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2232 Version: in.TBSCSR.Version,
2233 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2237 if out.PublicKeyAlgorithm != UnknownPublicKeyAlgorithm {
2238 out.PublicKey, err = parsePublicKey(&in.TBSCSR.PublicKey)
2244 var subject pkix.RDNSequence
2245 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2247 } else if len(rest) != 0 {
2248 return nil, errors.New("x509: trailing data after X.509 Subject")
2251 out.Subject.FillFromRDNSequence(&subject)
2253 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2257 for _, extension := range out.Extensions {
2259 case extension.Id.Equal(oidExtensionSubjectAltName):
2260 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2270 // CheckSignature reports whether the signature on c is valid.
2271 func (c *CertificateRequest) CheckSignature() error {
2272 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey, true)
2275 // RevocationList contains the fields used to create an X.509 v2 Certificate
2276 // Revocation list with CreateRevocationList.
2277 type RevocationList struct {
2278 // Raw contains the complete ASN.1 DER content of the CRL (tbsCertList,
2279 // signatureAlgorithm, and signatureValue.)
2281 // RawTBSRevocationList contains just the tbsCertList portion of the ASN.1
2283 RawTBSRevocationList []byte
2284 // RawIssuer contains the DER encoded Issuer.
2287 // Issuer contains the DN of the issuing certificate.
2289 // AuthorityKeyId is used to identify the public key associated with the
2290 // issuing certificate. It is populated from the authorityKeyIdentifier
2291 // extension when parsing a CRL. It is ignored when creating a CRL; the
2292 // extension is populated from the issuing certificate itself.
2293 AuthorityKeyId []byte
2296 // SignatureAlgorithm is used to determine the signature algorithm to be
2297 // used when signing the CRL. If 0 the default algorithm for the signing
2298 // key will be used.
2299 SignatureAlgorithm SignatureAlgorithm
2301 // RevokedCertificates is used to populate the revokedCertificates
2302 // sequence in the CRL, it may be empty. RevokedCertificates may be nil,
2303 // in which case an empty CRL will be created.
2304 RevokedCertificates []pkix.RevokedCertificate
2306 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2307 // which should be a monotonically increasing sequence number for a given
2308 // CRL scope and CRL issuer. It is also populated from the cRLNumber
2309 // extension when parsing a CRL.
2312 // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2313 // indicates the issuance date of the CRL.
2314 ThisUpdate time.Time
2315 // NextUpdate is used to populate the nextUpdate field in the CRL, which
2316 // indicates the date by which the next CRL will be issued. NextUpdate
2317 // must be greater than ThisUpdate.
2318 NextUpdate time.Time
2320 // Extensions contains raw X.509 extensions. When creating a CRL,
2321 // the Extensions field is ignored, see ExtraExtensions.
2322 Extensions []pkix.Extension
2324 // ExtraExtensions contains any additional extensions to add directly to
2326 ExtraExtensions []pkix.Extension
2329 // These structures reflect the ASN.1 structure of X.509 CRLs better than
2330 // the existing crypto/x509/pkix variants do. These mirror the existing
2331 // certificate structs in this file.
2333 // Notably, we include issuer as an asn1.RawValue, mirroring the behavior of
2334 // tbsCertificate and allowing raw (unparsed) subjects to be passed cleanly.
2335 type certificateList struct {
2336 TBSCertList tbsCertificateList
2337 SignatureAlgorithm pkix.AlgorithmIdentifier
2338 SignatureValue asn1.BitString
2341 type tbsCertificateList struct {
2343 Version int `asn1:"optional,default:0"`
2344 Signature pkix.AlgorithmIdentifier
2345 Issuer asn1.RawValue
2346 ThisUpdate time.Time
2347 NextUpdate time.Time `asn1:"optional"`
2348 RevokedCertificates []pkix.RevokedCertificate `asn1:"optional"`
2349 Extensions []pkix.Extension `asn1:"tag:0,optional,explicit"`
2352 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
2353 // according to RFC 5280, based on template.
2355 // The CRL is signed by priv which should be the private key associated with
2356 // the public key in the issuer certificate.
2358 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
2359 // order to use it as a CRL issuer.
2361 // The issuer distinguished name CRL field and authority key identifier
2362 // extension are populated using the issuer certificate. issuer must have
2363 // SubjectKeyId set.
2364 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2365 if template == nil {
2366 return nil, errors.New("x509: template can not be nil")
2369 return nil, errors.New("x509: issuer can not be nil")
2371 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2372 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2374 if len(issuer.SubjectKeyId) == 0 {
2375 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2377 if template.NextUpdate.Before(template.ThisUpdate) {
2378 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2380 if template.Number == nil {
2381 return nil, errors.New("x509: template contains nil Number field")
2384 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2389 // Force revocation times to UTC per RFC 5280.
2390 revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2391 for i, rc := range template.RevokedCertificates {
2392 rc.RevocationTime = rc.RevocationTime.UTC()
2393 revokedCertsUTC[i] = rc
2396 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2401 if numBytes := template.Number.Bytes(); len(numBytes) > 20 || (len(numBytes) == 20 && numBytes[0]&0x80 != 0) {
2402 return nil, errors.New("x509: CRL number exceeds 20 octets")
2404 crlNum, err := asn1.Marshal(template.Number)
2409 // Correctly use the issuer's subject sequence if one is specified.
2410 issuerSubject, err := subjectBytes(issuer)
2415 tbsCertList := tbsCertificateList{
2417 Signature: signatureAlgorithm,
2418 Issuer: asn1.RawValue{FullBytes: issuerSubject},
2419 ThisUpdate: template.ThisUpdate.UTC(),
2420 NextUpdate: template.NextUpdate.UTC(),
2421 Extensions: []pkix.Extension{
2423 Id: oidExtensionAuthorityKeyId,
2427 Id: oidExtensionCRLNumber,
2432 if len(revokedCertsUTC) > 0 {
2433 tbsCertList.RevokedCertificates = revokedCertsUTC
2436 if len(template.ExtraExtensions) > 0 {
2437 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2440 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2445 // Optimization to only marshal this struct once, when signing and
2446 // then embedding in certificateList below.
2447 tbsCertList.Raw = tbsCertListContents
2449 input := tbsCertListContents
2452 h.Write(tbsCertListContents)
2455 var signerOpts crypto.SignerOpts = hashFunc
2456 if template.SignatureAlgorithm.isRSAPSS() {
2457 signerOpts = &rsa.PSSOptions{
2458 SaltLength: rsa.PSSSaltLengthEqualsHash,
2463 signature, err := priv.Sign(rand, input, signerOpts)
2468 return asn1.Marshal(certificateList{
2469 TBSCertList: tbsCertList,
2470 SignatureAlgorithm: signatureAlgorithm,
2471 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2475 // CheckSignatureFrom verifies that the signature on rl is a valid signature
2477 func (rl *RevocationList) CheckSignatureFrom(parent *Certificate) error {
2478 if parent.Version == 3 && !parent.BasicConstraintsValid ||
2479 parent.BasicConstraintsValid && !parent.IsCA {
2480 return ConstraintViolationError{}
2483 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCRLSign == 0 {
2484 return ConstraintViolationError{}
2487 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
2488 return ErrUnsupportedAlgorithm
2491 return parent.CheckSignature(rl.SignatureAlgorithm, rl.RawTBSRevocationList, rl.Signature)