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, not verification.
191 DSAWithSHA1 // Unsupported.
192 DSAWithSHA256 // Unsupported.
193 ECDSAWithSHA1 // Only supported for signing, not verification.
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)}
269 // RFC 4055 5 PKCS #1 Version 1.5
271 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
273 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
275 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
278 // RFC 5758 3.1 DSA Signature Algorithms
280 // dsaWithSha256 OBJECT IDENTIFIER ::= {
281 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
282 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
284 // RFC 5758 3.2 ECDSA Signature Algorithm
286 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
287 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
289 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
290 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
292 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
293 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
296 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
298 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
301 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
302 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
303 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
304 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
305 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
306 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
307 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
308 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
309 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
310 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
311 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
312 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
313 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
314 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
316 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
317 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
318 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
320 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
322 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
323 // but it's specified by ISO. Microsoft's makecert.exe has been known
324 // to produce certificates with this OID.
325 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
328 var signatureAlgorithmDetails = []struct {
329 algo SignatureAlgorithm
331 oid asn1.ObjectIdentifier
332 pubKeyAlgo PublicKeyAlgorithm
335 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
336 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
337 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
338 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
339 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
340 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
341 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
342 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
343 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
344 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
345 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
346 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
347 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
348 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
349 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
350 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
351 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
354 // hashToPSSParameters contains the DER encoded RSA PSS parameters for the
355 // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
356 // The parameters contain the following values:
357 // * hashAlgorithm contains the associated hash identifier with NULL parameters
358 // * maskGenAlgorithm always contains the default mgf1SHA1 identifier
359 // * saltLength contains the length of the associated hash
360 // * trailerField always contains the default trailerFieldBC value
361 var hashToPSSParameters = map[crypto.Hash]asn1.RawValue{
362 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}},
363 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}},
364 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}},
367 // pssParameters reflects the parameters in an AlgorithmIdentifier that
368 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
369 type pssParameters struct {
370 // The following three fields are not marked as
371 // optional because the default values specify SHA-1,
372 // which is no longer suitable for use in signatures.
373 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
374 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
375 SaltLength int `asn1:"explicit,tag:2"`
376 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
379 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
380 if ai.Algorithm.Equal(oidSignatureEd25519) {
381 // RFC 8410, Section 3
382 // > For all of the OIDs, the parameters MUST be absent.
383 if len(ai.Parameters.FullBytes) != 0 {
384 return UnknownSignatureAlgorithm
388 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
389 for _, details := range signatureAlgorithmDetails {
390 if ai.Algorithm.Equal(details.oid) {
394 return UnknownSignatureAlgorithm
397 // RSA PSS is special because it encodes important parameters
398 // in the Parameters.
400 var params pssParameters
401 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
402 return UnknownSignatureAlgorithm
405 var mgf1HashFunc pkix.AlgorithmIdentifier
406 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
407 return UnknownSignatureAlgorithm
410 // PSS is greatly overburdened with options. This code forces them into
411 // three buckets by requiring that the MGF1 hash function always match the
412 // message hash function (as recommended in RFC 3447, Section 8.1), that the
413 // salt length matches the hash length, and that the trailer field has the
415 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
416 !params.MGF.Algorithm.Equal(oidMGF1) ||
417 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
418 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
419 params.TrailerField != 1 {
420 return UnknownSignatureAlgorithm
424 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
425 return SHA256WithRSAPSS
426 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
427 return SHA384WithRSAPSS
428 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
429 return SHA512WithRSAPSS
432 return UnknownSignatureAlgorithm
435 // RFC 3279, 2.3 Public Key Algorithms
437 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
438 // rsadsi(113549) pkcs(1) 1 }
440 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
442 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
443 // x9-57(10040) x9cm(4) 1 }
445 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
447 // id-ecPublicKey OBJECT IDENTIFIER ::= {
448 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
450 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
451 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
452 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
453 oidPublicKeyEd25519 = oidSignatureEd25519
456 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
458 case oid.Equal(oidPublicKeyRSA):
460 case oid.Equal(oidPublicKeyDSA):
462 case oid.Equal(oidPublicKeyECDSA):
464 case oid.Equal(oidPublicKeyEd25519):
467 return UnknownPublicKeyAlgorithm
470 // RFC 5480, 2.1.1.1. Named Curve
472 // secp224r1 OBJECT IDENTIFIER ::= {
473 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
475 // secp256r1 OBJECT IDENTIFIER ::= {
476 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
479 // secp384r1 OBJECT IDENTIFIER ::= {
480 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
482 // secp521r1 OBJECT IDENTIFIER ::= {
483 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
485 // NB: secp256r1 is equivalent to prime256v1
487 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
488 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
489 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
490 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
493 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
495 case oid.Equal(oidNamedCurveP224):
496 return elliptic.P224()
497 case oid.Equal(oidNamedCurveP256):
498 return elliptic.P256()
499 case oid.Equal(oidNamedCurveP384):
500 return elliptic.P384()
501 case oid.Equal(oidNamedCurveP521):
502 return elliptic.P521()
507 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
509 case elliptic.P224():
510 return oidNamedCurveP224, true
511 case elliptic.P256():
512 return oidNamedCurveP256, true
513 case elliptic.P384():
514 return oidNamedCurveP384, true
515 case elliptic.P521():
516 return oidNamedCurveP521, true
522 // KeyUsage represents the set of actions that are valid for a given key. It's
523 // a bitmap of the KeyUsage* constants.
527 KeyUsageDigitalSignature KeyUsage = 1 << iota
528 KeyUsageContentCommitment
529 KeyUsageKeyEncipherment
530 KeyUsageDataEncipherment
538 // RFC 5280, 4.2.1.12 Extended Key Usage
540 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
542 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
544 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
545 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
546 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
547 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
548 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
549 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
551 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
552 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
553 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
554 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
555 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
556 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
557 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
558 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
559 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
560 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
561 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
562 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
563 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
564 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
567 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
568 // Each of the ExtKeyUsage* constants define a unique action.
572 ExtKeyUsageAny ExtKeyUsage = iota
573 ExtKeyUsageServerAuth
574 ExtKeyUsageClientAuth
575 ExtKeyUsageCodeSigning
576 ExtKeyUsageEmailProtection
577 ExtKeyUsageIPSECEndSystem
578 ExtKeyUsageIPSECTunnel
580 ExtKeyUsageTimeStamping
581 ExtKeyUsageOCSPSigning
582 ExtKeyUsageMicrosoftServerGatedCrypto
583 ExtKeyUsageNetscapeServerGatedCrypto
584 ExtKeyUsageMicrosoftCommercialCodeSigning
585 ExtKeyUsageMicrosoftKernelCodeSigning
588 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
589 var extKeyUsageOIDs = []struct {
590 extKeyUsage ExtKeyUsage
591 oid asn1.ObjectIdentifier
593 {ExtKeyUsageAny, oidExtKeyUsageAny},
594 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
595 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
596 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
597 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
598 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
599 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
600 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
601 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
602 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
603 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
604 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
605 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
606 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
609 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
610 for _, pair := range extKeyUsageOIDs {
611 if oid.Equal(pair.oid) {
612 return pair.extKeyUsage, true
618 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
619 for _, pair := range extKeyUsageOIDs {
620 if eku == pair.extKeyUsage {
621 return pair.oid, true
627 // A Certificate represents an X.509 certificate.
628 type Certificate struct {
629 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
630 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
631 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
632 RawSubject []byte // DER encoded Subject
633 RawIssuer []byte // DER encoded Issuer
636 SignatureAlgorithm SignatureAlgorithm
638 PublicKeyAlgorithm PublicKeyAlgorithm
642 SerialNumber *big.Int
645 NotBefore, NotAfter time.Time // Validity bounds.
648 // Extensions contains raw X.509 extensions. When parsing certificates,
649 // this can be used to extract non-critical extensions that are not
650 // parsed by this package. When marshaling certificates, the Extensions
651 // field is ignored, see ExtraExtensions.
652 Extensions []pkix.Extension
654 // ExtraExtensions contains extensions to be copied, raw, into any
655 // marshaled certificates. Values override any extensions that would
656 // otherwise be produced based on the other fields. The ExtraExtensions
657 // field is not populated when parsing certificates, see Extensions.
658 ExtraExtensions []pkix.Extension
660 // UnhandledCriticalExtensions contains a list of extension IDs that
661 // were not (fully) processed when parsing. Verify will fail if this
662 // slice is non-empty, unless verification is delegated to an OS
663 // library which understands all the critical extensions.
665 // Users can access these extensions using Extensions and can remove
666 // elements from this slice if they believe that they have been
668 UnhandledCriticalExtensions []asn1.ObjectIdentifier
670 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
671 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
673 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
674 // and MaxPathLenZero are valid.
675 BasicConstraintsValid bool
678 // MaxPathLen and MaxPathLenZero indicate the presence and
679 // value of the BasicConstraints' "pathLenConstraint".
681 // When parsing a certificate, a positive non-zero MaxPathLen
682 // means that the field was specified, -1 means it was unset,
683 // and MaxPathLenZero being true mean that the field was
684 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
685 // should be treated equivalent to -1 (unset).
687 // When generating a certificate, an unset pathLenConstraint
688 // can be requested with either MaxPathLen == -1 or using the
689 // zero value for both MaxPathLen and MaxPathLenZero.
691 // MaxPathLenZero indicates that BasicConstraintsValid==true
692 // and MaxPathLen==0 should be interpreted as an actual
693 // maximum path length of zero. Otherwise, that combination is
694 // interpreted as MaxPathLen not being set.
698 AuthorityKeyId []byte
700 // RFC 5280, 4.2.2.1 (Authority Information Access)
702 IssuingCertificateURL []string
704 // Subject Alternate Name values. (Note that these values may not be valid
705 // if invalid values were contained within a parsed certificate. For
706 // example, an element of DNSNames may not be a valid DNS domain name.)
708 EmailAddresses []string
713 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
714 PermittedDNSDomains []string
715 ExcludedDNSDomains []string
716 PermittedIPRanges []*net.IPNet
717 ExcludedIPRanges []*net.IPNet
718 PermittedEmailAddresses []string
719 ExcludedEmailAddresses []string
720 PermittedURIDomains []string
721 ExcludedURIDomains []string
723 // CRL Distribution Points
724 CRLDistributionPoints []string
726 PolicyIdentifiers []asn1.ObjectIdentifier
729 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
730 // involves algorithms that are not currently implemented.
731 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
733 // debugAllowSHA1 allows SHA-1 signatures. See issue 41682.
734 var debugAllowSHA1 = godebug.Get("x509sha1") == "1"
736 // An InsecureAlgorithmError indicates that the SignatureAlgorithm used to
737 // generate the signature is not secure, and the signature has been rejected.
739 // To temporarily restore support for SHA-1 signatures, include the value
740 // "x509sha1=1" in the GODEBUG environment variable. Note that this option will
741 // be removed in Go 1.19.
742 type InsecureAlgorithmError SignatureAlgorithm
744 func (e InsecureAlgorithmError) Error() string {
746 if SignatureAlgorithm(e) == SHA1WithRSA || SignatureAlgorithm(e) == ECDSAWithSHA1 {
747 override = " (temporarily override with GODEBUG=x509sha1=1)"
749 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e)) + override
752 // ConstraintViolationError results when a requested usage is not permitted by
753 // a certificate. For example: checking a signature when the public key isn't a
754 // certificate signing key.
755 type ConstraintViolationError struct{}
757 func (ConstraintViolationError) Error() string {
758 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
761 func (c *Certificate) Equal(other *Certificate) bool {
762 if c == nil || other == nil {
765 return bytes.Equal(c.Raw, other.Raw)
768 func (c *Certificate) hasSANExtension() bool {
769 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
772 // CheckSignatureFrom verifies that the signature on c is a valid signature
774 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
775 // RFC 5280, 4.2.1.9:
776 // "If the basic constraints extension is not present in a version 3
777 // certificate, or the extension is present but the cA boolean is not
778 // asserted, then the certified public key MUST NOT be used to verify
779 // certificate signatures."
780 if parent.Version == 3 && !parent.BasicConstraintsValid ||
781 parent.BasicConstraintsValid && !parent.IsCA {
782 return ConstraintViolationError{}
785 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
786 return ConstraintViolationError{}
789 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
790 return ErrUnsupportedAlgorithm
793 // TODO(agl): don't ignore the path length constraint.
795 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
798 // CheckSignature verifies that signature is a valid signature over signed from
800 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
801 return checkSignature(algo, signed, signature, c.PublicKey)
804 func (c *Certificate) hasNameConstraints() bool {
805 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
808 func (c *Certificate) getSANExtension() []byte {
809 for _, e := range c.Extensions {
810 if e.Id.Equal(oidExtensionSubjectAltName) {
817 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey any) error {
818 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
821 // CheckSignature verifies that signature is a valid signature over signed from
822 // a crypto.PublicKey.
823 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
824 var hashType crypto.Hash
825 var pubKeyAlgo PublicKeyAlgorithm
827 for _, details := range signatureAlgorithmDetails {
828 if details.algo == algo {
829 hashType = details.hash
830 pubKeyAlgo = details.pubKeyAlgo
836 if pubKeyAlgo != Ed25519 {
837 return ErrUnsupportedAlgorithm
840 return InsecureAlgorithmError(algo)
843 return InsecureAlgorithmError(algo)
847 if !hashType.Available() {
848 return ErrUnsupportedAlgorithm
855 switch pub := publicKey.(type) {
857 if pubKeyAlgo != RSA {
858 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
861 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
863 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
865 case *ecdsa.PublicKey:
866 if pubKeyAlgo != ECDSA {
867 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
869 if !ecdsa.VerifyASN1(pub, signed, signature) {
870 return errors.New("x509: ECDSA verification failure")
873 case ed25519.PublicKey:
874 if pubKeyAlgo != Ed25519 {
875 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
877 if !ed25519.Verify(pub, signed, signature) {
878 return errors.New("x509: Ed25519 verification failure")
882 return ErrUnsupportedAlgorithm
885 // CheckCRLSignature checks that the signature in crl is from c.
886 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
887 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
888 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
891 type UnhandledCriticalExtension struct{}
893 func (h UnhandledCriticalExtension) Error() string {
894 return "x509: unhandled critical extension"
897 type basicConstraints struct {
898 IsCA bool `asn1:"optional"`
899 MaxPathLen int `asn1:"optional,default:-1"`
903 type policyInformation struct {
904 Policy asn1.ObjectIdentifier
905 // policyQualifiers omitted
916 type authorityInfoAccess struct {
917 Method asn1.ObjectIdentifier
918 Location asn1.RawValue
921 // RFC 5280, 4.2.1.14
922 type distributionPoint struct {
923 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
924 Reason asn1.BitString `asn1:"optional,tag:1"`
925 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
928 type distributionPointName struct {
929 FullName []asn1.RawValue `asn1:"optional,tag:0"`
930 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
933 func reverseBitsInAByte(in byte) byte {
935 b2 := b1>>2&0x33 | b1<<2&0xcc
936 b3 := b2>>1&0x55 | b2<<1&0xaa
940 // asn1BitLength returns the bit-length of bitString by considering the
941 // most-significant bit in a byte to be the "first" bit. This convention
942 // matches ASN.1, but differs from almost everything else.
943 func asn1BitLength(bitString []byte) int {
944 bitLen := len(bitString) * 8
946 for i := range bitString {
947 b := bitString[len(bitString)-i-1]
949 for bit := uint(0); bit < 8; bit++ {
961 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
962 oidExtensionKeyUsage = []int{2, 5, 29, 15}
963 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
964 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
965 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
966 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
967 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
968 oidExtensionNameConstraints = []int{2, 5, 29, 30}
969 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
970 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
971 oidExtensionCRLNumber = []int{2, 5, 29, 20}
975 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
976 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
979 // oidNotInExtensions reports whether an extension with the given oid exists in
981 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
982 for _, e := range extensions {
990 // marshalSANs marshals a list of addresses into a the contents of an X.509
991 // SubjectAlternativeName extension.
992 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
993 var rawValues []asn1.RawValue
994 for _, name := range dnsNames {
995 if err := isIA5String(name); err != nil {
998 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1000 for _, email := range emailAddresses {
1001 if err := isIA5String(email); err != nil {
1004 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1006 for _, rawIP := range ipAddresses {
1007 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1012 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1014 for _, uri := range uris {
1015 uriStr := uri.String()
1016 if err := isIA5String(uriStr); err != nil {
1019 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1021 return asn1.Marshal(rawValues)
1024 func isIA5String(s string) error {
1025 for _, r := range s {
1026 // Per RFC5280 "IA5String is limited to the set of ASCII characters"
1027 if r > unicode.MaxASCII {
1028 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1035 func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1036 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1039 if template.KeyUsage != 0 &&
1040 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1041 ret[n], err = marshalKeyUsage(template.KeyUsage)
1048 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1049 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1050 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
1057 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1058 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
1065 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1066 ret[n].Id = oidExtensionSubjectKeyId
1067 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1074 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1075 ret[n].Id = oidExtensionAuthorityKeyId
1076 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1083 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1084 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1085 ret[n].Id = oidExtensionAuthorityInfoAccess
1086 var aiaValues []authorityInfoAccess
1087 for _, name := range template.OCSPServer {
1088 aiaValues = append(aiaValues, authorityInfoAccess{
1089 Method: oidAuthorityInfoAccessOcsp,
1090 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1093 for _, name := range template.IssuingCertificateURL {
1094 aiaValues = append(aiaValues, authorityInfoAccess{
1095 Method: oidAuthorityInfoAccessIssuers,
1096 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1099 ret[n].Value, err = asn1.Marshal(aiaValues)
1106 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1107 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1108 ret[n].Id = oidExtensionSubjectAltName
1109 // From RFC 5280, Section 4.2.1.6:
1110 // “If the subject field contains an empty sequence ... then
1111 // subjectAltName extension ... is marked as critical”
1112 ret[n].Critical = subjectIsEmpty
1113 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1120 if len(template.PolicyIdentifiers) > 0 &&
1121 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1122 ret[n], err = marshalCertificatePolicies(template.PolicyIdentifiers)
1129 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1130 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1131 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1132 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1133 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1134 ret[n].Id = oidExtensionNameConstraints
1135 ret[n].Critical = template.PermittedDNSDomainsCritical
1137 ipAndMask := func(ipNet *net.IPNet) []byte {
1138 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1139 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1140 ipAndMask = append(ipAndMask, maskedIP...)
1141 ipAndMask = append(ipAndMask, ipNet.Mask...)
1145 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1146 var b cryptobyte.Builder
1148 for _, name := range dns {
1149 if err = isIA5String(name); err != nil {
1153 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1154 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1155 b.AddBytes([]byte(name))
1160 for _, ipNet := range ips {
1161 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1162 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1163 b.AddBytes(ipAndMask(ipNet))
1168 for _, email := range emails {
1169 if err = isIA5String(email); err != nil {
1173 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1174 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1175 b.AddBytes([]byte(email))
1180 for _, uriDomain := range uriDomains {
1181 if err = isIA5String(uriDomain); err != nil {
1185 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1186 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1187 b.AddBytes([]byte(uriDomain))
1195 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1200 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1205 var b cryptobyte.Builder
1206 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1207 if len(permitted) > 0 {
1208 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1209 b.AddBytes(permitted)
1213 if len(excluded) > 0 {
1214 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1215 b.AddBytes(excluded)
1220 ret[n].Value, err = b.Bytes()
1227 if len(template.CRLDistributionPoints) > 0 &&
1228 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1229 ret[n].Id = oidExtensionCRLDistributionPoints
1231 var crlDp []distributionPoint
1232 for _, name := range template.CRLDistributionPoints {
1233 dp := distributionPoint{
1234 DistributionPoint: distributionPointName{
1235 FullName: []asn1.RawValue{
1236 {Tag: 6, Class: 2, Bytes: []byte(name)},
1240 crlDp = append(crlDp, dp)
1243 ret[n].Value, err = asn1.Marshal(crlDp)
1250 // Adding another extension here? Remember to update the maximum number
1251 // of elements in the make() at the top of the function and the list of
1252 // template fields used in CreateCertificate documentation.
1254 return append(ret[:n], template.ExtraExtensions...), nil
1257 func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
1258 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
1261 a[0] = reverseBitsInAByte(byte(ku))
1262 a[1] = reverseBitsInAByte(byte(ku >> 8))
1271 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1275 func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
1276 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
1278 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
1279 for i, u := range extUsages {
1280 if oid, ok := oidFromExtKeyUsage(u); ok {
1283 return ext, errors.New("x509: unknown extended key usage")
1287 copy(oids[len(extUsages):], unknownUsages)
1290 ext.Value, err = asn1.Marshal(oids)
1294 func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
1295 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
1296 // Leaving MaxPathLen as zero indicates that no maximum path
1297 // length is desired, unless MaxPathLenZero is set. A value of
1298 // -1 causes encoding/asn1 to omit the value as desired.
1299 if maxPathLen == 0 && !maxPathLenZero {
1303 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
1307 func marshalCertificatePolicies(policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
1308 ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
1309 policies := make([]policyInformation, len(policyIdentifiers))
1310 for i, policy := range policyIdentifiers {
1311 policies[i].Policy = policy
1314 ext.Value, err = asn1.Marshal(policies)
1318 func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
1319 var ret []pkix.Extension
1321 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1322 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1323 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1328 ret = append(ret, pkix.Extension{
1329 Id: oidExtensionSubjectAltName,
1334 return append(ret, template.ExtraExtensions...), nil
1337 func subjectBytes(cert *Certificate) ([]byte, error) {
1338 if len(cert.RawSubject) > 0 {
1339 return cert.RawSubject, nil
1342 return asn1.Marshal(cert.Subject.ToRDNSequence())
1345 // signingParamsForPublicKey returns the parameters to use for signing with
1346 // priv. If requestedSigAlgo is not zero then it overrides the default
1347 // signature algorithm.
1348 func signingParamsForPublicKey(pub any, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1349 var pubType PublicKeyAlgorithm
1351 switch pub := pub.(type) {
1352 case *rsa.PublicKey:
1354 hashFunc = crypto.SHA256
1355 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1356 sigAlgo.Parameters = asn1.NullRawValue
1358 case *ecdsa.PublicKey:
1362 case elliptic.P224(), elliptic.P256():
1363 hashFunc = crypto.SHA256
1364 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1365 case elliptic.P384():
1366 hashFunc = crypto.SHA384
1367 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1368 case elliptic.P521():
1369 hashFunc = crypto.SHA512
1370 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1372 err = errors.New("x509: unknown elliptic curve")
1375 case ed25519.PublicKey:
1377 sigAlgo.Algorithm = oidSignatureEd25519
1380 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
1387 if requestedSigAlgo == 0 {
1392 for _, details := range signatureAlgorithmDetails {
1393 if details.algo == requestedSigAlgo {
1394 if details.pubKeyAlgo != pubType {
1395 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
1398 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
1399 if hashFunc == 0 && pubType != Ed25519 {
1400 err = errors.New("x509: cannot sign with hash function requested")
1403 if requestedSigAlgo.isRSAPSS() {
1404 sigAlgo.Parameters = hashToPSSParameters[hashFunc]
1412 err = errors.New("x509: unknown SignatureAlgorithm")
1418 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
1419 // just an empty SEQUENCE.
1420 var emptyASN1Subject = []byte{0x30, 0}
1422 // CreateCertificate creates a new X.509 v3 certificate based on a template.
1423 // The following members of template are currently used:
1426 // - BasicConstraintsValid
1427 // - CRLDistributionPoints
1430 // - ExcludedDNSDomains
1431 // - ExcludedEmailAddresses
1432 // - ExcludedIPRanges
1433 // - ExcludedURIDomains
1435 // - ExtraExtensions
1438 // - IssuingCertificateURL
1445 // - PermittedDNSDomains
1446 // - PermittedDNSDomainsCritical
1447 // - PermittedEmailAddresses
1448 // - PermittedIPRanges
1449 // - PermittedURIDomains
1450 // - PolicyIdentifiers
1452 // - SignatureAlgorithm
1456 // - UnknownExtKeyUsage
1458 // The certificate is signed by parent. If parent is equal to template then the
1459 // certificate is self-signed. The parameter pub is the public key of the
1460 // certificate to be generated and priv is the private key of the signer.
1462 // The returned slice is the certificate in DER encoding.
1464 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
1465 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
1466 // crypto.Signer with a supported public key.
1468 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
1469 // unless the resulting certificate is self-signed. Otherwise the value from
1470 // template will be used.
1472 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
1473 // will be generated from the hash of the public key.
1474 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv any) ([]byte, error) {
1475 key, ok := priv.(crypto.Signer)
1477 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1480 if template.SerialNumber == nil {
1481 return nil, errors.New("x509: no SerialNumber given")
1484 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
1485 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
1488 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1493 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1498 asn1Issuer, err := subjectBytes(parent)
1503 asn1Subject, err := subjectBytes(template)
1508 authorityKeyId := template.AuthorityKeyId
1509 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1510 authorityKeyId = parent.SubjectKeyId
1513 subjectKeyId := template.SubjectKeyId
1514 if len(subjectKeyId) == 0 && template.IsCA {
1515 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
1516 // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
1517 // value of the BIT STRING subjectPublicKey (excluding the tag,
1518 // length, and number of unused bits).
1519 h := sha1.Sum(publicKeyBytes)
1523 // Check that the signer's public key matches the private key, if available.
1524 type privateKey interface {
1525 Equal(crypto.PublicKey) bool
1527 if privPub, ok := key.Public().(privateKey); !ok {
1528 return nil, errors.New("x509: internal error: supported public key does not implement Equal")
1529 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
1530 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
1533 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
1538 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1539 c := tbsCertificate{
1541 SerialNumber: template.SerialNumber,
1542 SignatureAlgorithm: signatureAlgorithm,
1543 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1544 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1545 Subject: asn1.RawValue{FullBytes: asn1Subject},
1546 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1547 Extensions: extensions,
1550 tbsCertContents, err := asn1.Marshal(c)
1554 c.Raw = tbsCertContents
1556 signed := tbsCertContents
1563 var signerOpts crypto.SignerOpts = hashFunc
1564 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
1565 signerOpts = &rsa.PSSOptions{
1566 SaltLength: rsa.PSSSaltLengthEqualsHash,
1571 var signature []byte
1572 signature, err = key.Sign(rand, signed, signerOpts)
1577 signedCert, err := asn1.Marshal(certificate{
1581 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1587 // Check the signature to ensure the crypto.Signer behaved correctly.
1588 sigAlg := getSignatureAlgorithmFromAI(signatureAlgorithm)
1590 case MD5WithRSA, SHA1WithRSA, ECDSAWithSHA1:
1591 // We skip the check if the signature algorithm is only supported for
1592 // signing, not verification.
1594 if err := checkSignature(sigAlg, c.Raw, signature, key.Public()); err != nil {
1595 return nil, fmt.Errorf("x509: signature over certificate returned by signer is invalid: %w", err)
1599 return signedCert, nil
1602 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1604 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1606 // pemType is the type of a PEM encoded CRL.
1607 var pemType = "X509 CRL"
1609 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1610 // encoded CRLs will appear where they should be DER encoded, so this function
1611 // will transparently handle PEM encoding as long as there isn't any leading
1613 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1614 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1615 block, _ := pem.Decode(crlBytes)
1616 if block != nil && block.Type == pemType {
1617 crlBytes = block.Bytes
1620 return ParseDERCRL(crlBytes)
1623 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1624 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1625 certList := new(pkix.CertificateList)
1626 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
1628 } else if len(rest) != 0 {
1629 return nil, errors.New("x509: trailing data after CRL")
1631 return certList, nil
1634 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1635 // contains the given list of revoked certificates.
1637 // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
1638 // To generate a standards compliant CRL, use CreateRevocationList instead.
1639 func (c *Certificate) CreateCRL(rand io.Reader, priv any, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1640 key, ok := priv.(crypto.Signer)
1642 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1645 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
1650 // Force revocation times to UTC per RFC 5280.
1651 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
1652 for i, rc := range revokedCerts {
1653 rc.RevocationTime = rc.RevocationTime.UTC()
1654 revokedCertsUTC[i] = rc
1657 tbsCertList := pkix.TBSCertificateList{
1659 Signature: signatureAlgorithm,
1660 Issuer: c.Subject.ToRDNSequence(),
1661 ThisUpdate: now.UTC(),
1662 NextUpdate: expiry.UTC(),
1663 RevokedCertificates: revokedCertsUTC,
1667 if len(c.SubjectKeyId) > 0 {
1668 var aki pkix.Extension
1669 aki.Id = oidExtensionAuthorityKeyId
1670 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
1674 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
1677 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1682 signed := tbsCertListContents
1689 var signature []byte
1690 signature, err = key.Sign(rand, signed, hashFunc)
1695 return asn1.Marshal(pkix.CertificateList{
1696 TBSCertList: tbsCertList,
1697 SignatureAlgorithm: signatureAlgorithm,
1698 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1702 // CertificateRequest represents a PKCS #10, certificate signature request.
1703 type CertificateRequest struct {
1704 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
1705 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
1706 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
1707 RawSubject []byte // DER encoded Subject.
1711 SignatureAlgorithm SignatureAlgorithm
1713 PublicKeyAlgorithm PublicKeyAlgorithm
1718 // Attributes contains the CSR attributes that can parse as
1719 // pkix.AttributeTypeAndValueSET.
1721 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
1722 // generating the requestedExtensions attribute.
1723 Attributes []pkix.AttributeTypeAndValueSET
1725 // Extensions contains all requested extensions, in raw form. When parsing
1726 // CSRs, this can be used to extract extensions that are not parsed by this
1728 Extensions []pkix.Extension
1730 // ExtraExtensions contains extensions to be copied, raw, into any CSR
1731 // marshaled by CreateCertificateRequest. Values override any extensions
1732 // that would otherwise be produced based on the other fields but are
1733 // overridden by any extensions specified in Attributes.
1735 // The ExtraExtensions field is not populated by ParseCertificateRequest,
1736 // see Extensions instead.
1737 ExtraExtensions []pkix.Extension
1739 // Subject Alternate Name values.
1741 EmailAddresses []string
1742 IPAddresses []net.IP
1746 // These structures reflect the ASN.1 structure of X.509 certificate
1747 // signature requests (see RFC 2986):
1749 type tbsCertificateRequest struct {
1752 Subject asn1.RawValue
1753 PublicKey publicKeyInfo
1754 RawAttributes []asn1.RawValue `asn1:"tag:0"`
1757 type certificateRequest struct {
1759 TBSCSR tbsCertificateRequest
1760 SignatureAlgorithm pkix.AlgorithmIdentifier
1761 SignatureValue asn1.BitString
1764 // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
1765 // extensions in a CSR.
1766 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
1768 // newRawAttributes converts AttributeTypeAndValueSETs from a template
1769 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
1770 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
1771 var rawAttributes []asn1.RawValue
1772 b, err := asn1.Marshal(attributes)
1776 rest, err := asn1.Unmarshal(b, &rawAttributes)
1781 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
1783 return rawAttributes, nil
1786 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
1787 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
1788 var attributes []pkix.AttributeTypeAndValueSET
1789 for _, rawAttr := range rawAttributes {
1790 var attr pkix.AttributeTypeAndValueSET
1791 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
1792 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
1793 // (i.e.: challengePassword or unstructuredName).
1794 if err == nil && len(rest) == 0 {
1795 attributes = append(attributes, attr)
1801 // parseCSRExtensions parses the attributes from a CSR and extracts any
1802 // requested extensions.
1803 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
1804 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
1805 type pkcs10Attribute struct {
1806 Id asn1.ObjectIdentifier
1807 Values []asn1.RawValue `asn1:"set"`
1810 var ret []pkix.Extension
1811 for _, rawAttr := range rawAttributes {
1812 var attr pkcs10Attribute
1813 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
1814 // Ignore attributes that don't parse.
1818 if !attr.Id.Equal(oidExtensionRequest) {
1822 var extensions []pkix.Extension
1823 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
1826 ret = append(ret, extensions...)
1832 // CreateCertificateRequest creates a new certificate request based on a
1833 // template. The following members of template are used:
1835 // - SignatureAlgorithm
1841 // - ExtraExtensions
1842 // - Attributes (deprecated)
1844 // priv is the private key to sign the CSR with, and the corresponding public
1845 // key will be included in the CSR. It must implement crypto.Signer and its
1846 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
1847 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
1848 // ed25519.PrivateKey satisfies this.)
1850 // The returned slice is the certificate request in DER encoding.
1851 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv any) (csr []byte, err error) {
1852 key, ok := priv.(crypto.Signer)
1854 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1857 var hashFunc crypto.Hash
1858 var sigAlgo pkix.AlgorithmIdentifier
1859 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1864 var publicKeyBytes []byte
1865 var publicKeyAlgorithm pkix.AlgorithmIdentifier
1866 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
1871 extensions, err := buildCSRExtensions(template)
1876 // Make a copy of template.Attributes because we may alter it below.
1877 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
1878 for _, attr := range template.Attributes {
1879 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
1880 copy(values, attr.Value)
1881 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
1887 extensionsAppended := false
1888 if len(extensions) > 0 {
1889 // Append the extensions to an existing attribute if possible.
1890 for _, atvSet := range attributes {
1891 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
1895 // specifiedExtensions contains all the extensions that we
1896 // found specified via template.Attributes.
1897 specifiedExtensions := make(map[string]bool)
1899 for _, atvs := range atvSet.Value {
1900 for _, atv := range atvs {
1901 specifiedExtensions[atv.Type.String()] = true
1905 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
1906 newValue = append(newValue, atvSet.Value[0]...)
1908 for _, e := range extensions {
1909 if specifiedExtensions[e.Id.String()] {
1910 // Attributes already contained a value for
1911 // this extension and it takes priority.
1915 newValue = append(newValue, pkix.AttributeTypeAndValue{
1916 // There is no place for the critical
1917 // flag in an AttributeTypeAndValue.
1923 atvSet.Value[0] = newValue
1924 extensionsAppended = true
1929 rawAttributes, err := newRawAttributes(attributes)
1934 // If not included in attributes, add a new attribute for the
1936 if len(extensions) > 0 && !extensionsAppended {
1938 Type asn1.ObjectIdentifier
1939 Value [][]pkix.Extension `asn1:"set"`
1941 Type: oidExtensionRequest,
1942 Value: [][]pkix.Extension{extensions},
1945 b, err := asn1.Marshal(attr)
1947 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
1950 var rawValue asn1.RawValue
1951 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
1955 rawAttributes = append(rawAttributes, rawValue)
1958 asn1Subject := template.RawSubject
1959 if len(asn1Subject) == 0 {
1960 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
1966 tbsCSR := tbsCertificateRequest{
1967 Version: 0, // PKCS #10, RFC 2986
1968 Subject: asn1.RawValue{FullBytes: asn1Subject},
1969 PublicKey: publicKeyInfo{
1970 Algorithm: publicKeyAlgorithm,
1971 PublicKey: asn1.BitString{
1972 Bytes: publicKeyBytes,
1973 BitLength: len(publicKeyBytes) * 8,
1976 RawAttributes: rawAttributes,
1979 tbsCSRContents, err := asn1.Marshal(tbsCSR)
1983 tbsCSR.Raw = tbsCSRContents
1985 signed := tbsCSRContents
1992 var signature []byte
1993 signature, err = key.Sign(rand, signed, hashFunc)
1998 return asn1.Marshal(certificateRequest{
2000 SignatureAlgorithm: sigAlgo,
2001 SignatureValue: asn1.BitString{
2003 BitLength: len(signature) * 8,
2008 // ParseCertificateRequest parses a single certificate request from the
2009 // given ASN.1 DER data.
2010 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2011 var csr certificateRequest
2013 rest, err := asn1.Unmarshal(asn1Data, &csr)
2016 } else if len(rest) != 0 {
2017 return nil, asn1.SyntaxError{Msg: "trailing data"}
2020 return parseCertificateRequest(&csr)
2023 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2024 out := &CertificateRequest{
2026 RawTBSCertificateRequest: in.TBSCSR.Raw,
2027 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2028 RawSubject: in.TBSCSR.Subject.FullBytes,
2030 Signature: in.SignatureValue.RightAlign(),
2031 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2033 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2035 Version: in.TBSCSR.Version,
2036 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2040 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2045 var subject pkix.RDNSequence
2046 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2048 } else if len(rest) != 0 {
2049 return nil, errors.New("x509: trailing data after X.509 Subject")
2052 out.Subject.FillFromRDNSequence(&subject)
2054 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2058 for _, extension := range out.Extensions {
2060 case extension.Id.Equal(oidExtensionSubjectAltName):
2061 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2071 // CheckSignature reports whether the signature on c is valid.
2072 func (c *CertificateRequest) CheckSignature() error {
2073 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
2076 // RevocationList contains the fields used to create an X.509 v2 Certificate
2077 // Revocation list with CreateRevocationList.
2078 type RevocationList struct {
2079 // SignatureAlgorithm is used to determine the signature algorithm to be
2080 // used when signing the CRL. If 0 the default algorithm for the signing
2081 // key will be used.
2082 SignatureAlgorithm SignatureAlgorithm
2084 // RevokedCertificates is used to populate the revokedCertificates
2085 // sequence in the CRL, it may be empty. RevokedCertificates may be nil,
2086 // in which case an empty CRL will be created.
2087 RevokedCertificates []pkix.RevokedCertificate
2089 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2090 // which should be a monotonically increasing sequence number for a given
2091 // CRL scope and CRL issuer.
2093 // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2094 // indicates the issuance date of the CRL.
2095 ThisUpdate time.Time
2096 // NextUpdate is used to populate the nextUpdate field in the CRL, which
2097 // indicates the date by which the next CRL will be issued. NextUpdate
2098 // must be greater than ThisUpdate.
2099 NextUpdate time.Time
2100 // ExtraExtensions contains any additional extensions to add directly to
2102 ExtraExtensions []pkix.Extension
2105 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
2106 // according to RFC 5280, based on template.
2108 // The CRL is signed by priv which should be the private key associated with
2109 // the public key in the issuer certificate.
2111 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
2112 // order to use it as a CRL issuer.
2114 // The issuer distinguished name CRL field and authority key identifier
2115 // extension are populated using the issuer certificate. issuer must have
2116 // SubjectKeyId set.
2117 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2118 if template == nil {
2119 return nil, errors.New("x509: template can not be nil")
2122 return nil, errors.New("x509: issuer can not be nil")
2124 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2125 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2127 if len(issuer.SubjectKeyId) == 0 {
2128 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2130 if template.NextUpdate.Before(template.ThisUpdate) {
2131 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2133 if template.Number == nil {
2134 return nil, errors.New("x509: template contains nil Number field")
2137 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2142 // Force revocation times to UTC per RFC 5280.
2143 revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2144 for i, rc := range template.RevokedCertificates {
2145 rc.RevocationTime = rc.RevocationTime.UTC()
2146 revokedCertsUTC[i] = rc
2149 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2153 crlNum, err := asn1.Marshal(template.Number)
2158 tbsCertList := pkix.TBSCertificateList{
2160 Signature: signatureAlgorithm,
2161 Issuer: issuer.Subject.ToRDNSequence(),
2162 ThisUpdate: template.ThisUpdate.UTC(),
2163 NextUpdate: template.NextUpdate.UTC(),
2164 Extensions: []pkix.Extension{
2166 Id: oidExtensionAuthorityKeyId,
2170 Id: oidExtensionCRLNumber,
2175 if len(revokedCertsUTC) > 0 {
2176 tbsCertList.RevokedCertificates = revokedCertsUTC
2179 if len(template.ExtraExtensions) > 0 {
2180 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2183 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2188 input := tbsCertListContents
2191 h.Write(tbsCertListContents)
2194 var signerOpts crypto.SignerOpts = hashFunc
2195 if template.SignatureAlgorithm.isRSAPSS() {
2196 signerOpts = &rsa.PSSOptions{
2197 SaltLength: rsa.PSSSaltLengthEqualsHash,
2202 signature, err := priv.Sign(rand, input, signerOpts)
2207 return asn1.Marshal(pkix.CertificateList{
2208 TBSCertList: tbsCertList,
2209 SignatureAlgorithm: signatureAlgorithm,
2210 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},