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.
7 // On UNIX systems the environment variables SSL_CERT_FILE and SSL_CERT_DIR
8 // can be used to override the system default locations for the SSL certificate
9 // file and SSL certificate files directory, respectively.
38 "golang.org/x/crypto/cryptobyte"
39 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
42 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
44 type pkixPublicKey struct {
45 Algo pkix.AlgorithmIdentifier
46 BitString asn1.BitString
49 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
50 // The encoded public key is a SubjectPublicKeyInfo structure
51 // (see RFC 5280, Section 4.1).
53 // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
54 // ed25519.PublicKey. More types might be supported in the future.
56 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
57 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
59 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
60 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
61 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
64 } else if len(rest) != 0 {
65 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
67 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
68 if algo == UnknownPublicKeyAlgorithm {
69 return nil, errors.New("x509: unknown public key algorithm")
71 return parsePublicKey(algo, &pki)
74 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
75 switch pub := pub.(type) {
77 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
82 return nil, pkix.AlgorithmIdentifier{}, err
84 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
85 // This is a NULL parameters value which is required by
86 // RFC 3279, Section 2.3.1.
87 publicKeyAlgorithm.Parameters = asn1.NullRawValue
88 case *ecdsa.PublicKey:
89 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
90 oid, ok := oidFromNamedCurve(pub.Curve)
92 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
94 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
96 paramBytes, err = asn1.Marshal(oid)
100 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
101 case ed25519.PublicKey:
103 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
105 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
108 return publicKeyBytes, publicKeyAlgorithm, nil
111 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
112 // The encoded public key is a SubjectPublicKeyInfo structure
113 // (see RFC 5280, Section 4.1).
115 // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
116 // and ed25519.PublicKey. Unsupported key types result in an error.
118 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
119 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
120 var publicKeyBytes []byte
121 var publicKeyAlgorithm pkix.AlgorithmIdentifier
124 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
128 pkix := pkixPublicKey{
129 Algo: publicKeyAlgorithm,
130 BitString: asn1.BitString{
131 Bytes: publicKeyBytes,
132 BitLength: 8 * len(publicKeyBytes),
136 ret, _ := asn1.Marshal(pkix)
140 // These structures reflect the ASN.1 structure of X.509 certificates.:
142 type certificate struct {
144 TBSCertificate tbsCertificate
145 SignatureAlgorithm pkix.AlgorithmIdentifier
146 SignatureValue asn1.BitString
149 type tbsCertificate struct {
151 Version int `asn1:"optional,explicit,default:0,tag:0"`
152 SerialNumber *big.Int
153 SignatureAlgorithm pkix.AlgorithmIdentifier
156 Subject asn1.RawValue
157 PublicKey publicKeyInfo
158 UniqueId asn1.BitString `asn1:"optional,tag:1"`
159 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
160 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
163 type dsaAlgorithmParameters struct {
167 type dsaSignature struct {
171 type validity struct {
172 NotBefore, NotAfter time.Time
175 type publicKeyInfo struct {
177 Algorithm pkix.AlgorithmIdentifier
178 PublicKey asn1.BitString
182 type authKeyId struct {
183 Id []byte `asn1:"optional,tag:0"`
186 type SignatureAlgorithm int
189 UnknownSignatureAlgorithm SignatureAlgorithm = iota
208 func (algo SignatureAlgorithm) isRSAPSS() bool {
210 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
217 func (algo SignatureAlgorithm) String() string {
218 for _, details := range signatureAlgorithmDetails {
219 if details.algo == algo {
223 return strconv.Itoa(int(algo))
226 type PublicKeyAlgorithm int
229 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
236 var publicKeyAlgoName = [...]string{
243 func (algo PublicKeyAlgorithm) String() string {
244 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
245 return publicKeyAlgoName[algo]
247 return strconv.Itoa(int(algo))
250 // OIDs for signature algorithms
252 // pkcs-1 OBJECT IDENTIFIER ::= {
253 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
256 // RFC 3279 2.2.1 RSA Signature Algorithms
258 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
260 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
262 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
264 // dsaWithSha1 OBJECT IDENTIFIER ::= {
265 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
267 // RFC 3279 2.2.3 ECDSA Signature Algorithm
269 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
270 // iso(1) member-body(2) us(840) ansi-x962(10045)
271 // signatures(4) ecdsa-with-SHA1(1)}
274 // RFC 4055 5 PKCS #1 Version 1.5
276 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
278 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
280 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
283 // RFC 5758 3.1 DSA Signature Algorithms
285 // dsaWithSha256 OBJECT IDENTIFIER ::= {
286 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
287 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
289 // RFC 5758 3.2 ECDSA Signature Algorithm
291 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
292 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
294 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
295 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
297 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
298 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
301 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
303 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
306 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
307 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
308 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
309 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
310 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
311 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
312 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
313 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
314 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
315 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
316 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
317 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
318 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
319 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
321 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
322 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
323 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
325 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
327 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
328 // but it's specified by ISO. Microsoft's makecert.exe has been known
329 // to produce certificates with this OID.
330 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
333 var signatureAlgorithmDetails = []struct {
334 algo SignatureAlgorithm
336 oid asn1.ObjectIdentifier
337 pubKeyAlgo PublicKeyAlgorithm
340 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
341 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
342 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
343 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
344 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
345 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
346 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
347 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
348 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
349 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
350 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
351 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
352 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
353 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
354 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
355 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
356 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
359 // pssParameters reflects the parameters in an AlgorithmIdentifier that
360 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
361 type pssParameters struct {
362 // The following three fields are not marked as
363 // optional because the default values specify SHA-1,
364 // which is no longer suitable for use in signatures.
365 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
366 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
367 SaltLength int `asn1:"explicit,tag:2"`
368 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
371 // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
372 // in an AlgorithmIdentifier that specifies RSA PSS.
373 func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue {
374 var hashOID asn1.ObjectIdentifier
385 params := pssParameters{
386 Hash: pkix.AlgorithmIdentifier{
388 Parameters: asn1.NullRawValue,
390 MGF: pkix.AlgorithmIdentifier{
393 SaltLength: hashFunc.Size(),
397 mgf1Params := pkix.AlgorithmIdentifier{
399 Parameters: asn1.NullRawValue,
403 params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
408 serialized, err := asn1.Marshal(params)
413 return asn1.RawValue{FullBytes: serialized}
416 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
417 if ai.Algorithm.Equal(oidSignatureEd25519) {
418 // RFC 8410, Section 3
419 // > For all of the OIDs, the parameters MUST be absent.
420 if len(ai.Parameters.FullBytes) != 0 {
421 return UnknownSignatureAlgorithm
425 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
426 for _, details := range signatureAlgorithmDetails {
427 if ai.Algorithm.Equal(details.oid) {
431 return UnknownSignatureAlgorithm
434 // RSA PSS is special because it encodes important parameters
435 // in the Parameters.
437 var params pssParameters
438 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
439 return UnknownSignatureAlgorithm
442 var mgf1HashFunc pkix.AlgorithmIdentifier
443 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
444 return UnknownSignatureAlgorithm
447 // PSS is greatly overburdened with options. This code forces them into
448 // three buckets by requiring that the MGF1 hash function always match the
449 // message hash function (as recommended in RFC 3447, Section 8.1), that the
450 // salt length matches the hash length, and that the trailer field has the
452 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
453 !params.MGF.Algorithm.Equal(oidMGF1) ||
454 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
455 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
456 params.TrailerField != 1 {
457 return UnknownSignatureAlgorithm
461 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
462 return SHA256WithRSAPSS
463 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
464 return SHA384WithRSAPSS
465 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
466 return SHA512WithRSAPSS
469 return UnknownSignatureAlgorithm
472 // RFC 3279, 2.3 Public Key Algorithms
474 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
475 // rsadsi(113549) pkcs(1) 1 }
477 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
479 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
480 // x9-57(10040) x9cm(4) 1 }
482 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
484 // id-ecPublicKey OBJECT IDENTIFIER ::= {
485 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
487 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
488 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
489 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
490 oidPublicKeyEd25519 = oidSignatureEd25519
493 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
495 case oid.Equal(oidPublicKeyRSA):
497 case oid.Equal(oidPublicKeyDSA):
499 case oid.Equal(oidPublicKeyECDSA):
501 case oid.Equal(oidPublicKeyEd25519):
504 return UnknownPublicKeyAlgorithm
507 // RFC 5480, 2.1.1.1. Named Curve
509 // secp224r1 OBJECT IDENTIFIER ::= {
510 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
512 // secp256r1 OBJECT IDENTIFIER ::= {
513 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
516 // secp384r1 OBJECT IDENTIFIER ::= {
517 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
519 // secp521r1 OBJECT IDENTIFIER ::= {
520 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
522 // NB: secp256r1 is equivalent to prime256v1
524 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
525 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
526 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
527 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
530 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
532 case oid.Equal(oidNamedCurveP224):
533 return elliptic.P224()
534 case oid.Equal(oidNamedCurveP256):
535 return elliptic.P256()
536 case oid.Equal(oidNamedCurveP384):
537 return elliptic.P384()
538 case oid.Equal(oidNamedCurveP521):
539 return elliptic.P521()
544 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
546 case elliptic.P224():
547 return oidNamedCurveP224, true
548 case elliptic.P256():
549 return oidNamedCurveP256, true
550 case elliptic.P384():
551 return oidNamedCurveP384, true
552 case elliptic.P521():
553 return oidNamedCurveP521, true
559 // KeyUsage represents the set of actions that are valid for a given key. It's
560 // a bitmap of the KeyUsage* constants.
564 KeyUsageDigitalSignature KeyUsage = 1 << iota
565 KeyUsageContentCommitment
566 KeyUsageKeyEncipherment
567 KeyUsageDataEncipherment
575 // RFC 5280, 4.2.1.12 Extended Key Usage
577 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
579 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
581 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
582 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
583 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
584 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
585 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
586 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
588 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
589 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
590 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
591 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
592 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
593 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
594 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
595 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
596 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
597 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
598 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
599 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
600 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
601 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
604 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
605 // Each of the ExtKeyUsage* constants define a unique action.
609 ExtKeyUsageAny ExtKeyUsage = iota
610 ExtKeyUsageServerAuth
611 ExtKeyUsageClientAuth
612 ExtKeyUsageCodeSigning
613 ExtKeyUsageEmailProtection
614 ExtKeyUsageIPSECEndSystem
615 ExtKeyUsageIPSECTunnel
617 ExtKeyUsageTimeStamping
618 ExtKeyUsageOCSPSigning
619 ExtKeyUsageMicrosoftServerGatedCrypto
620 ExtKeyUsageNetscapeServerGatedCrypto
621 ExtKeyUsageMicrosoftCommercialCodeSigning
622 ExtKeyUsageMicrosoftKernelCodeSigning
625 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
626 var extKeyUsageOIDs = []struct {
627 extKeyUsage ExtKeyUsage
628 oid asn1.ObjectIdentifier
630 {ExtKeyUsageAny, oidExtKeyUsageAny},
631 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
632 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
633 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
634 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
635 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
636 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
637 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
638 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
639 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
640 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
641 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
642 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
643 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
646 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
647 for _, pair := range extKeyUsageOIDs {
648 if oid.Equal(pair.oid) {
649 return pair.extKeyUsage, true
655 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
656 for _, pair := range extKeyUsageOIDs {
657 if eku == pair.extKeyUsage {
658 return pair.oid, true
664 // A Certificate represents an X.509 certificate.
665 type Certificate struct {
666 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
667 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
668 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
669 RawSubject []byte // DER encoded Subject
670 RawIssuer []byte // DER encoded Issuer
673 SignatureAlgorithm SignatureAlgorithm
675 PublicKeyAlgorithm PublicKeyAlgorithm
676 PublicKey interface{}
679 SerialNumber *big.Int
682 NotBefore, NotAfter time.Time // Validity bounds.
685 // Extensions contains raw X.509 extensions. When parsing certificates,
686 // this can be used to extract non-critical extensions that are not
687 // parsed by this package. When marshaling certificates, the Extensions
688 // field is ignored, see ExtraExtensions.
689 Extensions []pkix.Extension
691 // ExtraExtensions contains extensions to be copied, raw, into any
692 // marshaled certificates. Values override any extensions that would
693 // otherwise be produced based on the other fields. The ExtraExtensions
694 // field is not populated when parsing certificates, see Extensions.
695 ExtraExtensions []pkix.Extension
697 // UnhandledCriticalExtensions contains a list of extension IDs that
698 // were not (fully) processed when parsing. Verify will fail if this
699 // slice is non-empty, unless verification is delegated to an OS
700 // library which understands all the critical extensions.
702 // Users can access these extensions using Extensions and can remove
703 // elements from this slice if they believe that they have been
705 UnhandledCriticalExtensions []asn1.ObjectIdentifier
707 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
708 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
710 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
711 // and MaxPathLenZero are valid.
712 BasicConstraintsValid bool
715 // MaxPathLen and MaxPathLenZero indicate the presence and
716 // value of the BasicConstraints' "pathLenConstraint".
718 // When parsing a certificate, a positive non-zero MaxPathLen
719 // means that the field was specified, -1 means it was unset,
720 // and MaxPathLenZero being true mean that the field was
721 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
722 // should be treated equivalent to -1 (unset).
724 // When generating a certificate, an unset pathLenConstraint
725 // can be requested with either MaxPathLen == -1 or using the
726 // zero value for both MaxPathLen and MaxPathLenZero.
728 // MaxPathLenZero indicates that BasicConstraintsValid==true
729 // and MaxPathLen==0 should be interpreted as an actual
730 // maximum path length of zero. Otherwise, that combination is
731 // interpreted as MaxPathLen not being set.
735 AuthorityKeyId []byte
737 // RFC 5280, 4.2.2.1 (Authority Information Access)
739 IssuingCertificateURL []string
741 // Subject Alternate Name values. (Note that these values may not be valid
742 // if invalid values were contained within a parsed certificate. For
743 // example, an element of DNSNames may not be a valid DNS domain name.)
745 EmailAddresses []string
750 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
751 PermittedDNSDomains []string
752 ExcludedDNSDomains []string
753 PermittedIPRanges []*net.IPNet
754 ExcludedIPRanges []*net.IPNet
755 PermittedEmailAddresses []string
756 ExcludedEmailAddresses []string
757 PermittedURIDomains []string
758 ExcludedURIDomains []string
760 // CRL Distribution Points
761 CRLDistributionPoints []string
763 PolicyIdentifiers []asn1.ObjectIdentifier
766 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
767 // involves algorithms that are not currently implemented.
768 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
770 // An InsecureAlgorithmError
771 type InsecureAlgorithmError SignatureAlgorithm
773 func (e InsecureAlgorithmError) Error() string {
774 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
777 // ConstraintViolationError results when a requested usage is not permitted by
778 // a certificate. For example: checking a signature when the public key isn't a
779 // certificate signing key.
780 type ConstraintViolationError struct{}
782 func (ConstraintViolationError) Error() string {
783 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
786 func (c *Certificate) Equal(other *Certificate) bool {
787 if c == nil || other == nil {
790 return bytes.Equal(c.Raw, other.Raw)
793 func (c *Certificate) hasSANExtension() bool {
794 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
797 // CheckSignatureFrom verifies that the signature on c is a valid signature
799 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
800 // RFC 5280, 4.2.1.9:
801 // "If the basic constraints extension is not present in a version 3
802 // certificate, or the extension is present but the cA boolean is not
803 // asserted, then the certified public key MUST NOT be used to verify
804 // certificate signatures."
805 if parent.Version == 3 && !parent.BasicConstraintsValid ||
806 parent.BasicConstraintsValid && !parent.IsCA {
807 return ConstraintViolationError{}
810 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
811 return ConstraintViolationError{}
814 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
815 return ErrUnsupportedAlgorithm
818 // TODO(agl): don't ignore the path length constraint.
820 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
823 // CheckSignature verifies that signature is a valid signature over signed from
825 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
826 return checkSignature(algo, signed, signature, c.PublicKey)
829 func (c *Certificate) hasNameConstraints() bool {
830 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
833 func (c *Certificate) getSANExtension() []byte {
834 for _, e := range c.Extensions {
835 if e.Id.Equal(oidExtensionSubjectAltName) {
842 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
843 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
846 // CheckSignature verifies that signature is a valid signature over signed from
847 // a crypto.PublicKey.
848 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
849 var hashType crypto.Hash
850 var pubKeyAlgo PublicKeyAlgorithm
852 for _, details := range signatureAlgorithmDetails {
853 if details.algo == algo {
854 hashType = details.hash
855 pubKeyAlgo = details.pubKeyAlgo
861 if pubKeyAlgo != Ed25519 {
862 return ErrUnsupportedAlgorithm
865 return InsecureAlgorithmError(algo)
867 if !hashType.Available() {
868 return ErrUnsupportedAlgorithm
875 switch pub := publicKey.(type) {
877 if pubKeyAlgo != RSA {
878 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
881 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
883 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
886 if pubKeyAlgo != DSA {
887 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
889 dsaSig := new(dsaSignature)
890 if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
892 } else if len(rest) != 0 {
893 return errors.New("x509: trailing data after DSA signature")
895 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
896 return errors.New("x509: DSA signature contained zero or negative values")
898 // According to FIPS 186-3, section 4.6, the hash must be truncated if it is longer
899 // than the key length, but crypto/dsa doesn't do it automatically.
900 if maxHashLen := pub.Q.BitLen() / 8; maxHashLen < len(signed) {
901 signed = signed[:maxHashLen]
903 if !dsa.Verify(pub, signed, dsaSig.R, dsaSig.S) {
904 return errors.New("x509: DSA verification failure")
907 case *ecdsa.PublicKey:
908 if pubKeyAlgo != ECDSA {
909 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
911 if !ecdsa.VerifyASN1(pub, signed, signature) {
912 return errors.New("x509: ECDSA verification failure")
915 case ed25519.PublicKey:
916 if pubKeyAlgo != Ed25519 {
917 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
919 if !ed25519.Verify(pub, signed, signature) {
920 return errors.New("x509: Ed25519 verification failure")
924 return ErrUnsupportedAlgorithm
927 // CheckCRLSignature checks that the signature in crl is from c.
928 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
929 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
930 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
933 type UnhandledCriticalExtension struct{}
935 func (h UnhandledCriticalExtension) Error() string {
936 return "x509: unhandled critical extension"
939 type basicConstraints struct {
940 IsCA bool `asn1:"optional"`
941 MaxPathLen int `asn1:"optional,default:-1"`
945 type policyInformation struct {
946 Policy asn1.ObjectIdentifier
947 // policyQualifiers omitted
958 type authorityInfoAccess struct {
959 Method asn1.ObjectIdentifier
960 Location asn1.RawValue
963 // RFC 5280, 4.2.1.14
964 type distributionPoint struct {
965 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
966 Reason asn1.BitString `asn1:"optional,tag:1"`
967 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
970 type distributionPointName struct {
971 FullName []asn1.RawValue `asn1:"optional,tag:0"`
972 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
975 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
976 asn1Data := keyData.PublicKey.RightAlign()
979 // RSA public keys must have a NULL in the parameters.
980 // See RFC 3279, Section 2.3.1.
981 if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
982 return nil, errors.New("x509: RSA key missing NULL parameters")
985 p := new(pkcs1PublicKey)
986 rest, err := asn1.Unmarshal(asn1Data, p)
991 return nil, errors.New("x509: trailing data after RSA public key")
995 return nil, errors.New("x509: RSA modulus is not a positive number")
998 return nil, errors.New("x509: RSA public exponent is not a positive number")
1001 pub := &rsa.PublicKey{
1008 rest, err := asn1.Unmarshal(asn1Data, &p)
1013 return nil, errors.New("x509: trailing data after DSA public key")
1015 paramsData := keyData.Algorithm.Parameters.FullBytes
1016 params := new(dsaAlgorithmParameters)
1017 rest, err = asn1.Unmarshal(paramsData, params)
1022 return nil, errors.New("x509: trailing data after DSA parameters")
1024 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
1025 return nil, errors.New("x509: zero or negative DSA parameter")
1027 pub := &dsa.PublicKey{
1028 Parameters: dsa.Parameters{
1037 paramsData := keyData.Algorithm.Parameters.FullBytes
1038 namedCurveOID := new(asn1.ObjectIdentifier)
1039 rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
1041 return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
1044 return nil, errors.New("x509: trailing data after ECDSA parameters")
1046 namedCurve := namedCurveFromOID(*namedCurveOID)
1047 if namedCurve == nil {
1048 return nil, errors.New("x509: unsupported elliptic curve")
1050 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
1052 return nil, errors.New("x509: failed to unmarshal elliptic curve point")
1054 pub := &ecdsa.PublicKey{
1061 // RFC 8410, Section 3
1062 // > For all of the OIDs, the parameters MUST be absent.
1063 if len(keyData.Algorithm.Parameters.FullBytes) != 0 {
1064 return nil, errors.New("x509: Ed25519 key encoded with illegal parameters")
1066 if len(asn1Data) != ed25519.PublicKeySize {
1067 return nil, errors.New("x509: wrong Ed25519 public key size")
1069 pub := make([]byte, ed25519.PublicKeySize)
1071 return ed25519.PublicKey(pub), nil
1077 func forEachSAN(extension []byte, callback func(tag int, data []byte) error) error {
1078 // RFC 5280, 4.2.1.6
1080 // SubjectAltName ::= GeneralNames
1082 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1084 // GeneralName ::= CHOICE {
1085 // otherName [0] OtherName,
1086 // rfc822Name [1] IA5String,
1087 // dNSName [2] IA5String,
1088 // x400Address [3] ORAddress,
1089 // directoryName [4] Name,
1090 // ediPartyName [5] EDIPartyName,
1091 // uniformResourceIdentifier [6] IA5String,
1092 // iPAddress [7] OCTET STRING,
1093 // registeredID [8] OBJECT IDENTIFIER }
1094 var seq asn1.RawValue
1095 rest, err := asn1.Unmarshal(extension, &seq)
1098 } else if len(rest) != 0 {
1099 return errors.New("x509: trailing data after X.509 extension")
1101 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
1102 return asn1.StructuralError{Msg: "bad SAN sequence"}
1108 rest, err = asn1.Unmarshal(rest, &v)
1113 if err := callback(v.Tag, v.Bytes); err != nil {
1121 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
1122 err = forEachSAN(value, func(tag int, data []byte) error {
1125 emailAddresses = append(emailAddresses, string(data))
1127 dnsNames = append(dnsNames, string(data))
1129 uri, err := url.Parse(string(data))
1131 return fmt.Errorf("x509: cannot parse URI %q: %s", string(data), err)
1133 if len(uri.Host) > 0 {
1134 if _, ok := domainToReverseLabels(uri.Host); !ok {
1135 return fmt.Errorf("x509: cannot parse URI %q: invalid domain", string(data))
1138 uris = append(uris, uri)
1141 case net.IPv4len, net.IPv6len:
1142 ipAddresses = append(ipAddresses, data)
1144 return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
1154 // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
1155 func isValidIPMask(mask []byte) bool {
1158 for _, b := range mask {
1168 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
1179 func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) {
1180 // RFC 5280, 4.2.1.10
1182 // NameConstraints ::= SEQUENCE {
1183 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
1184 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
1186 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
1188 // GeneralSubtree ::= SEQUENCE {
1189 // base GeneralName,
1190 // minimum [0] BaseDistance DEFAULT 0,
1191 // maximum [1] BaseDistance OPTIONAL }
1193 // BaseDistance ::= INTEGER (0..MAX)
1195 outer := cryptobyte.String(e.Value)
1196 var toplevel, permitted, excluded cryptobyte.String
1197 var havePermitted, haveExcluded bool
1198 if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
1200 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
1201 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
1203 return false, errors.New("x509: invalid NameConstraints extension")
1206 if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
1207 // From RFC 5280, Section 4.2.1.10:
1208 // “either the permittedSubtrees field
1209 // or the excludedSubtrees MUST be
1211 return false, errors.New("x509: empty name constraints extension")
1214 getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
1215 for !subtrees.Empty() {
1216 var seq, value cryptobyte.String
1217 var tag cryptobyte_asn1.Tag
1218 if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
1219 !seq.ReadAnyASN1(&value, &tag) {
1220 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
1224 dnsTag = cryptobyte_asn1.Tag(2).ContextSpecific()
1225 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
1226 ipTag = cryptobyte_asn1.Tag(7).ContextSpecific()
1227 uriTag = cryptobyte_asn1.Tag(6).ContextSpecific()
1232 domain := string(value)
1233 if err := isIA5String(domain); err != nil {
1234 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1237 trimmedDomain := domain
1238 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1239 // constraints can have a leading
1240 // period to exclude the domain
1241 // itself, but that's not valid in a
1242 // normal domain name.
1243 trimmedDomain = trimmedDomain[1:]
1245 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1246 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
1248 dnsNames = append(dnsNames, domain)
1264 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
1267 if !isValidIPMask(mask) {
1268 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
1271 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
1274 constraint := string(value)
1275 if err := isIA5String(constraint); err != nil {
1276 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1279 // If the constraint contains an @ then
1280 // it specifies an exact mailbox name.
1281 if strings.Contains(constraint, "@") {
1282 if _, ok := parseRFC2821Mailbox(constraint); !ok {
1283 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1286 // Otherwise it's a domain name.
1287 domain := constraint
1288 if len(domain) > 0 && domain[0] == '.' {
1291 if _, ok := domainToReverseLabels(domain); !ok {
1292 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1295 emails = append(emails, constraint)
1298 domain := string(value)
1299 if err := isIA5String(domain); err != nil {
1300 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1303 if net.ParseIP(domain) != nil {
1304 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
1307 trimmedDomain := domain
1308 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1309 // constraints can have a leading
1310 // period to exclude the domain itself,
1311 // but that's not valid in a normal
1313 trimmedDomain = trimmedDomain[1:]
1315 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1316 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain)
1318 uriDomains = append(uriDomains, domain)
1325 return dnsNames, ips, emails, uriDomains, nil
1328 if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
1331 if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
1334 out.PermittedDNSDomainsCritical = e.Critical
1336 return unhandled, nil
1339 func parseCertificate(in *certificate) (*Certificate, error) {
1340 out := new(Certificate)
1342 out.RawTBSCertificate = in.TBSCertificate.Raw
1343 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
1344 out.RawSubject = in.TBSCertificate.Subject.FullBytes
1345 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
1347 out.Signature = in.SignatureValue.RightAlign()
1348 out.SignatureAlgorithm =
1349 getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
1351 out.PublicKeyAlgorithm =
1352 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
1354 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
1359 out.Version = in.TBSCertificate.Version + 1
1360 out.SerialNumber = in.TBSCertificate.SerialNumber
1362 var issuer, subject pkix.RDNSequence
1363 if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
1365 } else if len(rest) != 0 {
1366 return nil, errors.New("x509: trailing data after X.509 subject")
1368 if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
1370 } else if len(rest) != 0 {
1371 return nil, errors.New("x509: trailing data after X.509 issuer")
1374 out.Issuer.FillFromRDNSequence(&issuer)
1375 out.Subject.FillFromRDNSequence(&subject)
1377 out.NotBefore = in.TBSCertificate.Validity.NotBefore
1378 out.NotAfter = in.TBSCertificate.Validity.NotAfter
1380 for _, e := range in.TBSCertificate.Extensions {
1381 out.Extensions = append(out.Extensions, e)
1384 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
1387 // RFC 5280, 4.2.1.3
1388 var usageBits asn1.BitString
1389 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
1391 } else if len(rest) != 0 {
1392 return nil, errors.New("x509: trailing data after X.509 KeyUsage")
1396 for i := 0; i < 9; i++ {
1397 if usageBits.At(i) != 0 {
1398 usage |= 1 << uint(i)
1401 out.KeyUsage = KeyUsage(usage)
1404 // RFC 5280, 4.2.1.9
1405 var constraints basicConstraints
1406 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1408 } else if len(rest) != 0 {
1409 return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
1412 out.BasicConstraintsValid = true
1413 out.IsCA = constraints.IsCA
1414 out.MaxPathLen = constraints.MaxPathLen
1415 out.MaxPathLenZero = out.MaxPathLen == 0
1416 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
1418 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value)
1423 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
1424 // If we didn't parse anything then we do the critical check, below.
1429 unhandled, err = parseNameConstraintsExtension(out, e)
1435 // RFC 5280, 4.2.1.13
1437 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1439 // DistributionPoint ::= SEQUENCE {
1440 // distributionPoint [0] DistributionPointName OPTIONAL,
1441 // reasons [1] ReasonFlags OPTIONAL,
1442 // cRLIssuer [2] GeneralNames OPTIONAL }
1444 // DistributionPointName ::= CHOICE {
1445 // fullName [0] GeneralNames,
1446 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
1448 var cdp []distributionPoint
1449 if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
1451 } else if len(rest) != 0 {
1452 return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
1455 for _, dp := range cdp {
1456 // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
1457 if len(dp.DistributionPoint.FullName) == 0 {
1461 for _, fullName := range dp.DistributionPoint.FullName {
1462 if fullName.Tag == 6 {
1463 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(fullName.Bytes))
1469 // RFC 5280, 4.2.1.1
1471 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
1473 } else if len(rest) != 0 {
1474 return nil, errors.New("x509: trailing data after X.509 authority key-id")
1476 out.AuthorityKeyId = a.Id
1479 // RFC 5280, 4.2.1.12. Extended Key Usage
1481 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1483 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1485 // KeyPurposeId ::= OBJECT IDENTIFIER
1487 var keyUsage []asn1.ObjectIdentifier
1488 if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
1490 } else if len(rest) != 0 {
1491 return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
1494 for _, u := range keyUsage {
1495 if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1496 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1498 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1503 // RFC 5280, 4.2.1.2
1505 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
1507 } else if len(rest) != 0 {
1508 return nil, errors.New("x509: trailing data after X.509 key-id")
1510 out.SubjectKeyId = keyid
1513 // RFC 5280 4.2.1.4: Certificate Policies
1514 var policies []policyInformation
1515 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
1517 } else if len(rest) != 0 {
1518 return nil, errors.New("x509: trailing data after X.509 certificate policies")
1520 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1521 for i, policy := range policies {
1522 out.PolicyIdentifiers[i] = policy.Policy
1526 // Unknown extensions are recorded if critical.
1529 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
1530 // RFC 5280 4.2.2.1: Authority Information Access
1531 var aia []authorityInfoAccess
1532 if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
1534 } else if len(rest) != 0 {
1535 return nil, errors.New("x509: trailing data after X.509 authority information")
1538 for _, v := range aia {
1539 // GeneralName: uniformResourceIdentifier [6] IA5String
1540 if v.Location.Tag != 6 {
1543 if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
1544 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
1545 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
1546 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
1550 // Unknown extensions are recorded if critical.
1554 if e.Critical && unhandled {
1555 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
1562 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1563 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
1564 var cert certificate
1565 rest, err := asn1.Unmarshal(asn1Data, &cert)
1570 return nil, asn1.SyntaxError{Msg: "trailing data"}
1573 return parseCertificate(&cert)
1576 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1577 // data. The certificates must be concatenated with no intermediate padding.
1578 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
1579 var v []*certificate
1581 for len(asn1Data) > 0 {
1582 cert := new(certificate)
1584 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
1591 ret := make([]*Certificate, len(v))
1592 for i, ci := range v {
1593 cert, err := parseCertificate(ci)
1603 func reverseBitsInAByte(in byte) byte {
1605 b2 := b1>>2&0x33 | b1<<2&0xcc
1606 b3 := b2>>1&0x55 | b2<<1&0xaa
1610 // asn1BitLength returns the bit-length of bitString by considering the
1611 // most-significant bit in a byte to be the "first" bit. This convention
1612 // matches ASN.1, but differs from almost everything else.
1613 func asn1BitLength(bitString []byte) int {
1614 bitLen := len(bitString) * 8
1616 for i := range bitString {
1617 b := bitString[len(bitString)-i-1]
1619 for bit := uint(0); bit < 8; bit++ {
1620 if (b>>bit)&1 == 1 {
1631 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1632 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1633 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1634 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1635 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1636 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1637 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1638 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1639 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1640 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1641 oidExtensionCRLNumber = []int{2, 5, 29, 20}
1645 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1646 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1649 // oidNotInExtensions reports whether an extension with the given oid exists in
1651 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1652 for _, e := range extensions {
1653 if e.Id.Equal(oid) {
1660 // marshalSANs marshals a list of addresses into a the contents of an X.509
1661 // SubjectAlternativeName extension.
1662 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1663 var rawValues []asn1.RawValue
1664 for _, name := range dnsNames {
1665 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1667 for _, email := range emailAddresses {
1668 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1670 for _, rawIP := range ipAddresses {
1671 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1676 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1678 for _, uri := range uris {
1679 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uri.String())})
1681 return asn1.Marshal(rawValues)
1684 func isIA5String(s string) error {
1685 for _, r := range s {
1686 if r >= utf8.RuneSelf {
1687 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1694 func buildExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1695 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1698 if template.KeyUsage != 0 &&
1699 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1700 ret[n].Id = oidExtensionKeyUsage
1701 ret[n].Critical = true
1704 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1705 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1713 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1720 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1721 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1722 ret[n].Id = oidExtensionExtendedKeyUsage
1724 var oids []asn1.ObjectIdentifier
1725 for _, u := range template.ExtKeyUsage {
1726 if oid, ok := oidFromExtKeyUsage(u); ok {
1727 oids = append(oids, oid)
1729 panic("internal error")
1733 oids = append(oids, template.UnknownExtKeyUsage...)
1735 ret[n].Value, err = asn1.Marshal(oids)
1742 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1743 // Leaving MaxPathLen as zero indicates that no maximum path
1744 // length is desired, unless MaxPathLenZero is set. A value of
1745 // -1 causes encoding/asn1 to omit the value as desired.
1746 maxPathLen := template.MaxPathLen
1747 if maxPathLen == 0 && !template.MaxPathLenZero {
1750 ret[n].Id = oidExtensionBasicConstraints
1751 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
1752 ret[n].Critical = true
1759 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1760 ret[n].Id = oidExtensionSubjectKeyId
1761 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1768 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1769 ret[n].Id = oidExtensionAuthorityKeyId
1770 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1777 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1778 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1779 ret[n].Id = oidExtensionAuthorityInfoAccess
1780 var aiaValues []authorityInfoAccess
1781 for _, name := range template.OCSPServer {
1782 aiaValues = append(aiaValues, authorityInfoAccess{
1783 Method: oidAuthorityInfoAccessOcsp,
1784 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1787 for _, name := range template.IssuingCertificateURL {
1788 aiaValues = append(aiaValues, authorityInfoAccess{
1789 Method: oidAuthorityInfoAccessIssuers,
1790 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1793 ret[n].Value, err = asn1.Marshal(aiaValues)
1800 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1801 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1802 ret[n].Id = oidExtensionSubjectAltName
1803 // From RFC 5280, Section 4.2.1.6:
1804 // “If the subject field contains an empty sequence ... then
1805 // subjectAltName extension ... is marked as critical”
1806 ret[n].Critical = subjectIsEmpty
1807 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1814 if len(template.PolicyIdentifiers) > 0 &&
1815 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1816 ret[n].Id = oidExtensionCertificatePolicies
1817 policies := make([]policyInformation, len(template.PolicyIdentifiers))
1818 for i, policy := range template.PolicyIdentifiers {
1819 policies[i].Policy = policy
1821 ret[n].Value, err = asn1.Marshal(policies)
1828 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1829 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1830 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1831 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1832 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1833 ret[n].Id = oidExtensionNameConstraints
1834 ret[n].Critical = template.PermittedDNSDomainsCritical
1836 ipAndMask := func(ipNet *net.IPNet) []byte {
1837 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1838 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1839 ipAndMask = append(ipAndMask, maskedIP...)
1840 ipAndMask = append(ipAndMask, ipNet.Mask...)
1844 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1845 var b cryptobyte.Builder
1847 for _, name := range dns {
1848 if err = isIA5String(name); err != nil {
1852 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1853 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1854 b.AddBytes([]byte(name))
1859 for _, ipNet := range ips {
1860 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1861 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1862 b.AddBytes(ipAndMask(ipNet))
1867 for _, email := range emails {
1868 if err = isIA5String(email); err != nil {
1872 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1873 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1874 b.AddBytes([]byte(email))
1879 for _, uriDomain := range uriDomains {
1880 if err = isIA5String(uriDomain); err != nil {
1884 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1885 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1886 b.AddBytes([]byte(uriDomain))
1894 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1899 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1904 var b cryptobyte.Builder
1905 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1906 if len(permitted) > 0 {
1907 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1908 b.AddBytes(permitted)
1912 if len(excluded) > 0 {
1913 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1914 b.AddBytes(excluded)
1919 ret[n].Value, err = b.Bytes()
1926 if len(template.CRLDistributionPoints) > 0 &&
1927 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1928 ret[n].Id = oidExtensionCRLDistributionPoints
1930 var crlDp []distributionPoint
1931 for _, name := range template.CRLDistributionPoints {
1932 dp := distributionPoint{
1933 DistributionPoint: distributionPointName{
1934 FullName: []asn1.RawValue{
1935 {Tag: 6, Class: 2, Bytes: []byte(name)},
1939 crlDp = append(crlDp, dp)
1942 ret[n].Value, err = asn1.Marshal(crlDp)
1949 // Adding another extension here? Remember to update the maximum number
1950 // of elements in the make() at the top of the function and the list of
1951 // template fields used in CreateCertificate documentation.
1953 return append(ret[:n], template.ExtraExtensions...), nil
1956 func subjectBytes(cert *Certificate) ([]byte, error) {
1957 if len(cert.RawSubject) > 0 {
1958 return cert.RawSubject, nil
1961 return asn1.Marshal(cert.Subject.ToRDNSequence())
1964 // signingParamsForPublicKey returns the parameters to use for signing with
1965 // priv. If requestedSigAlgo is not zero then it overrides the default
1966 // signature algorithm.
1967 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1968 var pubType PublicKeyAlgorithm
1970 switch pub := pub.(type) {
1971 case *rsa.PublicKey:
1973 hashFunc = crypto.SHA256
1974 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1975 sigAlgo.Parameters = asn1.NullRawValue
1977 case *ecdsa.PublicKey:
1981 case elliptic.P224(), elliptic.P256():
1982 hashFunc = crypto.SHA256
1983 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1984 case elliptic.P384():
1985 hashFunc = crypto.SHA384
1986 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1987 case elliptic.P521():
1988 hashFunc = crypto.SHA512
1989 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1991 err = errors.New("x509: unknown elliptic curve")
1994 case ed25519.PublicKey:
1996 sigAlgo.Algorithm = oidSignatureEd25519
1999 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
2006 if requestedSigAlgo == 0 {
2011 for _, details := range signatureAlgorithmDetails {
2012 if details.algo == requestedSigAlgo {
2013 if details.pubKeyAlgo != pubType {
2014 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
2017 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
2018 if hashFunc == 0 && pubType != Ed25519 {
2019 err = errors.New("x509: cannot sign with hash function requested")
2022 if requestedSigAlgo.isRSAPSS() {
2023 sigAlgo.Parameters = rsaPSSParameters(hashFunc)
2031 err = errors.New("x509: unknown SignatureAlgorithm")
2037 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
2038 // just an empty SEQUENCE.
2039 var emptyASN1Subject = []byte{0x30, 0}
2041 // CreateCertificate creates a new X.509v3 certificate based on a template.
2042 // The following members of template are used:
2045 // - BasicConstraintsValid
2046 // - CRLDistributionPoints
2049 // - ExcludedDNSDomains
2050 // - ExcludedEmailAddresses
2051 // - ExcludedIPRanges
2052 // - ExcludedURIDomains
2054 // - ExtraExtensions
2057 // - IssuingCertificateURL
2064 // - PermittedDNSDomains
2065 // - PermittedDNSDomainsCritical
2066 // - PermittedEmailAddresses
2067 // - PermittedIPRanges
2068 // - PermittedURIDomains
2069 // - PolicyIdentifiers
2071 // - SignatureAlgorithm
2075 // - UnknownExtKeyUsage
2077 // The certificate is signed by parent. If parent is equal to template then the
2078 // certificate is self-signed. The parameter pub is the public key of the
2079 // signee and priv is the private key of the signer.
2081 // The returned slice is the certificate in DER encoding.
2083 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
2084 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
2085 // crypto.Signer with a supported public key.
2087 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
2088 // unless the resulting certificate is self-signed. Otherwise the value from
2089 // template will be used.
2091 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
2092 // will be generated from the hash of the public key.
2093 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
2094 key, ok := priv.(crypto.Signer)
2096 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2099 if template.SerialNumber == nil {
2100 return nil, errors.New("x509: no SerialNumber given")
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 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
2129 pki := publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey}
2130 subjectKeyId := template.SubjectKeyId
2131 if len(subjectKeyId) == 0 && template.IsCA {
2132 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2
2133 b, err := asn1.Marshal(pki)
2141 extensions, err := buildExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
2146 c := tbsCertificate{
2148 SerialNumber: template.SerialNumber,
2149 SignatureAlgorithm: signatureAlgorithm,
2150 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
2151 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
2152 Subject: asn1.RawValue{FullBytes: asn1Subject},
2154 Extensions: extensions,
2157 tbsCertContents, err := asn1.Marshal(c)
2161 c.Raw = tbsCertContents
2163 signed := tbsCertContents
2170 var signerOpts crypto.SignerOpts = hashFunc
2171 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
2172 signerOpts = &rsa.PSSOptions{
2173 SaltLength: rsa.PSSSaltLengthEqualsHash,
2178 var signature []byte
2179 signature, err = key.Sign(rand, signed, signerOpts)
2184 return asn1.Marshal(certificate{
2188 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2192 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
2194 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
2196 // pemType is the type of a PEM encoded CRL.
2197 var pemType = "X509 CRL"
2199 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
2200 // encoded CRLs will appear where they should be DER encoded, so this function
2201 // will transparently handle PEM encoding as long as there isn't any leading
2203 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
2204 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
2205 block, _ := pem.Decode(crlBytes)
2206 if block != nil && block.Type == pemType {
2207 crlBytes = block.Bytes
2210 return ParseDERCRL(crlBytes)
2213 // ParseDERCRL parses a DER encoded CRL from the given bytes.
2214 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
2215 certList := new(pkix.CertificateList)
2216 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
2218 } else if len(rest) != 0 {
2219 return nil, errors.New("x509: trailing data after CRL")
2221 return certList, nil
2224 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
2225 // contains the given list of revoked certificates.
2227 // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
2228 // To generate a standards compliant CRL, use CreateRevocationList instead.
2229 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
2230 key, ok := priv.(crypto.Signer)
2232 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2235 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
2240 // Force revocation times to UTC per RFC 5280.
2241 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
2242 for i, rc := range revokedCerts {
2243 rc.RevocationTime = rc.RevocationTime.UTC()
2244 revokedCertsUTC[i] = rc
2247 tbsCertList := pkix.TBSCertificateList{
2249 Signature: signatureAlgorithm,
2250 Issuer: c.Subject.ToRDNSequence(),
2251 ThisUpdate: now.UTC(),
2252 NextUpdate: expiry.UTC(),
2253 RevokedCertificates: revokedCertsUTC,
2257 if len(c.SubjectKeyId) > 0 {
2258 var aki pkix.Extension
2259 aki.Id = oidExtensionAuthorityKeyId
2260 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
2264 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
2267 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2272 signed := tbsCertListContents
2279 var signature []byte
2280 signature, err = key.Sign(rand, signed, hashFunc)
2285 return asn1.Marshal(pkix.CertificateList{
2286 TBSCertList: tbsCertList,
2287 SignatureAlgorithm: signatureAlgorithm,
2288 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2292 // CertificateRequest represents a PKCS #10, certificate signature request.
2293 type CertificateRequest struct {
2294 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
2295 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
2296 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
2297 RawSubject []byte // DER encoded Subject.
2301 SignatureAlgorithm SignatureAlgorithm
2303 PublicKeyAlgorithm PublicKeyAlgorithm
2304 PublicKey interface{}
2308 // Attributes contains the CSR attributes that can parse as
2309 // pkix.AttributeTypeAndValueSET.
2311 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
2312 // generating the requestedExtensions attribute.
2313 Attributes []pkix.AttributeTypeAndValueSET
2315 // Extensions contains all requested extensions, in raw form. When parsing
2316 // CSRs, this can be used to extract extensions that are not parsed by this
2318 Extensions []pkix.Extension
2320 // ExtraExtensions contains extensions to be copied, raw, into any CSR
2321 // marshaled by CreateCertificateRequest. Values override any extensions
2322 // that would otherwise be produced based on the other fields but are
2323 // overridden by any extensions specified in Attributes.
2325 // The ExtraExtensions field is not populated by ParseCertificateRequest,
2326 // see Extensions instead.
2327 ExtraExtensions []pkix.Extension
2329 // Subject Alternate Name values.
2331 EmailAddresses []string
2332 IPAddresses []net.IP
2336 // These structures reflect the ASN.1 structure of X.509 certificate
2337 // signature requests (see RFC 2986):
2339 type tbsCertificateRequest struct {
2342 Subject asn1.RawValue
2343 PublicKey publicKeyInfo
2344 RawAttributes []asn1.RawValue `asn1:"tag:0"`
2347 type certificateRequest struct {
2349 TBSCSR tbsCertificateRequest
2350 SignatureAlgorithm pkix.AlgorithmIdentifier
2351 SignatureValue asn1.BitString
2354 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
2355 // extensions in a CSR.
2356 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2358 // newRawAttributes converts AttributeTypeAndValueSETs from a template
2359 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
2360 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2361 var rawAttributes []asn1.RawValue
2362 b, err := asn1.Marshal(attributes)
2366 rest, err := asn1.Unmarshal(b, &rawAttributes)
2371 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2373 return rawAttributes, nil
2376 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
2377 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2378 var attributes []pkix.AttributeTypeAndValueSET
2379 for _, rawAttr := range rawAttributes {
2380 var attr pkix.AttributeTypeAndValueSET
2381 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2382 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2383 // (i.e.: challengePassword or unstructuredName).
2384 if err == nil && len(rest) == 0 {
2385 attributes = append(attributes, attr)
2391 // parseCSRExtensions parses the attributes from a CSR and extracts any
2392 // requested extensions.
2393 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2394 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
2395 type pkcs10Attribute struct {
2396 Id asn1.ObjectIdentifier
2397 Values []asn1.RawValue `asn1:"set"`
2400 var ret []pkix.Extension
2401 for _, rawAttr := range rawAttributes {
2402 var attr pkcs10Attribute
2403 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2404 // Ignore attributes that don't parse.
2408 if !attr.Id.Equal(oidExtensionRequest) {
2412 var extensions []pkix.Extension
2413 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2416 ret = append(ret, extensions...)
2422 // CreateCertificateRequest creates a new certificate request based on a
2423 // template. The following members of template are used:
2425 // - SignatureAlgorithm
2431 // - ExtraExtensions
2432 // - Attributes (deprecated)
2434 // priv is the private key to sign the CSR with, and the corresponding public
2435 // key will be included in the CSR. It must implement crypto.Signer and its
2436 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
2437 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
2438 // ed25519.PrivateKey satisfies this.)
2440 // The returned slice is the certificate request in DER encoding.
2441 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
2442 key, ok := priv.(crypto.Signer)
2444 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2447 var hashFunc crypto.Hash
2448 var sigAlgo pkix.AlgorithmIdentifier
2449 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2454 var publicKeyBytes []byte
2455 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2456 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2461 var extensions []pkix.Extension
2463 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
2464 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
2465 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
2470 extensions = append(extensions, pkix.Extension{
2471 Id: oidExtensionSubjectAltName,
2476 extensions = append(extensions, template.ExtraExtensions...)
2478 // Make a copy of template.Attributes because we may alter it below.
2479 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2480 for _, attr := range template.Attributes {
2481 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2482 copy(values, attr.Value)
2483 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2489 extensionsAppended := false
2490 if len(extensions) > 0 {
2491 // Append the extensions to an existing attribute if possible.
2492 for _, atvSet := range attributes {
2493 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2497 // specifiedExtensions contains all the extensions that we
2498 // found specified via template.Attributes.
2499 specifiedExtensions := make(map[string]bool)
2501 for _, atvs := range atvSet.Value {
2502 for _, atv := range atvs {
2503 specifiedExtensions[atv.Type.String()] = true
2507 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2508 newValue = append(newValue, atvSet.Value[0]...)
2510 for _, e := range extensions {
2511 if specifiedExtensions[e.Id.String()] {
2512 // Attributes already contained a value for
2513 // this extension and it takes priority.
2517 newValue = append(newValue, pkix.AttributeTypeAndValue{
2518 // There is no place for the critical
2519 // flag in an AttributeTypeAndValue.
2525 atvSet.Value[0] = newValue
2526 extensionsAppended = true
2531 rawAttributes, err := newRawAttributes(attributes)
2536 // If not included in attributes, add a new attribute for the
2538 if len(extensions) > 0 && !extensionsAppended {
2540 Type asn1.ObjectIdentifier
2541 Value [][]pkix.Extension `asn1:"set"`
2543 Type: oidExtensionRequest,
2544 Value: [][]pkix.Extension{extensions},
2547 b, err := asn1.Marshal(attr)
2549 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2552 var rawValue asn1.RawValue
2553 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2557 rawAttributes = append(rawAttributes, rawValue)
2560 asn1Subject := template.RawSubject
2561 if len(asn1Subject) == 0 {
2562 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2568 tbsCSR := tbsCertificateRequest{
2569 Version: 0, // PKCS #10, RFC 2986
2570 Subject: asn1.RawValue{FullBytes: asn1Subject},
2571 PublicKey: publicKeyInfo{
2572 Algorithm: publicKeyAlgorithm,
2573 PublicKey: asn1.BitString{
2574 Bytes: publicKeyBytes,
2575 BitLength: len(publicKeyBytes) * 8,
2578 RawAttributes: rawAttributes,
2581 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2585 tbsCSR.Raw = tbsCSRContents
2587 signed := tbsCSRContents
2594 var signature []byte
2595 signature, err = key.Sign(rand, signed, hashFunc)
2600 return asn1.Marshal(certificateRequest{
2602 SignatureAlgorithm: sigAlgo,
2603 SignatureValue: asn1.BitString{
2605 BitLength: len(signature) * 8,
2610 // ParseCertificateRequest parses a single certificate request from the
2611 // given ASN.1 DER data.
2612 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2613 var csr certificateRequest
2615 rest, err := asn1.Unmarshal(asn1Data, &csr)
2618 } else if len(rest) != 0 {
2619 return nil, asn1.SyntaxError{Msg: "trailing data"}
2622 return parseCertificateRequest(&csr)
2625 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2626 out := &CertificateRequest{
2628 RawTBSCertificateRequest: in.TBSCSR.Raw,
2629 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2630 RawSubject: in.TBSCSR.Subject.FullBytes,
2632 Signature: in.SignatureValue.RightAlign(),
2633 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2635 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2637 Version: in.TBSCSR.Version,
2638 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2642 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2647 var subject pkix.RDNSequence
2648 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2650 } else if len(rest) != 0 {
2651 return nil, errors.New("x509: trailing data after X.509 Subject")
2654 out.Subject.FillFromRDNSequence(&subject)
2656 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2660 for _, extension := range out.Extensions {
2661 if extension.Id.Equal(oidExtensionSubjectAltName) {
2662 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2672 // CheckSignature reports whether the signature on c is valid.
2673 func (c *CertificateRequest) CheckSignature() error {
2674 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
2677 // RevocationList contains the fields used to create an X.509 v2 Certificate
2678 // Revocation list with CreateRevocationList.
2679 type RevocationList struct {
2680 // SignatureAlgorithm is used to determine the signature algorithm to be
2681 // used when signing the CRL. If 0 the default algorithm for the signing
2682 // key will be used.
2683 SignatureAlgorithm SignatureAlgorithm
2685 // RevokedCertificates is used to populate the revokedCertificates
2686 // sequence in the CRL, it may be empty. RevokedCertificates may be nil,
2687 // in which case an empty CRL will be created.
2688 RevokedCertificates []pkix.RevokedCertificate
2690 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2691 // which should be a monotonically increasing sequence number for a given
2692 // CRL scope and CRL issuer.
2694 // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2695 // indicates the issuance date of the CRL.
2696 ThisUpdate time.Time
2697 // NextUpdate is used to populate the nextUpdate field in the CRL, which
2698 // indicates the date by which the next CRL will be issued. NextUpdate
2699 // must be greater than ThisUpdate.
2700 NextUpdate time.Time
2701 // ExtraExtensions contains any additional extensions to add directly to
2703 ExtraExtensions []pkix.Extension
2706 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
2707 // according to RFC 5280, based on template.
2709 // The CRL is signed by priv which should be the private key associated with
2710 // the public key in the issuer certificate.
2712 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
2713 // order to use it as a CRL issuer.
2715 // The issuer distinguished name CRL field and authority key identifier
2716 // extension are populated using the issuer certificate. issuer must have
2717 // SubjectKeyId set.
2718 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2719 if template == nil {
2720 return nil, errors.New("x509: template can not be nil")
2723 return nil, errors.New("x509: issuer can not be nil")
2725 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2726 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2728 if len(issuer.SubjectKeyId) == 0 {
2729 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2731 if template.NextUpdate.Before(template.ThisUpdate) {
2732 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2734 if template.Number == nil {
2735 return nil, errors.New("x509: template contains nil Number field")
2738 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2743 // Force revocation times to UTC per RFC 5280.
2744 revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2745 for i, rc := range template.RevokedCertificates {
2746 rc.RevocationTime = rc.RevocationTime.UTC()
2747 revokedCertsUTC[i] = rc
2750 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2754 crlNum, err := asn1.Marshal(template.Number)
2759 tbsCertList := pkix.TBSCertificateList{
2761 Signature: signatureAlgorithm,
2762 Issuer: issuer.Subject.ToRDNSequence(),
2763 ThisUpdate: template.ThisUpdate.UTC(),
2764 NextUpdate: template.NextUpdate.UTC(),
2765 Extensions: []pkix.Extension{
2767 Id: oidExtensionAuthorityKeyId,
2771 Id: oidExtensionCRLNumber,
2776 if len(revokedCertsUTC) > 0 {
2777 tbsCertList.RevokedCertificates = revokedCertsUTC
2780 if len(template.ExtraExtensions) > 0 {
2781 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2784 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2789 input := tbsCertListContents
2792 h.Write(tbsCertListContents)
2795 var signerOpts crypto.SignerOpts = hashFunc
2796 if template.SignatureAlgorithm.isRSAPSS() {
2797 signerOpts = &rsa.PSSOptions{
2798 SaltLength: rsa.PSSSaltLengthEqualsHash,
2803 signature, err := priv.Sign(rand, input, signerOpts)
2808 return asn1.Marshal(pkix.CertificateList{
2809 TBSCertList: tbsCertList,
2810 SignatureAlgorithm: signatureAlgorithm,
2811 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},