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.
34 "golang.org/x/crypto/cryptobyte"
35 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
38 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
40 type pkixPublicKey struct {
41 Algo pkix.AlgorithmIdentifier
42 BitString asn1.BitString
45 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
46 // The encoded public key is a SubjectPublicKeyInfo structure
47 // (see RFC 5280, Section 4.1).
49 // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
50 // ed25519.PublicKey. More types might be supported in the future.
52 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
53 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
55 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
56 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
57 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
60 } else if len(rest) != 0 {
61 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
63 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
64 if algo == UnknownPublicKeyAlgorithm {
65 return nil, errors.New("x509: unknown public key algorithm")
67 return parsePublicKey(algo, &pki)
70 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
71 switch pub := pub.(type) {
73 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
78 return nil, pkix.AlgorithmIdentifier{}, err
80 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
81 // This is a NULL parameters value which is required by
82 // RFC 3279, Section 2.3.1.
83 publicKeyAlgorithm.Parameters = asn1.NullRawValue
84 case *ecdsa.PublicKey:
85 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
86 oid, ok := oidFromNamedCurve(pub.Curve)
88 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
90 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
92 paramBytes, err = asn1.Marshal(oid)
96 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
97 case ed25519.PublicKey:
99 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
101 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
104 return publicKeyBytes, publicKeyAlgorithm, nil
107 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
108 // The encoded public key is a SubjectPublicKeyInfo structure
109 // (see RFC 5280, Section 4.1).
111 // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
112 // and ed25519.PublicKey. Unsupported key types result in an error.
114 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
115 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
116 var publicKeyBytes []byte
117 var publicKeyAlgorithm pkix.AlgorithmIdentifier
120 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
124 pkix := pkixPublicKey{
125 Algo: publicKeyAlgorithm,
126 BitString: asn1.BitString{
127 Bytes: publicKeyBytes,
128 BitLength: 8 * len(publicKeyBytes),
132 ret, _ := asn1.Marshal(pkix)
136 // These structures reflect the ASN.1 structure of X.509 certificates.:
138 type certificate struct {
140 TBSCertificate tbsCertificate
141 SignatureAlgorithm pkix.AlgorithmIdentifier
142 SignatureValue asn1.BitString
145 type tbsCertificate struct {
147 Version int `asn1:"optional,explicit,default:0,tag:0"`
148 SerialNumber *big.Int
149 SignatureAlgorithm pkix.AlgorithmIdentifier
152 Subject asn1.RawValue
153 PublicKey publicKeyInfo
154 UniqueId asn1.BitString `asn1:"optional,tag:1"`
155 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
156 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
159 type dsaAlgorithmParameters struct {
163 type dsaSignature struct {
167 type validity struct {
168 NotBefore, NotAfter time.Time
171 type publicKeyInfo struct {
173 Algorithm pkix.AlgorithmIdentifier
174 PublicKey asn1.BitString
178 type authKeyId struct {
179 Id []byte `asn1:"optional,tag:0"`
182 type SignatureAlgorithm int
185 UnknownSignatureAlgorithm SignatureAlgorithm = iota
204 func (algo SignatureAlgorithm) isRSAPSS() bool {
206 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
213 func (algo SignatureAlgorithm) String() string {
214 for _, details := range signatureAlgorithmDetails {
215 if details.algo == algo {
219 return strconv.Itoa(int(algo))
222 type PublicKeyAlgorithm int
225 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
232 var publicKeyAlgoName = [...]string{
239 func (algo PublicKeyAlgorithm) String() string {
240 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
241 return publicKeyAlgoName[algo]
243 return strconv.Itoa(int(algo))
246 // OIDs for signature algorithms
248 // pkcs-1 OBJECT IDENTIFIER ::= {
249 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
252 // RFC 3279 2.2.1 RSA Signature Algorithms
254 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
256 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
258 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
260 // dsaWithSha1 OBJECT IDENTIFIER ::= {
261 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
263 // RFC 3279 2.2.3 ECDSA Signature Algorithm
265 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
266 // iso(1) member-body(2) us(840) ansi-x962(10045)
267 // signatures(4) ecdsa-with-SHA1(1)}
270 // RFC 4055 5 PKCS #1 Version 1.5
272 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
274 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
276 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
279 // RFC 5758 3.1 DSA Signature Algorithms
281 // dsaWithSha256 OBJECT IDENTIFIER ::= {
282 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
283 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
285 // RFC 5758 3.2 ECDSA Signature Algorithm
287 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
288 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
290 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
291 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
293 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
294 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
297 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
299 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
302 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
303 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
304 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
305 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
306 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
307 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
308 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
309 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
310 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
311 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
312 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
313 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
314 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
315 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
317 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
318 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
319 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
321 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
323 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
324 // but it's specified by ISO. Microsoft's makecert.exe has been known
325 // to produce certificates with this OID.
326 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
329 var signatureAlgorithmDetails = []struct {
330 algo SignatureAlgorithm
332 oid asn1.ObjectIdentifier
333 pubKeyAlgo PublicKeyAlgorithm
336 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
337 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
338 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
339 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
340 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
341 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
342 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
343 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
344 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
345 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
346 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
347 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
348 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
349 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
350 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
351 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
352 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
355 // pssParameters reflects the parameters in an AlgorithmIdentifier that
356 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
357 type pssParameters struct {
358 // The following three fields are not marked as
359 // optional because the default values specify SHA-1,
360 // which is no longer suitable for use in signatures.
361 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
362 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
363 SaltLength int `asn1:"explicit,tag:2"`
364 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
367 // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
368 // in an AlgorithmIdentifier that specifies RSA PSS.
369 func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue {
370 var hashOID asn1.ObjectIdentifier
381 params := pssParameters{
382 Hash: pkix.AlgorithmIdentifier{
384 Parameters: asn1.NullRawValue,
386 MGF: pkix.AlgorithmIdentifier{
389 SaltLength: hashFunc.Size(),
393 mgf1Params := pkix.AlgorithmIdentifier{
395 Parameters: asn1.NullRawValue,
399 params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
404 serialized, err := asn1.Marshal(params)
409 return asn1.RawValue{FullBytes: serialized}
412 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
413 if ai.Algorithm.Equal(oidSignatureEd25519) {
414 // RFC 8410, Section 3
415 // > For all of the OIDs, the parameters MUST be absent.
416 if len(ai.Parameters.FullBytes) != 0 {
417 return UnknownSignatureAlgorithm
421 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
422 for _, details := range signatureAlgorithmDetails {
423 if ai.Algorithm.Equal(details.oid) {
427 return UnknownSignatureAlgorithm
430 // RSA PSS is special because it encodes important parameters
431 // in the Parameters.
433 var params pssParameters
434 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
435 return UnknownSignatureAlgorithm
438 var mgf1HashFunc pkix.AlgorithmIdentifier
439 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
440 return UnknownSignatureAlgorithm
443 // PSS is greatly overburdened with options. This code forces them into
444 // three buckets by requiring that the MGF1 hash function always match the
445 // message hash function (as recommended in RFC 3447, Section 8.1), that the
446 // salt length matches the hash length, and that the trailer field has the
448 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
449 !params.MGF.Algorithm.Equal(oidMGF1) ||
450 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
451 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
452 params.TrailerField != 1 {
453 return UnknownSignatureAlgorithm
457 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
458 return SHA256WithRSAPSS
459 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
460 return SHA384WithRSAPSS
461 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
462 return SHA512WithRSAPSS
465 return UnknownSignatureAlgorithm
468 // RFC 3279, 2.3 Public Key Algorithms
470 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
471 // rsadsi(113549) pkcs(1) 1 }
473 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
475 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
476 // x9-57(10040) x9cm(4) 1 }
478 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
480 // id-ecPublicKey OBJECT IDENTIFIER ::= {
481 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
483 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
484 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
485 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
486 oidPublicKeyEd25519 = oidSignatureEd25519
489 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
491 case oid.Equal(oidPublicKeyRSA):
493 case oid.Equal(oidPublicKeyDSA):
495 case oid.Equal(oidPublicKeyECDSA):
497 case oid.Equal(oidPublicKeyEd25519):
500 return UnknownPublicKeyAlgorithm
503 // RFC 5480, 2.1.1.1. Named Curve
505 // secp224r1 OBJECT IDENTIFIER ::= {
506 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
508 // secp256r1 OBJECT IDENTIFIER ::= {
509 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
512 // secp384r1 OBJECT IDENTIFIER ::= {
513 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
515 // secp521r1 OBJECT IDENTIFIER ::= {
516 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
518 // NB: secp256r1 is equivalent to prime256v1
520 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
521 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
522 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
523 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
526 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
528 case oid.Equal(oidNamedCurveP224):
529 return elliptic.P224()
530 case oid.Equal(oidNamedCurveP256):
531 return elliptic.P256()
532 case oid.Equal(oidNamedCurveP384):
533 return elliptic.P384()
534 case oid.Equal(oidNamedCurveP521):
535 return elliptic.P521()
540 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
542 case elliptic.P224():
543 return oidNamedCurveP224, true
544 case elliptic.P256():
545 return oidNamedCurveP256, true
546 case elliptic.P384():
547 return oidNamedCurveP384, true
548 case elliptic.P521():
549 return oidNamedCurveP521, true
555 // KeyUsage represents the set of actions that are valid for a given key. It's
556 // a bitmap of the KeyUsage* constants.
560 KeyUsageDigitalSignature KeyUsage = 1 << iota
561 KeyUsageContentCommitment
562 KeyUsageKeyEncipherment
563 KeyUsageDataEncipherment
571 // RFC 5280, 4.2.1.12 Extended Key Usage
573 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
575 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
577 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
578 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
579 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
580 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
581 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
582 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
584 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
585 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
586 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
587 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
588 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
589 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
590 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
591 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
592 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
593 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
594 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
595 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
596 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
597 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
600 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
601 // Each of the ExtKeyUsage* constants define a unique action.
605 ExtKeyUsageAny ExtKeyUsage = iota
606 ExtKeyUsageServerAuth
607 ExtKeyUsageClientAuth
608 ExtKeyUsageCodeSigning
609 ExtKeyUsageEmailProtection
610 ExtKeyUsageIPSECEndSystem
611 ExtKeyUsageIPSECTunnel
613 ExtKeyUsageTimeStamping
614 ExtKeyUsageOCSPSigning
615 ExtKeyUsageMicrosoftServerGatedCrypto
616 ExtKeyUsageNetscapeServerGatedCrypto
617 ExtKeyUsageMicrosoftCommercialCodeSigning
618 ExtKeyUsageMicrosoftKernelCodeSigning
621 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
622 var extKeyUsageOIDs = []struct {
623 extKeyUsage ExtKeyUsage
624 oid asn1.ObjectIdentifier
626 {ExtKeyUsageAny, oidExtKeyUsageAny},
627 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
628 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
629 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
630 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
631 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
632 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
633 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
634 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
635 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
636 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
637 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
638 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
639 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
642 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
643 for _, pair := range extKeyUsageOIDs {
644 if oid.Equal(pair.oid) {
645 return pair.extKeyUsage, true
651 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
652 for _, pair := range extKeyUsageOIDs {
653 if eku == pair.extKeyUsage {
654 return pair.oid, true
660 // A Certificate represents an X.509 certificate.
661 type Certificate struct {
662 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
663 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
664 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
665 RawSubject []byte // DER encoded Subject
666 RawIssuer []byte // DER encoded Issuer
669 SignatureAlgorithm SignatureAlgorithm
671 PublicKeyAlgorithm PublicKeyAlgorithm
672 PublicKey interface{}
675 SerialNumber *big.Int
678 NotBefore, NotAfter time.Time // Validity bounds.
681 // Extensions contains raw X.509 extensions. When parsing certificates,
682 // this can be used to extract non-critical extensions that are not
683 // parsed by this package. When marshaling certificates, the Extensions
684 // field is ignored, see ExtraExtensions.
685 Extensions []pkix.Extension
687 // ExtraExtensions contains extensions to be copied, raw, into any
688 // marshaled certificates. Values override any extensions that would
689 // otherwise be produced based on the other fields. The ExtraExtensions
690 // field is not populated when parsing certificates, see Extensions.
691 ExtraExtensions []pkix.Extension
693 // UnhandledCriticalExtensions contains a list of extension IDs that
694 // were not (fully) processed when parsing. Verify will fail if this
695 // slice is non-empty, unless verification is delegated to an OS
696 // library which understands all the critical extensions.
698 // Users can access these extensions using Extensions and can remove
699 // elements from this slice if they believe that they have been
701 UnhandledCriticalExtensions []asn1.ObjectIdentifier
703 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
704 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
706 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
707 // and MaxPathLenZero are valid.
708 BasicConstraintsValid bool
711 // MaxPathLen and MaxPathLenZero indicate the presence and
712 // value of the BasicConstraints' "pathLenConstraint".
714 // When parsing a certificate, a positive non-zero MaxPathLen
715 // means that the field was specified, -1 means it was unset,
716 // and MaxPathLenZero being true mean that the field was
717 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
718 // should be treated equivalent to -1 (unset).
720 // When generating a certificate, an unset pathLenConstraint
721 // can be requested with either MaxPathLen == -1 or using the
722 // zero value for both MaxPathLen and MaxPathLenZero.
724 // MaxPathLenZero indicates that BasicConstraintsValid==true
725 // and MaxPathLen==0 should be interpreted as an actual
726 // maximum path length of zero. Otherwise, that combination is
727 // interpreted as MaxPathLen not being set.
731 AuthorityKeyId []byte
733 // RFC 5280, 4.2.2.1 (Authority Information Access)
735 IssuingCertificateURL []string
737 // Subject Alternate Name values. (Note that these values may not be valid
738 // if invalid values were contained within a parsed certificate. For
739 // example, an element of DNSNames may not be a valid DNS domain name.)
741 EmailAddresses []string
746 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
747 PermittedDNSDomains []string
748 ExcludedDNSDomains []string
749 PermittedIPRanges []*net.IPNet
750 ExcludedIPRanges []*net.IPNet
751 PermittedEmailAddresses []string
752 ExcludedEmailAddresses []string
753 PermittedURIDomains []string
754 ExcludedURIDomains []string
756 // CRL Distribution Points
757 CRLDistributionPoints []string
759 PolicyIdentifiers []asn1.ObjectIdentifier
762 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
763 // involves algorithms that are not currently implemented.
764 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
766 // An InsecureAlgorithmError
767 type InsecureAlgorithmError SignatureAlgorithm
769 func (e InsecureAlgorithmError) Error() string {
770 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
773 // ConstraintViolationError results when a requested usage is not permitted by
774 // a certificate. For example: checking a signature when the public key isn't a
775 // certificate signing key.
776 type ConstraintViolationError struct{}
778 func (ConstraintViolationError) Error() string {
779 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
782 func (c *Certificate) Equal(other *Certificate) bool {
783 if c == nil || other == nil {
786 return bytes.Equal(c.Raw, other.Raw)
789 func (c *Certificate) hasSANExtension() bool {
790 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
793 // CheckSignatureFrom verifies that the signature on c is a valid signature
795 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
796 // RFC 5280, 4.2.1.9:
797 // "If the basic constraints extension is not present in a version 3
798 // certificate, or the extension is present but the cA boolean is not
799 // asserted, then the certified public key MUST NOT be used to verify
800 // certificate signatures."
801 if parent.Version == 3 && !parent.BasicConstraintsValid ||
802 parent.BasicConstraintsValid && !parent.IsCA {
803 return ConstraintViolationError{}
806 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
807 return ConstraintViolationError{}
810 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
811 return ErrUnsupportedAlgorithm
814 // TODO(agl): don't ignore the path length constraint.
816 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
819 // CheckSignature verifies that signature is a valid signature over signed from
821 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
822 return checkSignature(algo, signed, signature, c.PublicKey)
825 func (c *Certificate) hasNameConstraints() bool {
826 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
829 func (c *Certificate) getSANExtension() []byte {
830 for _, e := range c.Extensions {
831 if e.Id.Equal(oidExtensionSubjectAltName) {
838 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
839 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
842 // CheckSignature verifies that signature is a valid signature over signed from
843 // a crypto.PublicKey.
844 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
845 var hashType crypto.Hash
846 var pubKeyAlgo PublicKeyAlgorithm
848 for _, details := range signatureAlgorithmDetails {
849 if details.algo == algo {
850 hashType = details.hash
851 pubKeyAlgo = details.pubKeyAlgo
857 if pubKeyAlgo != Ed25519 {
858 return ErrUnsupportedAlgorithm
861 return InsecureAlgorithmError(algo)
863 if !hashType.Available() {
864 return ErrUnsupportedAlgorithm
871 switch pub := publicKey.(type) {
873 if pubKeyAlgo != RSA {
874 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
877 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
879 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
882 if pubKeyAlgo != DSA {
883 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
885 dsaSig := new(dsaSignature)
886 if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
888 } else if len(rest) != 0 {
889 return errors.New("x509: trailing data after DSA signature")
891 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
892 return errors.New("x509: DSA signature contained zero or negative values")
894 // According to FIPS 186-3, section 4.6, the hash must be truncated if it is longer
895 // than the key length, but crypto/dsa doesn't do it automatically.
896 if maxHashLen := pub.Q.BitLen() / 8; maxHashLen < len(signed) {
897 signed = signed[:maxHashLen]
899 if !dsa.Verify(pub, signed, dsaSig.R, dsaSig.S) {
900 return errors.New("x509: DSA verification failure")
903 case *ecdsa.PublicKey:
904 if pubKeyAlgo != ECDSA {
905 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
907 if !ecdsa.VerifyASN1(pub, signed, signature) {
908 return errors.New("x509: ECDSA verification failure")
911 case ed25519.PublicKey:
912 if pubKeyAlgo != Ed25519 {
913 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
915 if !ed25519.Verify(pub, signed, signature) {
916 return errors.New("x509: Ed25519 verification failure")
920 return ErrUnsupportedAlgorithm
923 // CheckCRLSignature checks that the signature in crl is from c.
924 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
925 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
926 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
929 type UnhandledCriticalExtension struct{}
931 func (h UnhandledCriticalExtension) Error() string {
932 return "x509: unhandled critical extension"
935 type basicConstraints struct {
936 IsCA bool `asn1:"optional"`
937 MaxPathLen int `asn1:"optional,default:-1"`
941 type policyInformation struct {
942 Policy asn1.ObjectIdentifier
943 // policyQualifiers omitted
954 type authorityInfoAccess struct {
955 Method asn1.ObjectIdentifier
956 Location asn1.RawValue
959 // RFC 5280, 4.2.1.14
960 type distributionPoint struct {
961 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
962 Reason asn1.BitString `asn1:"optional,tag:1"`
963 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
966 type distributionPointName struct {
967 FullName []asn1.RawValue `asn1:"optional,tag:0"`
968 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
971 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
972 asn1Data := keyData.PublicKey.RightAlign()
975 // RSA public keys must have a NULL in the parameters.
976 // See RFC 3279, Section 2.3.1.
977 if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
978 return nil, errors.New("x509: RSA key missing NULL parameters")
981 p := new(pkcs1PublicKey)
982 rest, err := asn1.Unmarshal(asn1Data, p)
987 return nil, errors.New("x509: trailing data after RSA public key")
991 return nil, errors.New("x509: RSA modulus is not a positive number")
994 return nil, errors.New("x509: RSA public exponent is not a positive number")
997 pub := &rsa.PublicKey{
1004 rest, err := asn1.Unmarshal(asn1Data, &p)
1009 return nil, errors.New("x509: trailing data after DSA public key")
1011 paramsData := keyData.Algorithm.Parameters.FullBytes
1012 params := new(dsaAlgorithmParameters)
1013 rest, err = asn1.Unmarshal(paramsData, params)
1018 return nil, errors.New("x509: trailing data after DSA parameters")
1020 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
1021 return nil, errors.New("x509: zero or negative DSA parameter")
1023 pub := &dsa.PublicKey{
1024 Parameters: dsa.Parameters{
1033 paramsData := keyData.Algorithm.Parameters.FullBytes
1034 namedCurveOID := new(asn1.ObjectIdentifier)
1035 rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
1037 return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
1040 return nil, errors.New("x509: trailing data after ECDSA parameters")
1042 namedCurve := namedCurveFromOID(*namedCurveOID)
1043 if namedCurve == nil {
1044 return nil, errors.New("x509: unsupported elliptic curve")
1046 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
1048 return nil, errors.New("x509: failed to unmarshal elliptic curve point")
1050 pub := &ecdsa.PublicKey{
1057 // RFC 8410, Section 3
1058 // > For all of the OIDs, the parameters MUST be absent.
1059 if len(keyData.Algorithm.Parameters.FullBytes) != 0 {
1060 return nil, errors.New("x509: Ed25519 key encoded with illegal parameters")
1062 if len(asn1Data) != ed25519.PublicKeySize {
1063 return nil, errors.New("x509: wrong Ed25519 public key size")
1065 pub := make([]byte, ed25519.PublicKeySize)
1067 return ed25519.PublicKey(pub), nil
1073 func forEachSAN(extension []byte, callback func(tag int, data []byte) error) error {
1074 // RFC 5280, 4.2.1.6
1076 // SubjectAltName ::= GeneralNames
1078 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1080 // GeneralName ::= CHOICE {
1081 // otherName [0] OtherName,
1082 // rfc822Name [1] IA5String,
1083 // dNSName [2] IA5String,
1084 // x400Address [3] ORAddress,
1085 // directoryName [4] Name,
1086 // ediPartyName [5] EDIPartyName,
1087 // uniformResourceIdentifier [6] IA5String,
1088 // iPAddress [7] OCTET STRING,
1089 // registeredID [8] OBJECT IDENTIFIER }
1090 var seq asn1.RawValue
1091 rest, err := asn1.Unmarshal(extension, &seq)
1094 } else if len(rest) != 0 {
1095 return errors.New("x509: trailing data after X.509 extension")
1097 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
1098 return asn1.StructuralError{Msg: "bad SAN sequence"}
1104 rest, err = asn1.Unmarshal(rest, &v)
1109 if err := callback(v.Tag, v.Bytes); err != nil {
1117 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
1118 err = forEachSAN(value, func(tag int, data []byte) error {
1121 emailAddresses = append(emailAddresses, string(data))
1123 dnsNames = append(dnsNames, string(data))
1125 uri, err := url.Parse(string(data))
1127 return fmt.Errorf("x509: cannot parse URI %q: %s", string(data), err)
1129 if len(uri.Host) > 0 {
1130 if _, ok := domainToReverseLabels(uri.Host); !ok {
1131 return fmt.Errorf("x509: cannot parse URI %q: invalid domain", string(data))
1134 uris = append(uris, uri)
1137 case net.IPv4len, net.IPv6len:
1138 ipAddresses = append(ipAddresses, data)
1140 return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
1150 // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
1151 func isValidIPMask(mask []byte) bool {
1154 for _, b := range mask {
1164 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
1175 func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) {
1176 // RFC 5280, 4.2.1.10
1178 // NameConstraints ::= SEQUENCE {
1179 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
1180 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
1182 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
1184 // GeneralSubtree ::= SEQUENCE {
1185 // base GeneralName,
1186 // minimum [0] BaseDistance DEFAULT 0,
1187 // maximum [1] BaseDistance OPTIONAL }
1189 // BaseDistance ::= INTEGER (0..MAX)
1191 outer := cryptobyte.String(e.Value)
1192 var toplevel, permitted, excluded cryptobyte.String
1193 var havePermitted, haveExcluded bool
1194 if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
1196 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
1197 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
1199 return false, errors.New("x509: invalid NameConstraints extension")
1202 if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
1203 // From RFC 5280, Section 4.2.1.10:
1204 // “either the permittedSubtrees field
1205 // or the excludedSubtrees MUST be
1207 return false, errors.New("x509: empty name constraints extension")
1210 getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
1211 for !subtrees.Empty() {
1212 var seq, value cryptobyte.String
1213 var tag cryptobyte_asn1.Tag
1214 if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
1215 !seq.ReadAnyASN1(&value, &tag) {
1216 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
1220 dnsTag = cryptobyte_asn1.Tag(2).ContextSpecific()
1221 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
1222 ipTag = cryptobyte_asn1.Tag(7).ContextSpecific()
1223 uriTag = cryptobyte_asn1.Tag(6).ContextSpecific()
1228 domain := string(value)
1229 if err := isIA5String(domain); err != nil {
1230 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1233 trimmedDomain := domain
1234 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1235 // constraints can have a leading
1236 // period to exclude the domain
1237 // itself, but that's not valid in a
1238 // normal domain name.
1239 trimmedDomain = trimmedDomain[1:]
1241 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1242 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
1244 dnsNames = append(dnsNames, domain)
1260 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
1263 if !isValidIPMask(mask) {
1264 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
1267 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
1270 constraint := string(value)
1271 if err := isIA5String(constraint); err != nil {
1272 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1275 // If the constraint contains an @ then
1276 // it specifies an exact mailbox name.
1277 if strings.Contains(constraint, "@") {
1278 if _, ok := parseRFC2821Mailbox(constraint); !ok {
1279 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1282 // Otherwise it's a domain name.
1283 domain := constraint
1284 if len(domain) > 0 && domain[0] == '.' {
1287 if _, ok := domainToReverseLabels(domain); !ok {
1288 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1291 emails = append(emails, constraint)
1294 domain := string(value)
1295 if err := isIA5String(domain); err != nil {
1296 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1299 if net.ParseIP(domain) != nil {
1300 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
1303 trimmedDomain := domain
1304 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1305 // constraints can have a leading
1306 // period to exclude the domain itself,
1307 // but that's not valid in a normal
1309 trimmedDomain = trimmedDomain[1:]
1311 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1312 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain)
1314 uriDomains = append(uriDomains, domain)
1321 return dnsNames, ips, emails, uriDomains, nil
1324 if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
1327 if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
1330 out.PermittedDNSDomainsCritical = e.Critical
1332 return unhandled, nil
1335 func parseCertificate(in *certificate) (*Certificate, error) {
1336 out := new(Certificate)
1338 out.RawTBSCertificate = in.TBSCertificate.Raw
1339 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
1340 out.RawSubject = in.TBSCertificate.Subject.FullBytes
1341 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
1343 out.Signature = in.SignatureValue.RightAlign()
1344 out.SignatureAlgorithm =
1345 getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
1347 out.PublicKeyAlgorithm =
1348 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
1350 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
1355 out.Version = in.TBSCertificate.Version + 1
1356 out.SerialNumber = in.TBSCertificate.SerialNumber
1358 var issuer, subject pkix.RDNSequence
1359 if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
1361 } else if len(rest) != 0 {
1362 return nil, errors.New("x509: trailing data after X.509 subject")
1364 if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
1366 } else if len(rest) != 0 {
1367 return nil, errors.New("x509: trailing data after X.509 issuer")
1370 out.Issuer.FillFromRDNSequence(&issuer)
1371 out.Subject.FillFromRDNSequence(&subject)
1373 out.NotBefore = in.TBSCertificate.Validity.NotBefore
1374 out.NotAfter = in.TBSCertificate.Validity.NotAfter
1376 for _, e := range in.TBSCertificate.Extensions {
1377 out.Extensions = append(out.Extensions, e)
1380 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
1383 // RFC 5280, 4.2.1.3
1384 var usageBits asn1.BitString
1385 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
1387 } else if len(rest) != 0 {
1388 return nil, errors.New("x509: trailing data after X.509 KeyUsage")
1392 for i := 0; i < 9; i++ {
1393 if usageBits.At(i) != 0 {
1394 usage |= 1 << uint(i)
1397 out.KeyUsage = KeyUsage(usage)
1400 // RFC 5280, 4.2.1.9
1401 var constraints basicConstraints
1402 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1404 } else if len(rest) != 0 {
1405 return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
1408 out.BasicConstraintsValid = true
1409 out.IsCA = constraints.IsCA
1410 out.MaxPathLen = constraints.MaxPathLen
1411 out.MaxPathLenZero = out.MaxPathLen == 0
1412 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
1414 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value)
1419 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
1420 // If we didn't parse anything then we do the critical check, below.
1425 unhandled, err = parseNameConstraintsExtension(out, e)
1431 // RFC 5280, 4.2.1.13
1433 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1435 // DistributionPoint ::= SEQUENCE {
1436 // distributionPoint [0] DistributionPointName OPTIONAL,
1437 // reasons [1] ReasonFlags OPTIONAL,
1438 // cRLIssuer [2] GeneralNames OPTIONAL }
1440 // DistributionPointName ::= CHOICE {
1441 // fullName [0] GeneralNames,
1442 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
1444 var cdp []distributionPoint
1445 if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
1447 } else if len(rest) != 0 {
1448 return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
1451 for _, dp := range cdp {
1452 // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
1453 if len(dp.DistributionPoint.FullName) == 0 {
1457 for _, fullName := range dp.DistributionPoint.FullName {
1458 if fullName.Tag == 6 {
1459 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(fullName.Bytes))
1465 // RFC 5280, 4.2.1.1
1467 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
1469 } else if len(rest) != 0 {
1470 return nil, errors.New("x509: trailing data after X.509 authority key-id")
1472 out.AuthorityKeyId = a.Id
1475 // RFC 5280, 4.2.1.12. Extended Key Usage
1477 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1479 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1481 // KeyPurposeId ::= OBJECT IDENTIFIER
1483 var keyUsage []asn1.ObjectIdentifier
1484 if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
1486 } else if len(rest) != 0 {
1487 return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
1490 for _, u := range keyUsage {
1491 if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1492 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1494 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1499 // RFC 5280, 4.2.1.2
1501 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
1503 } else if len(rest) != 0 {
1504 return nil, errors.New("x509: trailing data after X.509 key-id")
1506 out.SubjectKeyId = keyid
1509 // RFC 5280 4.2.1.4: Certificate Policies
1510 var policies []policyInformation
1511 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
1513 } else if len(rest) != 0 {
1514 return nil, errors.New("x509: trailing data after X.509 certificate policies")
1516 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1517 for i, policy := range policies {
1518 out.PolicyIdentifiers[i] = policy.Policy
1522 // Unknown extensions are recorded if critical.
1525 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
1526 // RFC 5280 4.2.2.1: Authority Information Access
1527 var aia []authorityInfoAccess
1528 if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
1530 } else if len(rest) != 0 {
1531 return nil, errors.New("x509: trailing data after X.509 authority information")
1534 for _, v := range aia {
1535 // GeneralName: uniformResourceIdentifier [6] IA5String
1536 if v.Location.Tag != 6 {
1539 if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
1540 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
1541 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
1542 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
1546 // Unknown extensions are recorded if critical.
1550 if e.Critical && unhandled {
1551 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
1558 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1559 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
1560 var cert certificate
1561 rest, err := asn1.Unmarshal(asn1Data, &cert)
1566 return nil, asn1.SyntaxError{Msg: "trailing data"}
1569 return parseCertificate(&cert)
1572 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1573 // data. The certificates must be concatenated with no intermediate padding.
1574 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
1575 var v []*certificate
1577 for len(asn1Data) > 0 {
1578 cert := new(certificate)
1580 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
1587 ret := make([]*Certificate, len(v))
1588 for i, ci := range v {
1589 cert, err := parseCertificate(ci)
1599 func reverseBitsInAByte(in byte) byte {
1601 b2 := b1>>2&0x33 | b1<<2&0xcc
1602 b3 := b2>>1&0x55 | b2<<1&0xaa
1606 // asn1BitLength returns the bit-length of bitString by considering the
1607 // most-significant bit in a byte to be the "first" bit. This convention
1608 // matches ASN.1, but differs from almost everything else.
1609 func asn1BitLength(bitString []byte) int {
1610 bitLen := len(bitString) * 8
1612 for i := range bitString {
1613 b := bitString[len(bitString)-i-1]
1615 for bit := uint(0); bit < 8; bit++ {
1616 if (b>>bit)&1 == 1 {
1627 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1628 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1629 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1630 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1631 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1632 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1633 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1634 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1635 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1636 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1637 oidExtensionCRLNumber = []int{2, 5, 29, 20}
1641 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1642 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1645 // oidNotInExtensions reports whether an extension with the given oid exists in
1647 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1648 for _, e := range extensions {
1649 if e.Id.Equal(oid) {
1656 // marshalSANs marshals a list of addresses into a the contents of an X.509
1657 // SubjectAlternativeName extension.
1658 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1659 var rawValues []asn1.RawValue
1660 for _, name := range dnsNames {
1661 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1663 for _, email := range emailAddresses {
1664 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1666 for _, rawIP := range ipAddresses {
1667 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1672 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1674 for _, uri := range uris {
1675 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uri.String())})
1677 return asn1.Marshal(rawValues)
1680 func isIA5String(s string) error {
1681 for _, r := range s {
1682 if r >= utf8.RuneSelf {
1683 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1690 func buildExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1691 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1694 if template.KeyUsage != 0 &&
1695 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1696 ret[n].Id = oidExtensionKeyUsage
1697 ret[n].Critical = true
1700 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1701 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1709 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1716 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1717 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1718 ret[n].Id = oidExtensionExtendedKeyUsage
1720 var oids []asn1.ObjectIdentifier
1721 for _, u := range template.ExtKeyUsage {
1722 if oid, ok := oidFromExtKeyUsage(u); ok {
1723 oids = append(oids, oid)
1725 panic("internal error")
1729 oids = append(oids, template.UnknownExtKeyUsage...)
1731 ret[n].Value, err = asn1.Marshal(oids)
1738 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1739 // Leaving MaxPathLen as zero indicates that no maximum path
1740 // length is desired, unless MaxPathLenZero is set. A value of
1741 // -1 causes encoding/asn1 to omit the value as desired.
1742 maxPathLen := template.MaxPathLen
1743 if maxPathLen == 0 && !template.MaxPathLenZero {
1746 ret[n].Id = oidExtensionBasicConstraints
1747 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
1748 ret[n].Critical = true
1755 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1756 ret[n].Id = oidExtensionSubjectKeyId
1757 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1764 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1765 ret[n].Id = oidExtensionAuthorityKeyId
1766 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1773 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1774 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1775 ret[n].Id = oidExtensionAuthorityInfoAccess
1776 var aiaValues []authorityInfoAccess
1777 for _, name := range template.OCSPServer {
1778 aiaValues = append(aiaValues, authorityInfoAccess{
1779 Method: oidAuthorityInfoAccessOcsp,
1780 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1783 for _, name := range template.IssuingCertificateURL {
1784 aiaValues = append(aiaValues, authorityInfoAccess{
1785 Method: oidAuthorityInfoAccessIssuers,
1786 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1789 ret[n].Value, err = asn1.Marshal(aiaValues)
1796 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1797 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1798 ret[n].Id = oidExtensionSubjectAltName
1799 // From RFC 5280, Section 4.2.1.6:
1800 // “If the subject field contains an empty sequence ... then
1801 // subjectAltName extension ... is marked as critical”
1802 ret[n].Critical = subjectIsEmpty
1803 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1810 if len(template.PolicyIdentifiers) > 0 &&
1811 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1812 ret[n].Id = oidExtensionCertificatePolicies
1813 policies := make([]policyInformation, len(template.PolicyIdentifiers))
1814 for i, policy := range template.PolicyIdentifiers {
1815 policies[i].Policy = policy
1817 ret[n].Value, err = asn1.Marshal(policies)
1824 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1825 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1826 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1827 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1828 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1829 ret[n].Id = oidExtensionNameConstraints
1830 ret[n].Critical = template.PermittedDNSDomainsCritical
1832 ipAndMask := func(ipNet *net.IPNet) []byte {
1833 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1834 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1835 ipAndMask = append(ipAndMask, maskedIP...)
1836 ipAndMask = append(ipAndMask, ipNet.Mask...)
1840 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1841 var b cryptobyte.Builder
1843 for _, name := range dns {
1844 if err = isIA5String(name); err != nil {
1848 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1849 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1850 b.AddBytes([]byte(name))
1855 for _, ipNet := range ips {
1856 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1857 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1858 b.AddBytes(ipAndMask(ipNet))
1863 for _, email := range emails {
1864 if err = isIA5String(email); err != nil {
1868 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1869 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1870 b.AddBytes([]byte(email))
1875 for _, uriDomain := range uriDomains {
1876 if err = isIA5String(uriDomain); err != nil {
1880 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1881 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1882 b.AddBytes([]byte(uriDomain))
1890 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1895 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1900 var b cryptobyte.Builder
1901 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1902 if len(permitted) > 0 {
1903 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1904 b.AddBytes(permitted)
1908 if len(excluded) > 0 {
1909 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1910 b.AddBytes(excluded)
1915 ret[n].Value, err = b.Bytes()
1922 if len(template.CRLDistributionPoints) > 0 &&
1923 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1924 ret[n].Id = oidExtensionCRLDistributionPoints
1926 var crlDp []distributionPoint
1927 for _, name := range template.CRLDistributionPoints {
1928 dp := distributionPoint{
1929 DistributionPoint: distributionPointName{
1930 FullName: []asn1.RawValue{
1931 {Tag: 6, Class: 2, Bytes: []byte(name)},
1935 crlDp = append(crlDp, dp)
1938 ret[n].Value, err = asn1.Marshal(crlDp)
1945 // Adding another extension here? Remember to update the maximum number
1946 // of elements in the make() at the top of the function and the list of
1947 // template fields used in CreateCertificate documentation.
1949 return append(ret[:n], template.ExtraExtensions...), nil
1952 func subjectBytes(cert *Certificate) ([]byte, error) {
1953 if len(cert.RawSubject) > 0 {
1954 return cert.RawSubject, nil
1957 return asn1.Marshal(cert.Subject.ToRDNSequence())
1960 // signingParamsForPublicKey returns the parameters to use for signing with
1961 // priv. If requestedSigAlgo is not zero then it overrides the default
1962 // signature algorithm.
1963 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1964 var pubType PublicKeyAlgorithm
1966 switch pub := pub.(type) {
1967 case *rsa.PublicKey:
1969 hashFunc = crypto.SHA256
1970 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1971 sigAlgo.Parameters = asn1.NullRawValue
1973 case *ecdsa.PublicKey:
1977 case elliptic.P224(), elliptic.P256():
1978 hashFunc = crypto.SHA256
1979 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1980 case elliptic.P384():
1981 hashFunc = crypto.SHA384
1982 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1983 case elliptic.P521():
1984 hashFunc = crypto.SHA512
1985 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1987 err = errors.New("x509: unknown elliptic curve")
1990 case ed25519.PublicKey:
1992 sigAlgo.Algorithm = oidSignatureEd25519
1995 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
2002 if requestedSigAlgo == 0 {
2007 for _, details := range signatureAlgorithmDetails {
2008 if details.algo == requestedSigAlgo {
2009 if details.pubKeyAlgo != pubType {
2010 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
2013 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
2014 if hashFunc == 0 && pubType != Ed25519 {
2015 err = errors.New("x509: cannot sign with hash function requested")
2018 if requestedSigAlgo.isRSAPSS() {
2019 sigAlgo.Parameters = rsaPSSParameters(hashFunc)
2027 err = errors.New("x509: unknown SignatureAlgorithm")
2033 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
2034 // just an empty SEQUENCE.
2035 var emptyASN1Subject = []byte{0x30, 0}
2037 // CreateCertificate creates a new X.509v3 certificate based on a template.
2038 // The following members of template are used:
2041 // - BasicConstraintsValid
2042 // - CRLDistributionPoints
2045 // - ExcludedDNSDomains
2046 // - ExcludedEmailAddresses
2047 // - ExcludedIPRanges
2048 // - ExcludedURIDomains
2050 // - ExtraExtensions
2053 // - IssuingCertificateURL
2060 // - PermittedDNSDomains
2061 // - PermittedDNSDomainsCritical
2062 // - PermittedEmailAddresses
2063 // - PermittedIPRanges
2064 // - PermittedURIDomains
2065 // - PolicyIdentifiers
2067 // - SignatureAlgorithm
2071 // - UnknownExtKeyUsage
2073 // The certificate is signed by parent. If parent is equal to template then the
2074 // certificate is self-signed. The parameter pub is the public key of the
2075 // signee and priv is the private key of the signer.
2077 // The returned slice is the certificate in DER encoding.
2079 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
2080 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
2081 // crypto.Signer with a supported public key.
2083 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
2084 // unless the resulting certificate is self-signed. Otherwise the value from
2085 // template will be used.
2087 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
2088 // will be generated from the hash of the public key.
2089 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
2090 key, ok := priv.(crypto.Signer)
2092 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2095 if template.SerialNumber == nil {
2096 return nil, errors.New("x509: no SerialNumber given")
2099 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
2100 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
2103 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2108 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
2113 asn1Issuer, err := subjectBytes(parent)
2118 asn1Subject, err := subjectBytes(template)
2123 authorityKeyId := template.AuthorityKeyId
2124 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
2125 authorityKeyId = parent.SubjectKeyId
2128 subjectKeyId := template.SubjectKeyId
2129 if len(subjectKeyId) == 0 && template.IsCA {
2130 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
2131 // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
2132 // value of the BIT STRING subjectPublicKey (excluding the tag,
2133 // length, and number of unused bits).
2134 h := sha1.Sum(publicKeyBytes)
2138 extensions, err := buildExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
2143 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
2144 c := tbsCertificate{
2146 SerialNumber: template.SerialNumber,
2147 SignatureAlgorithm: signatureAlgorithm,
2148 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
2149 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
2150 Subject: asn1.RawValue{FullBytes: asn1Subject},
2151 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
2152 Extensions: extensions,
2155 tbsCertContents, err := asn1.Marshal(c)
2159 c.Raw = tbsCertContents
2161 signed := tbsCertContents
2168 var signerOpts crypto.SignerOpts = hashFunc
2169 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
2170 signerOpts = &rsa.PSSOptions{
2171 SaltLength: rsa.PSSSaltLengthEqualsHash,
2176 var signature []byte
2177 signature, err = key.Sign(rand, signed, signerOpts)
2182 return asn1.Marshal(certificate{
2186 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2190 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
2192 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
2194 // pemType is the type of a PEM encoded CRL.
2195 var pemType = "X509 CRL"
2197 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
2198 // encoded CRLs will appear where they should be DER encoded, so this function
2199 // will transparently handle PEM encoding as long as there isn't any leading
2201 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
2202 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
2203 block, _ := pem.Decode(crlBytes)
2204 if block != nil && block.Type == pemType {
2205 crlBytes = block.Bytes
2208 return ParseDERCRL(crlBytes)
2211 // ParseDERCRL parses a DER encoded CRL from the given bytes.
2212 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
2213 certList := new(pkix.CertificateList)
2214 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
2216 } else if len(rest) != 0 {
2217 return nil, errors.New("x509: trailing data after CRL")
2219 return certList, nil
2222 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
2223 // contains the given list of revoked certificates.
2225 // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
2226 // To generate a standards compliant CRL, use CreateRevocationList instead.
2227 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
2228 key, ok := priv.(crypto.Signer)
2230 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2233 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
2238 // Force revocation times to UTC per RFC 5280.
2239 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
2240 for i, rc := range revokedCerts {
2241 rc.RevocationTime = rc.RevocationTime.UTC()
2242 revokedCertsUTC[i] = rc
2245 tbsCertList := pkix.TBSCertificateList{
2247 Signature: signatureAlgorithm,
2248 Issuer: c.Subject.ToRDNSequence(),
2249 ThisUpdate: now.UTC(),
2250 NextUpdate: expiry.UTC(),
2251 RevokedCertificates: revokedCertsUTC,
2255 if len(c.SubjectKeyId) > 0 {
2256 var aki pkix.Extension
2257 aki.Id = oidExtensionAuthorityKeyId
2258 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
2262 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
2265 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2270 signed := tbsCertListContents
2277 var signature []byte
2278 signature, err = key.Sign(rand, signed, hashFunc)
2283 return asn1.Marshal(pkix.CertificateList{
2284 TBSCertList: tbsCertList,
2285 SignatureAlgorithm: signatureAlgorithm,
2286 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2290 // CertificateRequest represents a PKCS #10, certificate signature request.
2291 type CertificateRequest struct {
2292 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
2293 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
2294 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
2295 RawSubject []byte // DER encoded Subject.
2299 SignatureAlgorithm SignatureAlgorithm
2301 PublicKeyAlgorithm PublicKeyAlgorithm
2302 PublicKey interface{}
2306 // Attributes contains the CSR attributes that can parse as
2307 // pkix.AttributeTypeAndValueSET.
2309 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
2310 // generating the requestedExtensions attribute.
2311 Attributes []pkix.AttributeTypeAndValueSET
2313 // Extensions contains all requested extensions, in raw form. When parsing
2314 // CSRs, this can be used to extract extensions that are not parsed by this
2316 Extensions []pkix.Extension
2318 // ExtraExtensions contains extensions to be copied, raw, into any CSR
2319 // marshaled by CreateCertificateRequest. Values override any extensions
2320 // that would otherwise be produced based on the other fields but are
2321 // overridden by any extensions specified in Attributes.
2323 // The ExtraExtensions field is not populated by ParseCertificateRequest,
2324 // see Extensions instead.
2325 ExtraExtensions []pkix.Extension
2327 // Subject Alternate Name values.
2329 EmailAddresses []string
2330 IPAddresses []net.IP
2334 // These structures reflect the ASN.1 structure of X.509 certificate
2335 // signature requests (see RFC 2986):
2337 type tbsCertificateRequest struct {
2340 Subject asn1.RawValue
2341 PublicKey publicKeyInfo
2342 RawAttributes []asn1.RawValue `asn1:"tag:0"`
2345 type certificateRequest struct {
2347 TBSCSR tbsCertificateRequest
2348 SignatureAlgorithm pkix.AlgorithmIdentifier
2349 SignatureValue asn1.BitString
2352 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
2353 // extensions in a CSR.
2354 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2356 // newRawAttributes converts AttributeTypeAndValueSETs from a template
2357 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
2358 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2359 var rawAttributes []asn1.RawValue
2360 b, err := asn1.Marshal(attributes)
2364 rest, err := asn1.Unmarshal(b, &rawAttributes)
2369 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2371 return rawAttributes, nil
2374 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
2375 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2376 var attributes []pkix.AttributeTypeAndValueSET
2377 for _, rawAttr := range rawAttributes {
2378 var attr pkix.AttributeTypeAndValueSET
2379 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2380 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2381 // (i.e.: challengePassword or unstructuredName).
2382 if err == nil && len(rest) == 0 {
2383 attributes = append(attributes, attr)
2389 // parseCSRExtensions parses the attributes from a CSR and extracts any
2390 // requested extensions.
2391 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2392 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
2393 type pkcs10Attribute struct {
2394 Id asn1.ObjectIdentifier
2395 Values []asn1.RawValue `asn1:"set"`
2398 var ret []pkix.Extension
2399 for _, rawAttr := range rawAttributes {
2400 var attr pkcs10Attribute
2401 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2402 // Ignore attributes that don't parse.
2406 if !attr.Id.Equal(oidExtensionRequest) {
2410 var extensions []pkix.Extension
2411 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2414 ret = append(ret, extensions...)
2420 // CreateCertificateRequest creates a new certificate request based on a
2421 // template. The following members of template are used:
2423 // - SignatureAlgorithm
2429 // - ExtraExtensions
2430 // - Attributes (deprecated)
2432 // priv is the private key to sign the CSR with, and the corresponding public
2433 // key will be included in the CSR. It must implement crypto.Signer and its
2434 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
2435 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
2436 // ed25519.PrivateKey satisfies this.)
2438 // The returned slice is the certificate request in DER encoding.
2439 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
2440 key, ok := priv.(crypto.Signer)
2442 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2445 var hashFunc crypto.Hash
2446 var sigAlgo pkix.AlgorithmIdentifier
2447 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2452 var publicKeyBytes []byte
2453 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2454 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2459 var extensions []pkix.Extension
2461 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
2462 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
2463 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
2468 extensions = append(extensions, pkix.Extension{
2469 Id: oidExtensionSubjectAltName,
2474 extensions = append(extensions, template.ExtraExtensions...)
2476 // Make a copy of template.Attributes because we may alter it below.
2477 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2478 for _, attr := range template.Attributes {
2479 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2480 copy(values, attr.Value)
2481 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2487 extensionsAppended := false
2488 if len(extensions) > 0 {
2489 // Append the extensions to an existing attribute if possible.
2490 for _, atvSet := range attributes {
2491 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2495 // specifiedExtensions contains all the extensions that we
2496 // found specified via template.Attributes.
2497 specifiedExtensions := make(map[string]bool)
2499 for _, atvs := range atvSet.Value {
2500 for _, atv := range atvs {
2501 specifiedExtensions[atv.Type.String()] = true
2505 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2506 newValue = append(newValue, atvSet.Value[0]...)
2508 for _, e := range extensions {
2509 if specifiedExtensions[e.Id.String()] {
2510 // Attributes already contained a value for
2511 // this extension and it takes priority.
2515 newValue = append(newValue, pkix.AttributeTypeAndValue{
2516 // There is no place for the critical
2517 // flag in an AttributeTypeAndValue.
2523 atvSet.Value[0] = newValue
2524 extensionsAppended = true
2529 rawAttributes, err := newRawAttributes(attributes)
2534 // If not included in attributes, add a new attribute for the
2536 if len(extensions) > 0 && !extensionsAppended {
2538 Type asn1.ObjectIdentifier
2539 Value [][]pkix.Extension `asn1:"set"`
2541 Type: oidExtensionRequest,
2542 Value: [][]pkix.Extension{extensions},
2545 b, err := asn1.Marshal(attr)
2547 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2550 var rawValue asn1.RawValue
2551 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2555 rawAttributes = append(rawAttributes, rawValue)
2558 asn1Subject := template.RawSubject
2559 if len(asn1Subject) == 0 {
2560 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2566 tbsCSR := tbsCertificateRequest{
2567 Version: 0, // PKCS #10, RFC 2986
2568 Subject: asn1.RawValue{FullBytes: asn1Subject},
2569 PublicKey: publicKeyInfo{
2570 Algorithm: publicKeyAlgorithm,
2571 PublicKey: asn1.BitString{
2572 Bytes: publicKeyBytes,
2573 BitLength: len(publicKeyBytes) * 8,
2576 RawAttributes: rawAttributes,
2579 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2583 tbsCSR.Raw = tbsCSRContents
2585 signed := tbsCSRContents
2592 var signature []byte
2593 signature, err = key.Sign(rand, signed, hashFunc)
2598 return asn1.Marshal(certificateRequest{
2600 SignatureAlgorithm: sigAlgo,
2601 SignatureValue: asn1.BitString{
2603 BitLength: len(signature) * 8,
2608 // ParseCertificateRequest parses a single certificate request from the
2609 // given ASN.1 DER data.
2610 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2611 var csr certificateRequest
2613 rest, err := asn1.Unmarshal(asn1Data, &csr)
2616 } else if len(rest) != 0 {
2617 return nil, asn1.SyntaxError{Msg: "trailing data"}
2620 return parseCertificateRequest(&csr)
2623 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2624 out := &CertificateRequest{
2626 RawTBSCertificateRequest: in.TBSCSR.Raw,
2627 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2628 RawSubject: in.TBSCSR.Subject.FullBytes,
2630 Signature: in.SignatureValue.RightAlign(),
2631 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2633 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2635 Version: in.TBSCSR.Version,
2636 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2640 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2645 var subject pkix.RDNSequence
2646 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2648 } else if len(rest) != 0 {
2649 return nil, errors.New("x509: trailing data after X.509 Subject")
2652 out.Subject.FillFromRDNSequence(&subject)
2654 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2658 for _, extension := range out.Extensions {
2659 if extension.Id.Equal(oidExtensionSubjectAltName) {
2660 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2670 // CheckSignature reports whether the signature on c is valid.
2671 func (c *CertificateRequest) CheckSignature() error {
2672 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
2675 // RevocationList contains the fields used to create an X.509 v2 Certificate
2676 // Revocation list with CreateRevocationList.
2677 type RevocationList struct {
2678 // SignatureAlgorithm is used to determine the signature algorithm to be
2679 // used when signing the CRL. If 0 the default algorithm for the signing
2680 // key will be used.
2681 SignatureAlgorithm SignatureAlgorithm
2683 // RevokedCertificates is used to populate the revokedCertificates
2684 // sequence in the CRL, it may be empty. RevokedCertificates may be nil,
2685 // in which case an empty CRL will be created.
2686 RevokedCertificates []pkix.RevokedCertificate
2688 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2689 // which should be a monotonically increasing sequence number for a given
2690 // CRL scope and CRL issuer.
2692 // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2693 // indicates the issuance date of the CRL.
2694 ThisUpdate time.Time
2695 // NextUpdate is used to populate the nextUpdate field in the CRL, which
2696 // indicates the date by which the next CRL will be issued. NextUpdate
2697 // must be greater than ThisUpdate.
2698 NextUpdate time.Time
2699 // ExtraExtensions contains any additional extensions to add directly to
2701 ExtraExtensions []pkix.Extension
2704 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
2705 // according to RFC 5280, based on template.
2707 // The CRL is signed by priv which should be the private key associated with
2708 // the public key in the issuer certificate.
2710 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
2711 // order to use it as a CRL issuer.
2713 // The issuer distinguished name CRL field and authority key identifier
2714 // extension are populated using the issuer certificate. issuer must have
2715 // SubjectKeyId set.
2716 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2717 if template == nil {
2718 return nil, errors.New("x509: template can not be nil")
2721 return nil, errors.New("x509: issuer can not be nil")
2723 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2724 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2726 if len(issuer.SubjectKeyId) == 0 {
2727 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2729 if template.NextUpdate.Before(template.ThisUpdate) {
2730 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2732 if template.Number == nil {
2733 return nil, errors.New("x509: template contains nil Number field")
2736 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2741 // Force revocation times to UTC per RFC 5280.
2742 revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2743 for i, rc := range template.RevokedCertificates {
2744 rc.RevocationTime = rc.RevocationTime.UTC()
2745 revokedCertsUTC[i] = rc
2748 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2752 crlNum, err := asn1.Marshal(template.Number)
2757 tbsCertList := pkix.TBSCertificateList{
2759 Signature: signatureAlgorithm,
2760 Issuer: issuer.Subject.ToRDNSequence(),
2761 ThisUpdate: template.ThisUpdate.UTC(),
2762 NextUpdate: template.NextUpdate.UTC(),
2763 Extensions: []pkix.Extension{
2765 Id: oidExtensionAuthorityKeyId,
2769 Id: oidExtensionCRLNumber,
2774 if len(revokedCertsUTC) > 0 {
2775 tbsCertList.RevokedCertificates = revokedCertsUTC
2778 if len(template.ExtraExtensions) > 0 {
2779 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2782 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2787 input := tbsCertListContents
2790 h.Write(tbsCertListContents)
2793 var signerOpts crypto.SignerOpts = hashFunc
2794 if template.SignatureAlgorithm.isRSAPSS() {
2795 signerOpts = &rsa.PSSOptions{
2796 SaltLength: rsa.PSSSaltLengthEqualsHash,
2801 signature, err := priv.Sign(rand, input, signerOpts)
2806 return asn1.Marshal(pkix.CertificateList{
2807 TBSCertList: tbsCertList,
2808 SignatureAlgorithm: signatureAlgorithm,
2809 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},