1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package x509 parses X.509-encoded keys and certificates.
30 // Explicitly import these for their crypto.RegisterHash init side-effects.
31 // Keep these as blank imports, even if they're imported above.
36 "golang.org/x/crypto/cryptobyte"
37 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
40 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
42 type pkixPublicKey struct {
43 Algo pkix.AlgorithmIdentifier
44 BitString asn1.BitString
47 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
48 // The encoded public key is a SubjectPublicKeyInfo structure
49 // (see RFC 5280, Section 4.1).
51 // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
52 // ed25519.PublicKey. More types might be supported in the future.
54 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
55 func ParsePKIXPublicKey(derBytes []byte) (pub any, err error) {
57 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
58 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
59 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
62 } else if len(rest) != 0 {
63 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
65 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
66 if algo == UnknownPublicKeyAlgorithm {
67 return nil, errors.New("x509: unknown public key algorithm")
69 return parsePublicKey(algo, &pki)
72 func marshalPublicKey(pub any) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
73 switch pub := pub.(type) {
75 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
80 return nil, pkix.AlgorithmIdentifier{}, err
82 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
83 // This is a NULL parameters value which is required by
84 // RFC 3279, Section 2.3.1.
85 publicKeyAlgorithm.Parameters = asn1.NullRawValue
86 case *ecdsa.PublicKey:
87 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
88 oid, ok := oidFromNamedCurve(pub.Curve)
90 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
92 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
94 paramBytes, err = asn1.Marshal(oid)
98 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
99 case ed25519.PublicKey:
101 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
103 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
106 return publicKeyBytes, publicKeyAlgorithm, nil
109 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
110 // The encoded public key is a SubjectPublicKeyInfo structure
111 // (see RFC 5280, Section 4.1).
113 // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
114 // and ed25519.PublicKey. Unsupported key types result in an error.
116 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
117 func MarshalPKIXPublicKey(pub any) ([]byte, error) {
118 var publicKeyBytes []byte
119 var publicKeyAlgorithm pkix.AlgorithmIdentifier
122 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
126 pkix := pkixPublicKey{
127 Algo: publicKeyAlgorithm,
128 BitString: asn1.BitString{
129 Bytes: publicKeyBytes,
130 BitLength: 8 * len(publicKeyBytes),
134 ret, _ := asn1.Marshal(pkix)
138 // These structures reflect the ASN.1 structure of X.509 certificates.:
140 type certificate struct {
142 TBSCertificate tbsCertificate
143 SignatureAlgorithm pkix.AlgorithmIdentifier
144 SignatureValue asn1.BitString
147 type tbsCertificate struct {
149 Version int `asn1:"optional,explicit,default:0,tag:0"`
150 SerialNumber *big.Int
151 SignatureAlgorithm pkix.AlgorithmIdentifier
154 Subject asn1.RawValue
155 PublicKey publicKeyInfo
156 UniqueId asn1.BitString `asn1:"optional,tag:1"`
157 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
158 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
161 type dsaAlgorithmParameters struct {
165 type validity struct {
166 NotBefore, NotAfter time.Time
169 type publicKeyInfo struct {
171 Algorithm pkix.AlgorithmIdentifier
172 PublicKey asn1.BitString
176 type authKeyId struct {
177 Id []byte `asn1:"optional,tag:0"`
180 type SignatureAlgorithm int
183 UnknownSignatureAlgorithm SignatureAlgorithm = iota
185 MD2WithRSA // Unsupported.
186 MD5WithRSA // Only supported for signing, not verification.
187 SHA1WithRSA // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
191 DSAWithSHA1 // Unsupported.
192 DSAWithSHA256 // Unsupported.
193 ECDSAWithSHA1 // Only supported for signing, and verification of CRLs, CSRs, and OCSP responses.
203 func (algo SignatureAlgorithm) isRSAPSS() bool {
205 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
212 func (algo SignatureAlgorithm) String() string {
213 for _, details := range signatureAlgorithmDetails {
214 if details.algo == algo {
218 return strconv.Itoa(int(algo))
221 type PublicKeyAlgorithm int
224 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
231 var publicKeyAlgoName = [...]string{
238 func (algo PublicKeyAlgorithm) String() string {
239 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
240 return publicKeyAlgoName[algo]
242 return strconv.Itoa(int(algo))
245 // OIDs for signature algorithms
247 // pkcs-1 OBJECT IDENTIFIER ::= {
248 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
251 // RFC 3279 2.2.1 RSA Signature Algorithms
253 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
255 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
257 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
259 // dsaWithSha1 OBJECT IDENTIFIER ::= {
260 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
262 // RFC 3279 2.2.3 ECDSA Signature Algorithm
264 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
265 // iso(1) member-body(2) us(840) ansi-x962(10045)
266 // signatures(4) ecdsa-with-SHA1(1)}
268 // RFC 4055 5 PKCS #1 Version 1.5
270 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
272 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
274 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
277 // RFC 5758 3.1 DSA Signature Algorithms
279 // dsaWithSha256 OBJECT IDENTIFIER ::= {
280 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
281 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
283 // RFC 5758 3.2 ECDSA Signature Algorithm
285 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
286 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
288 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
289 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
291 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
292 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
294 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
296 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
298 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
299 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
300 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
301 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
302 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
303 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
304 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
305 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
306 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
307 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
308 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
309 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
310 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
311 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
313 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
314 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
315 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
317 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
319 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
320 // but it's specified by ISO. Microsoft's makecert.exe has been known
321 // to produce certificates with this OID.
322 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
325 var signatureAlgorithmDetails = []struct {
326 algo SignatureAlgorithm
328 oid asn1.ObjectIdentifier
329 pubKeyAlgo PublicKeyAlgorithm
332 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
333 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
334 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
335 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
336 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
337 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
338 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
339 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
340 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
341 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
342 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
343 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
344 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
345 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
346 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
347 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
348 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
351 // hashToPSSParameters contains the DER encoded RSA PSS parameters for the
352 // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
353 // The parameters contain the following values:
354 // * hashAlgorithm contains the associated hash identifier with NULL parameters
355 // * maskGenAlgorithm always contains the default mgf1SHA1 identifier
356 // * saltLength contains the length of the associated hash
357 // * trailerField always contains the default trailerFieldBC value
358 var hashToPSSParameters = map[crypto.Hash]asn1.RawValue{
359 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}},
360 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}},
361 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}},
364 // pssParameters reflects the parameters in an AlgorithmIdentifier that
365 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
366 type pssParameters struct {
367 // The following three fields are not marked as
368 // optional because the default values specify SHA-1,
369 // which is no longer suitable for use in signatures.
370 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
371 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
372 SaltLength int `asn1:"explicit,tag:2"`
373 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
376 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
377 if ai.Algorithm.Equal(oidSignatureEd25519) {
378 // RFC 8410, Section 3
379 // > For all of the OIDs, the parameters MUST be absent.
380 if len(ai.Parameters.FullBytes) != 0 {
381 return UnknownSignatureAlgorithm
385 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
386 for _, details := range signatureAlgorithmDetails {
387 if ai.Algorithm.Equal(details.oid) {
391 return UnknownSignatureAlgorithm
394 // RSA PSS is special because it encodes important parameters
395 // in the Parameters.
397 var params pssParameters
398 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
399 return UnknownSignatureAlgorithm
402 var mgf1HashFunc pkix.AlgorithmIdentifier
403 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
404 return UnknownSignatureAlgorithm
407 // PSS is greatly overburdened with options. This code forces them into
408 // three buckets by requiring that the MGF1 hash function always match the
409 // message hash function (as recommended in RFC 3447, Section 8.1), that the
410 // salt length matches the hash length, and that the trailer field has the
412 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
413 !params.MGF.Algorithm.Equal(oidMGF1) ||
414 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
415 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
416 params.TrailerField != 1 {
417 return UnknownSignatureAlgorithm
421 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
422 return SHA256WithRSAPSS
423 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
424 return SHA384WithRSAPSS
425 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
426 return SHA512WithRSAPSS
429 return UnknownSignatureAlgorithm
432 // RFC 3279, 2.3 Public Key Algorithms
434 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
435 // rsadsi(113549) pkcs(1) 1 }
437 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
439 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
440 // x9-57(10040) x9cm(4) 1 }
442 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
444 // id-ecPublicKey OBJECT IDENTIFIER ::= {
445 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
447 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
448 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
449 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
450 oidPublicKeyEd25519 = oidSignatureEd25519
453 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
455 case oid.Equal(oidPublicKeyRSA):
457 case oid.Equal(oidPublicKeyDSA):
459 case oid.Equal(oidPublicKeyECDSA):
461 case oid.Equal(oidPublicKeyEd25519):
464 return UnknownPublicKeyAlgorithm
467 // RFC 5480, 2.1.1.1. Named Curve
469 // secp224r1 OBJECT IDENTIFIER ::= {
470 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
472 // secp256r1 OBJECT IDENTIFIER ::= {
473 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
476 // secp384r1 OBJECT IDENTIFIER ::= {
477 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
479 // secp521r1 OBJECT IDENTIFIER ::= {
480 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
482 // NB: secp256r1 is equivalent to prime256v1
484 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
485 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
486 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
487 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
490 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
492 case oid.Equal(oidNamedCurveP224):
493 return elliptic.P224()
494 case oid.Equal(oidNamedCurveP256):
495 return elliptic.P256()
496 case oid.Equal(oidNamedCurveP384):
497 return elliptic.P384()
498 case oid.Equal(oidNamedCurveP521):
499 return elliptic.P521()
504 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
506 case elliptic.P224():
507 return oidNamedCurveP224, true
508 case elliptic.P256():
509 return oidNamedCurveP256, true
510 case elliptic.P384():
511 return oidNamedCurveP384, true
512 case elliptic.P521():
513 return oidNamedCurveP521, true
519 // KeyUsage represents the set of actions that are valid for a given key. It's
520 // a bitmap of the KeyUsage* constants.
524 KeyUsageDigitalSignature KeyUsage = 1 << iota
525 KeyUsageContentCommitment
526 KeyUsageKeyEncipherment
527 KeyUsageDataEncipherment
535 // RFC 5280, 4.2.1.12 Extended Key Usage
537 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
539 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
541 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
542 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
543 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
544 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
545 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
546 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
548 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
549 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
550 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
551 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
552 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
553 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
554 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
555 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
556 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
557 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
558 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
559 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
560 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
561 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
564 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
565 // Each of the ExtKeyUsage* constants define a unique action.
569 ExtKeyUsageAny ExtKeyUsage = iota
570 ExtKeyUsageServerAuth
571 ExtKeyUsageClientAuth
572 ExtKeyUsageCodeSigning
573 ExtKeyUsageEmailProtection
574 ExtKeyUsageIPSECEndSystem
575 ExtKeyUsageIPSECTunnel
577 ExtKeyUsageTimeStamping
578 ExtKeyUsageOCSPSigning
579 ExtKeyUsageMicrosoftServerGatedCrypto
580 ExtKeyUsageNetscapeServerGatedCrypto
581 ExtKeyUsageMicrosoftCommercialCodeSigning
582 ExtKeyUsageMicrosoftKernelCodeSigning
585 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
586 var extKeyUsageOIDs = []struct {
587 extKeyUsage ExtKeyUsage
588 oid asn1.ObjectIdentifier
590 {ExtKeyUsageAny, oidExtKeyUsageAny},
591 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
592 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
593 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
594 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
595 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
596 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
597 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
598 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
599 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
600 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
601 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
602 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
603 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
606 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
607 for _, pair := range extKeyUsageOIDs {
608 if oid.Equal(pair.oid) {
609 return pair.extKeyUsage, true
615 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
616 for _, pair := range extKeyUsageOIDs {
617 if eku == pair.extKeyUsage {
618 return pair.oid, true
624 // A Certificate represents an X.509 certificate.
625 type Certificate struct {
626 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
627 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
628 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
629 RawSubject []byte // DER encoded Subject
630 RawIssuer []byte // DER encoded Issuer
633 SignatureAlgorithm SignatureAlgorithm
635 PublicKeyAlgorithm PublicKeyAlgorithm
639 SerialNumber *big.Int
642 NotBefore, NotAfter time.Time // Validity bounds.
645 // Extensions contains raw X.509 extensions. When parsing certificates,
646 // this can be used to extract non-critical extensions that are not
647 // parsed by this package. When marshaling certificates, the Extensions
648 // field is ignored, see ExtraExtensions.
649 Extensions []pkix.Extension
651 // ExtraExtensions contains extensions to be copied, raw, into any
652 // marshaled certificates. Values override any extensions that would
653 // otherwise be produced based on the other fields. The ExtraExtensions
654 // field is not populated when parsing certificates, see Extensions.
655 ExtraExtensions []pkix.Extension
657 // UnhandledCriticalExtensions contains a list of extension IDs that
658 // were not (fully) processed when parsing. Verify will fail if this
659 // slice is non-empty, unless verification is delegated to an OS
660 // library which understands all the critical extensions.
662 // Users can access these extensions using Extensions and can remove
663 // elements from this slice if they believe that they have been
665 UnhandledCriticalExtensions []asn1.ObjectIdentifier
667 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
668 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
670 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
671 // and MaxPathLenZero are valid.
672 BasicConstraintsValid bool
675 // MaxPathLen and MaxPathLenZero indicate the presence and
676 // value of the BasicConstraints' "pathLenConstraint".
678 // When parsing a certificate, a positive non-zero MaxPathLen
679 // means that the field was specified, -1 means it was unset,
680 // and MaxPathLenZero being true mean that the field was
681 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
682 // should be treated equivalent to -1 (unset).
684 // When generating a certificate, an unset pathLenConstraint
685 // can be requested with either MaxPathLen == -1 or using the
686 // zero value for both MaxPathLen and MaxPathLenZero.
688 // MaxPathLenZero indicates that BasicConstraintsValid==true
689 // and MaxPathLen==0 should be interpreted as an actual
690 // maximum path length of zero. Otherwise, that combination is
691 // interpreted as MaxPathLen not being set.
695 AuthorityKeyId []byte
697 // RFC 5280, 4.2.2.1 (Authority Information Access)
699 IssuingCertificateURL []string
701 // Subject Alternate Name values. (Note that these values may not be valid
702 // if invalid values were contained within a parsed certificate. For
703 // example, an element of DNSNames may not be a valid DNS domain name.)
705 EmailAddresses []string
710 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
711 PermittedDNSDomains []string
712 ExcludedDNSDomains []string
713 PermittedIPRanges []*net.IPNet
714 ExcludedIPRanges []*net.IPNet
715 PermittedEmailAddresses []string
716 ExcludedEmailAddresses []string
717 PermittedURIDomains []string
718 ExcludedURIDomains []string
720 // CRL Distribution Points
721 CRLDistributionPoints []string
723 PolicyIdentifiers []asn1.ObjectIdentifier
726 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
727 // involves algorithms that are not currently implemented.
728 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
730 // debugAllowSHA1 allows SHA-1 signatures. See issue 41682.
731 var debugAllowSHA1 = godebug.Get("x509sha1") == "1"
733 // An InsecureAlgorithmError indicates that the SignatureAlgorithm used to
734 // generate the signature is not secure, and the signature has been rejected.
736 // To temporarily restore support for SHA-1 signatures, include the value
737 // "x509sha1=1" in the GODEBUG environment variable. Note that this option will
738 // be removed in Go 1.19.
739 type InsecureAlgorithmError SignatureAlgorithm
741 func (e InsecureAlgorithmError) Error() string {
743 if SignatureAlgorithm(e) == SHA1WithRSA || SignatureAlgorithm(e) == ECDSAWithSHA1 {
744 override = " (temporarily override with GODEBUG=x509sha1=1)"
746 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e)) + override
749 // ConstraintViolationError results when a requested usage is not permitted by
750 // a certificate. For example: checking a signature when the public key isn't a
751 // certificate signing key.
752 type ConstraintViolationError struct{}
754 func (ConstraintViolationError) Error() string {
755 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
758 func (c *Certificate) Equal(other *Certificate) bool {
759 if c == nil || other == nil {
762 return bytes.Equal(c.Raw, other.Raw)
765 func (c *Certificate) hasSANExtension() bool {
766 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
769 // CheckSignatureFrom verifies that the signature on c is a valid signature
770 // from parent. SHA1WithRSA and ECDSAWithSHA1 signatures are not supported.
771 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
772 // RFC 5280, 4.2.1.9:
773 // "If the basic constraints extension is not present in a version 3
774 // certificate, or the extension is present but the cA boolean is not
775 // asserted, then the certified public key MUST NOT be used to verify
776 // certificate signatures."
777 if parent.Version == 3 && !parent.BasicConstraintsValid ||
778 parent.BasicConstraintsValid && !parent.IsCA {
779 return ConstraintViolationError{}
782 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
783 return ConstraintViolationError{}
786 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
787 return ErrUnsupportedAlgorithm
790 // TODO(agl): don't ignore the path length constraint.
792 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature, parent.PublicKey, debugAllowSHA1)
795 // CheckSignature verifies that signature is a valid signature over signed from
797 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
798 return checkSignature(algo, signed, signature, c.PublicKey, true)
801 func (c *Certificate) hasNameConstraints() bool {
802 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
805 func (c *Certificate) getSANExtension() []byte {
806 for _, e := range c.Extensions {
807 if e.Id.Equal(oidExtensionSubjectAltName) {
814 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {
815 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
818 // checkSignature verifies that signature is a valid signature over signed from
819 // a crypto.PublicKey.
820 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey, allowSHA1 bool) (err error) {
821 var hashType crypto.Hash
822 var pubKeyAlgo PublicKeyAlgorithm
824 for _, details := range signatureAlgorithmDetails {
825 if details.algo == algo {
826 hashType = details.hash
827 pubKeyAlgo = details.pubKeyAlgo
833 if pubKeyAlgo != Ed25519 {
834 return ErrUnsupportedAlgorithm
837 return InsecureAlgorithmError(algo)
840 return InsecureAlgorithmError(algo)
844 if !hashType.Available() {
845 return ErrUnsupportedAlgorithm
852 switch pub := publicKey.(type) {
854 if pubKeyAlgo != RSA {
855 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
858 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
860 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
862 case *ecdsa.PublicKey:
863 if pubKeyAlgo != ECDSA {
864 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
866 if !ecdsa.VerifyASN1(pub, signed, signature) {
867 return errors.New("x509: ECDSA verification failure")
870 case ed25519.PublicKey:
871 if pubKeyAlgo != Ed25519 {
872 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
874 if !ed25519.Verify(pub, signed, signature) {
875 return errors.New("x509: Ed25519 verification failure")
879 return ErrUnsupportedAlgorithm
882 // CheckCRLSignature checks that the signature in crl is from c.
883 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
884 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
885 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
888 type UnhandledCriticalExtension struct{}
890 func (h UnhandledCriticalExtension) Error() string {
891 return "x509: unhandled critical extension"
894 type basicConstraints struct {
895 IsCA bool `asn1:"optional"`
896 MaxPathLen int `asn1:"optional,default:-1"`
900 type policyInformation struct {
901 Policy asn1.ObjectIdentifier
902 // policyQualifiers omitted
913 type authorityInfoAccess struct {
914 Method asn1.ObjectIdentifier
915 Location asn1.RawValue
918 // RFC 5280, 4.2.1.14
919 type distributionPoint struct {
920 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
921 Reason asn1.BitString `asn1:"optional,tag:1"`
922 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
925 type distributionPointName struct {
926 FullName []asn1.RawValue `asn1:"optional,tag:0"`
927 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
930 func reverseBitsInAByte(in byte) byte {
932 b2 := b1>>2&0x33 | b1<<2&0xcc
933 b3 := b2>>1&0x55 | b2<<1&0xaa
937 // asn1BitLength returns the bit-length of bitString by considering the
938 // most-significant bit in a byte to be the "first" bit. This convention
939 // matches ASN.1, but differs from almost everything else.
940 func asn1BitLength(bitString []byte) int {
941 bitLen := len(bitString) * 8
943 for i := range bitString {
944 b := bitString[len(bitString)-i-1]
946 for bit := uint(0); bit < 8; bit++ {
958 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
959 oidExtensionKeyUsage = []int{2, 5, 29, 15}
960 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
961 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
962 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
963 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
964 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
965 oidExtensionNameConstraints = []int{2, 5, 29, 30}
966 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
967 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
968 oidExtensionCRLNumber = []int{2, 5, 29, 20}
972 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
973 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
976 // oidNotInExtensions reports whether an extension with the given oid exists in
978 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
979 for _, e := range extensions {
987 // marshalSANs marshals a list of addresses into a the contents of an X.509
988 // SubjectAlternativeName extension.
989 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
990 var rawValues []asn1.RawValue
991 for _, name := range dnsNames {
992 if err := isIA5String(name); err != nil {
995 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
997 for _, email := range emailAddresses {
998 if err := isIA5String(email); err != nil {
1001 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1003 for _, rawIP := range ipAddresses {
1004 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1009 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1011 for _, uri := range uris {
1012 uriStr := uri.String()
1013 if err := isIA5String(uriStr); err != nil {
1016 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1018 return asn1.Marshal(rawValues)
1021 func isIA5String(s string) error {
1022 for _, r := range s {
1023 // Per RFC5280 "IA5String is limited to the set of ASCII characters"
1024 if r > unicode.MaxASCII {
1025 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1032 func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1033 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1036 if template.KeyUsage != 0 &&
1037 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1038 ret[n], err = marshalKeyUsage(template.KeyUsage)
1045 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1046 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1047 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
1054 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1055 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
1062 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1063 ret[n].Id = oidExtensionSubjectKeyId
1064 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1071 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1072 ret[n].Id = oidExtensionAuthorityKeyId
1073 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1080 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1081 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1082 ret[n].Id = oidExtensionAuthorityInfoAccess
1083 var aiaValues []authorityInfoAccess
1084 for _, name := range template.OCSPServer {
1085 aiaValues = append(aiaValues, authorityInfoAccess{
1086 Method: oidAuthorityInfoAccessOcsp,
1087 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1090 for _, name := range template.IssuingCertificateURL {
1091 aiaValues = append(aiaValues, authorityInfoAccess{
1092 Method: oidAuthorityInfoAccessIssuers,
1093 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1096 ret[n].Value, err = asn1.Marshal(aiaValues)
1103 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1104 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1105 ret[n].Id = oidExtensionSubjectAltName
1106 // From RFC 5280, Section 4.2.1.6:
1107 // “If the subject field contains an empty sequence ... then
1108 // subjectAltName extension ... is marked as critical”
1109 ret[n].Critical = subjectIsEmpty
1110 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1117 if len(template.PolicyIdentifiers) > 0 &&
1118 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1119 ret[n], err = marshalCertificatePolicies(template.PolicyIdentifiers)
1126 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1127 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1128 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1129 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1130 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1131 ret[n].Id = oidExtensionNameConstraints
1132 ret[n].Critical = template.PermittedDNSDomainsCritical
1134 ipAndMask := func(ipNet *net.IPNet) []byte {
1135 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1136 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1137 ipAndMask = append(ipAndMask, maskedIP...)
1138 ipAndMask = append(ipAndMask, ipNet.Mask...)
1142 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1143 var b cryptobyte.Builder
1145 for _, name := range dns {
1146 if err = isIA5String(name); err != nil {
1150 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1151 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1152 b.AddBytes([]byte(name))
1157 for _, ipNet := range ips {
1158 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1159 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1160 b.AddBytes(ipAndMask(ipNet))
1165 for _, email := range emails {
1166 if err = isIA5String(email); err != nil {
1170 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1171 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1172 b.AddBytes([]byte(email))
1177 for _, uriDomain := range uriDomains {
1178 if err = isIA5String(uriDomain); err != nil {
1182 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1183 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1184 b.AddBytes([]byte(uriDomain))
1192 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1197 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1202 var b cryptobyte.Builder
1203 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1204 if len(permitted) > 0 {
1205 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1206 b.AddBytes(permitted)
1210 if len(excluded) > 0 {
1211 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1212 b.AddBytes(excluded)
1217 ret[n].Value, err = b.Bytes()
1224 if len(template.CRLDistributionPoints) > 0 &&
1225 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1226 ret[n].Id = oidExtensionCRLDistributionPoints
1228 var crlDp []distributionPoint
1229 for _, name := range template.CRLDistributionPoints {
1230 dp := distributionPoint{
1231 DistributionPoint: distributionPointName{
1232 FullName: []asn1.RawValue{
1233 {Tag: 6, Class: 2, Bytes: []byte(name)},
1237 crlDp = append(crlDp, dp)
1240 ret[n].Value, err = asn1.Marshal(crlDp)
1247 // Adding another extension here? Remember to update the maximum number
1248 // of elements in the make() at the top of the function and the list of
1249 // template fields used in CreateCertificate documentation.
1251 return append(ret[:n], template.ExtraExtensions...), nil
1254 func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
1255 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
1258 a[0] = reverseBitsInAByte(byte(ku))
1259 a[1] = reverseBitsInAByte(byte(ku >> 8))
1268 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1272 func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
1273 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
1275 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
1276 for i, u := range extUsages {
1277 if oid, ok := oidFromExtKeyUsage(u); ok {
1280 return ext, errors.New("x509: unknown extended key usage")
1284 copy(oids[len(extUsages):], unknownUsages)
1287 ext.Value, err = asn1.Marshal(oids)
1291 func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
1292 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
1293 // Leaving MaxPathLen as zero indicates that no maximum path
1294 // length is desired, unless MaxPathLenZero is set. A value of
1295 // -1 causes encoding/asn1 to omit the value as desired.
1296 if maxPathLen == 0 && !maxPathLenZero {
1300 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
1304 func marshalCertificatePolicies(policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
1305 ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
1306 policies := make([]policyInformation, len(policyIdentifiers))
1307 for i, policy := range policyIdentifiers {
1308 policies[i].Policy = policy
1311 ext.Value, err = asn1.Marshal(policies)
1315 func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
1316 var ret []pkix.Extension
1318 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1319 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1320 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1325 ret = append(ret, pkix.Extension{
1326 Id: oidExtensionSubjectAltName,
1331 return append(ret, template.ExtraExtensions...), nil
1334 func subjectBytes(cert *Certificate) ([]byte, error) {
1335 if len(cert.RawSubject) > 0 {
1336 return cert.RawSubject, nil
1339 return asn1.Marshal(cert.Subject.ToRDNSequence())
1342 // signingParamsForPublicKey returns the parameters to use for signing with
1343 // priv. If requestedSigAlgo is not zero then it overrides the default
1344 // signature algorithm.
1345 func signingParamsForPublicKey(pub any, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1346 var pubType PublicKeyAlgorithm
1348 switch pub := pub.(type) {
1349 case *rsa.PublicKey:
1351 hashFunc = crypto.SHA256
1352 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1353 sigAlgo.Parameters = asn1.NullRawValue
1355 case *ecdsa.PublicKey:
1359 case elliptic.P224(), elliptic.P256():
1360 hashFunc = crypto.SHA256
1361 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1362 case elliptic.P384():
1363 hashFunc = crypto.SHA384
1364 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1365 case elliptic.P521():
1366 hashFunc = crypto.SHA512
1367 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1369 err = errors.New("x509: unknown elliptic curve")
1372 case ed25519.PublicKey:
1374 sigAlgo.Algorithm = oidSignatureEd25519
1377 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
1384 if requestedSigAlgo == 0 {
1389 for _, details := range signatureAlgorithmDetails {
1390 if details.algo == requestedSigAlgo {
1391 if details.pubKeyAlgo != pubType {
1392 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
1395 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
1396 if hashFunc == 0 && pubType != Ed25519 {
1397 err = errors.New("x509: cannot sign with hash function requested")
1400 if requestedSigAlgo.isRSAPSS() {
1401 sigAlgo.Parameters = hashToPSSParameters[hashFunc]
1409 err = errors.New("x509: unknown SignatureAlgorithm")
1415 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
1416 // just an empty SEQUENCE.
1417 var emptyASN1Subject = []byte{0x30, 0}
1419 // CreateCertificate creates a new X.509 v3 certificate based on a template.
1420 // The following members of template are currently used:
1423 // - BasicConstraintsValid
1424 // - CRLDistributionPoints
1427 // - ExcludedDNSDomains
1428 // - ExcludedEmailAddresses
1429 // - ExcludedIPRanges
1430 // - ExcludedURIDomains
1432 // - ExtraExtensions
1435 // - IssuingCertificateURL
1442 // - PermittedDNSDomains
1443 // - PermittedDNSDomainsCritical
1444 // - PermittedEmailAddresses
1445 // - PermittedIPRanges
1446 // - PermittedURIDomains
1447 // - PolicyIdentifiers
1449 // - SignatureAlgorithm
1453 // - UnknownExtKeyUsage
1455 // The certificate is signed by parent. If parent is equal to template then the
1456 // certificate is self-signed. The parameter pub is the public key of the
1457 // certificate to be generated and priv is the private key of the signer.
1459 // The returned slice is the certificate in DER encoding.
1461 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
1462 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
1463 // crypto.Signer with a supported public key.
1465 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
1466 // unless the resulting certificate is self-signed. Otherwise the value from
1467 // template will be used.
1469 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
1470 // will be generated from the hash of the public key.
1471 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) {
1472 key, ok := priv.(crypto.Signer)
1474 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1477 if template.SerialNumber == nil {
1478 return nil, errors.New("x509: no SerialNumber given")
1481 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
1482 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
1485 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1490 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1495 asn1Issuer, err := subjectBytes(parent)
1500 asn1Subject, err := subjectBytes(template)
1505 authorityKeyId := template.AuthorityKeyId
1506 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1507 authorityKeyId = parent.SubjectKeyId
1510 subjectKeyId := template.SubjectKeyId
1511 if len(subjectKeyId) == 0 && template.IsCA {
1512 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
1513 // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
1514 // value of the BIT STRING subjectPublicKey (excluding the tag,
1515 // length, and number of unused bits).
1516 h := sha1.Sum(publicKeyBytes)
1520 // Check that the signer's public key matches the private key, if available.
1521 type privateKey interface {
1522 Equal(crypto.PublicKey) bool
1524 if privPub, ok := key.Public().(privateKey); !ok {
1525 return nil, errors.New("x509: internal error: supported public key does not implement Equal")
1526 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
1527 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
1530 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
1535 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1536 c := tbsCertificate{
1538 SerialNumber: template.SerialNumber,
1539 SignatureAlgorithm: signatureAlgorithm,
1540 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1541 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1542 Subject: asn1.RawValue{FullBytes: asn1Subject},
1543 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1544 Extensions: extensions,
1547 tbsCertContents, err := asn1.Marshal(c)
1551 c.Raw = tbsCertContents
1553 signed := tbsCertContents
1560 var signerOpts crypto.SignerOpts = hashFunc
1561 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
1562 signerOpts = &rsa.PSSOptions{
1563 SaltLength: rsa.PSSSaltLengthEqualsHash,
1568 var signature []byte
1569 signature, err = key.Sign(rand, signed, signerOpts)
1574 signedCert, err := asn1.Marshal(certificate{
1578 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1584 // Check the signature to ensure the crypto.Signer behaved correctly.
1585 sigAlg := getSignatureAlgorithmFromAI(signatureAlgorithm)
1588 // We skip the check if the signature algorithm is only supported for
1589 // signing, not verification.
1591 if err := checkSignature(sigAlg, c.Raw, signature, key.Public(), true); err != nil {
1592 return nil, fmt.Errorf("x509: signature over certificate returned by signer is invalid: %w", err)
1596 return signedCert, nil
1599 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1601 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1603 // pemType is the type of a PEM encoded CRL.
1604 var pemType = "X509 CRL"
1606 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1607 // encoded CRLs will appear where they should be DER encoded, so this function
1608 // will transparently handle PEM encoding as long as there isn't any leading
1610 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1611 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1612 block, _ := pem.Decode(crlBytes)
1613 if block != nil && block.Type == pemType {
1614 crlBytes = block.Bytes
1617 return ParseDERCRL(crlBytes)
1620 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1621 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1622 certList := new(pkix.CertificateList)
1623 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
1625 } else if len(rest) != 0 {
1626 return nil, errors.New("x509: trailing data after CRL")
1628 return certList, nil
1631 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1632 // contains the given list of revoked certificates.
1634 // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
1635 // To generate a standards compliant CRL, use CreateRevocationList instead.
1636 func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1637 key, ok := priv.(crypto.Signer)
1639 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1642 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
1647 // Force revocation times to UTC per RFC 5280.
1648 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
1649 for i, rc := range revokedCerts {
1650 rc.RevocationTime = rc.RevocationTime.UTC()
1651 revokedCertsUTC[i] = rc
1654 tbsCertList := pkix.TBSCertificateList{
1656 Signature: signatureAlgorithm,
1657 Issuer: c.Subject.ToRDNSequence(),
1658 ThisUpdate: now.UTC(),
1659 NextUpdate: expiry.UTC(),
1660 RevokedCertificates: revokedCertsUTC,
1664 if len(c.SubjectKeyId) > 0 {
1665 var aki pkix.Extension
1666 aki.Id = oidExtensionAuthorityKeyId
1667 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
1671 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
1674 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1679 signed := tbsCertListContents
1686 var signature []byte
1687 signature, err = key.Sign(rand, signed, hashFunc)
1692 return asn1.Marshal(pkix.CertificateList{
1693 TBSCertList: tbsCertList,
1694 SignatureAlgorithm: signatureAlgorithm,
1695 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1699 // CertificateRequest represents a PKCS #10, certificate signature request.
1700 type CertificateRequest struct {
1701 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
1702 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
1703 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
1704 RawSubject []byte // DER encoded Subject.
1708 SignatureAlgorithm SignatureAlgorithm
1710 PublicKeyAlgorithm PublicKeyAlgorithm
1715 // Attributes contains the CSR attributes that can parse as
1716 // pkix.AttributeTypeAndValueSET.
1718 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
1719 // generating the requestedExtensions attribute.
1720 Attributes []pkix.AttributeTypeAndValueSET
1722 // Extensions contains all requested extensions, in raw form. When parsing
1723 // CSRs, this can be used to extract extensions that are not parsed by this
1725 Extensions []pkix.Extension
1727 // ExtraExtensions contains extensions to be copied, raw, into any CSR
1728 // marshaled by CreateCertificateRequest. Values override any extensions
1729 // that would otherwise be produced based on the other fields but are
1730 // overridden by any extensions specified in Attributes.
1732 // The ExtraExtensions field is not populated by ParseCertificateRequest,
1733 // see Extensions instead.
1734 ExtraExtensions []pkix.Extension
1736 // Subject Alternate Name values.
1738 EmailAddresses []string
1739 IPAddresses []net.IP
1743 // These structures reflect the ASN.1 structure of X.509 certificate
1744 // signature requests (see RFC 2986):
1746 type tbsCertificateRequest struct {
1749 Subject asn1.RawValue
1750 PublicKey publicKeyInfo
1751 RawAttributes []asn1.RawValue `asn1:"tag:0"`
1754 type certificateRequest struct {
1756 TBSCSR tbsCertificateRequest
1757 SignatureAlgorithm pkix.AlgorithmIdentifier
1758 SignatureValue asn1.BitString
1761 // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
1762 // extensions in a CSR.
1763 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
1765 // newRawAttributes converts AttributeTypeAndValueSETs from a template
1766 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
1767 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
1768 var rawAttributes []asn1.RawValue
1769 b, err := asn1.Marshal(attributes)
1773 rest, err := asn1.Unmarshal(b, &rawAttributes)
1778 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
1780 return rawAttributes, nil
1783 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
1784 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
1785 var attributes []pkix.AttributeTypeAndValueSET
1786 for _, rawAttr := range rawAttributes {
1787 var attr pkix.AttributeTypeAndValueSET
1788 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
1789 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
1790 // (i.e.: challengePassword or unstructuredName).
1791 if err == nil && len(rest) == 0 {
1792 attributes = append(attributes, attr)
1798 // parseCSRExtensions parses the attributes from a CSR and extracts any
1799 // requested extensions.
1800 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
1801 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
1802 type pkcs10Attribute struct {
1803 Id asn1.ObjectIdentifier
1804 Values []asn1.RawValue `asn1:"set"`
1807 var ret []pkix.Extension
1808 for _, rawAttr := range rawAttributes {
1809 var attr pkcs10Attribute
1810 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
1811 // Ignore attributes that don't parse.
1815 if !attr.Id.Equal(oidExtensionRequest) {
1819 var extensions []pkix.Extension
1820 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
1823 ret = append(ret, extensions...)
1829 // CreateCertificateRequest creates a new certificate request based on a
1830 // template. The following members of template are used:
1832 // - SignatureAlgorithm
1838 // - ExtraExtensions
1839 // - Attributes (deprecated)
1841 // priv is the private key to sign the CSR with, and the corresponding public
1842 // key will be included in the CSR. It must implement crypto.Signer and its
1843 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
1844 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
1845 // ed25519.PrivateKey satisfies this.)
1847 // The returned slice is the certificate request in DER encoding.
1848 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error) {
1849 key, ok := priv.(crypto.Signer)
1851 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1854 var hashFunc crypto.Hash
1855 var sigAlgo pkix.AlgorithmIdentifier
1856 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1861 var publicKeyBytes []byte
1862 var publicKeyAlgorithm pkix.AlgorithmIdentifier
1863 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
1868 extensions, err := buildCSRExtensions(template)
1873 // Make a copy of template.Attributes because we may alter it below.
1874 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
1875 for _, attr := range template.Attributes {
1876 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
1877 copy(values, attr.Value)
1878 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
1884 extensionsAppended := false
1885 if len(extensions) > 0 {
1886 // Append the extensions to an existing attribute if possible.
1887 for _, atvSet := range attributes {
1888 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
1892 // specifiedExtensions contains all the extensions that we
1893 // found specified via template.Attributes.
1894 specifiedExtensions := make(map[string]bool)
1896 for _, atvs := range atvSet.Value {
1897 for _, atv := range atvs {
1898 specifiedExtensions[atv.Type.String()] = true
1902 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
1903 newValue = append(newValue, atvSet.Value[0]...)
1905 for _, e := range extensions {
1906 if specifiedExtensions[e.Id.String()] {
1907 // Attributes already contained a value for
1908 // this extension and it takes priority.
1912 newValue = append(newValue, pkix.AttributeTypeAndValue{
1913 // There is no place for the critical
1914 // flag in an AttributeTypeAndValue.
1920 atvSet.Value[0] = newValue
1921 extensionsAppended = true
1926 rawAttributes, err := newRawAttributes(attributes)
1931 // If not included in attributes, add a new attribute for the
1933 if len(extensions) > 0 && !extensionsAppended {
1935 Type asn1.ObjectIdentifier
1936 Value [][]pkix.Extension `asn1:"set"`
1938 Type: oidExtensionRequest,
1939 Value: [][]pkix.Extension{extensions},
1942 b, err := asn1.Marshal(attr)
1944 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
1947 var rawValue asn1.RawValue
1948 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
1952 rawAttributes = append(rawAttributes, rawValue)
1955 asn1Subject := template.RawSubject
1956 if len(asn1Subject) == 0 {
1957 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
1963 tbsCSR := tbsCertificateRequest{
1964 Version: 0, // PKCS #10, RFC 2986
1965 Subject: asn1.RawValue{FullBytes: asn1Subject},
1966 PublicKey: publicKeyInfo{
1967 Algorithm: publicKeyAlgorithm,
1968 PublicKey: asn1.BitString{
1969 Bytes: publicKeyBytes,
1970 BitLength: len(publicKeyBytes) * 8,
1973 RawAttributes: rawAttributes,
1976 tbsCSRContents, err := asn1.Marshal(tbsCSR)
1980 tbsCSR.Raw = tbsCSRContents
1982 signed := tbsCSRContents
1989 var signature []byte
1990 signature, err = key.Sign(rand, signed, hashFunc)
1995 return asn1.Marshal(certificateRequest{
1997 SignatureAlgorithm: sigAlgo,
1998 SignatureValue: asn1.BitString{
2000 BitLength: len(signature) * 8,
2005 // ParseCertificateRequest parses a single certificate request from the
2006 // given ASN.1 DER data.
2007 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2008 var csr certificateRequest
2010 rest, err := asn1.Unmarshal(asn1Data, &csr)
2013 } else if len(rest) != 0 {
2014 return nil, asn1.SyntaxError{Msg: "trailing data"}
2017 return parseCertificateRequest(&csr)
2020 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2021 out := &CertificateRequest{
2023 RawTBSCertificateRequest: in.TBSCSR.Raw,
2024 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2025 RawSubject: in.TBSCSR.Subject.FullBytes,
2027 Signature: in.SignatureValue.RightAlign(),
2028 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2030 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2032 Version: in.TBSCSR.Version,
2033 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2037 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2042 var subject pkix.RDNSequence
2043 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2045 } else if len(rest) != 0 {
2046 return nil, errors.New("x509: trailing data after X.509 Subject")
2049 out.Subject.FillFromRDNSequence(&subject)
2051 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2055 for _, extension := range out.Extensions {
2057 case extension.Id.Equal(oidExtensionSubjectAltName):
2058 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2068 // CheckSignature reports whether the signature on c is valid.
2069 func (c *CertificateRequest) CheckSignature() error {
2070 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey, true)
2073 // RevocationList contains the fields used to create an X.509 v2 Certificate
2074 // Revocation list with CreateRevocationList.
2075 type RevocationList struct {
2076 // SignatureAlgorithm is used to determine the signature algorithm to be
2077 // used when signing the CRL. If 0 the default algorithm for the signing
2078 // key will be used.
2079 SignatureAlgorithm SignatureAlgorithm
2081 // RevokedCertificates is used to populate the revokedCertificates
2082 // sequence in the CRL, it may be empty. RevokedCertificates may be nil,
2083 // in which case an empty CRL will be created.
2084 RevokedCertificates []pkix.RevokedCertificate
2086 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2087 // which should be a monotonically increasing sequence number for a given
2088 // CRL scope and CRL issuer.
2090 // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2091 // indicates the issuance date of the CRL.
2092 ThisUpdate time.Time
2093 // NextUpdate is used to populate the nextUpdate field in the CRL, which
2094 // indicates the date by which the next CRL will be issued. NextUpdate
2095 // must be greater than ThisUpdate.
2096 NextUpdate time.Time
2097 // ExtraExtensions contains any additional extensions to add directly to
2099 ExtraExtensions []pkix.Extension
2102 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
2103 // according to RFC 5280, based on template.
2105 // The CRL is signed by priv which should be the private key associated with
2106 // the public key in the issuer certificate.
2108 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
2109 // order to use it as a CRL issuer.
2111 // The issuer distinguished name CRL field and authority key identifier
2112 // extension are populated using the issuer certificate. issuer must have
2113 // SubjectKeyId set.
2114 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2115 if template == nil {
2116 return nil, errors.New("x509: template can not be nil")
2119 return nil, errors.New("x509: issuer can not be nil")
2121 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2122 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2124 if len(issuer.SubjectKeyId) == 0 {
2125 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2127 if template.NextUpdate.Before(template.ThisUpdate) {
2128 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2130 if template.Number == nil {
2131 return nil, errors.New("x509: template contains nil Number field")
2134 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2139 // Force revocation times to UTC per RFC 5280.
2140 revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2141 for i, rc := range template.RevokedCertificates {
2142 rc.RevocationTime = rc.RevocationTime.UTC()
2143 revokedCertsUTC[i] = rc
2146 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2150 crlNum, err := asn1.Marshal(template.Number)
2155 tbsCertList := pkix.TBSCertificateList{
2157 Signature: signatureAlgorithm,
2158 Issuer: issuer.Subject.ToRDNSequence(),
2159 ThisUpdate: template.ThisUpdate.UTC(),
2160 NextUpdate: template.NextUpdate.UTC(),
2161 Extensions: []pkix.Extension{
2163 Id: oidExtensionAuthorityKeyId,
2167 Id: oidExtensionCRLNumber,
2172 if len(revokedCertsUTC) > 0 {
2173 tbsCertList.RevokedCertificates = revokedCertsUTC
2176 if len(template.ExtraExtensions) > 0 {
2177 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2180 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2185 input := tbsCertListContents
2188 h.Write(tbsCertListContents)
2191 var signerOpts crypto.SignerOpts = hashFunc
2192 if template.SignatureAlgorithm.isRSAPSS() {
2193 signerOpts = &rsa.PSSOptions{
2194 SaltLength: rsa.PSSSaltLengthEqualsHash,
2199 signature, err := priv.Sign(rand, input, signerOpts)
2204 return asn1.Marshal(pkix.CertificateList{
2205 TBSCertList: tbsCertList,
2206 SignatureAlgorithm: signatureAlgorithm,
2207 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},