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.
37 "golang.org/x/crypto/cryptobyte"
38 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
41 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
43 type pkixPublicKey struct {
44 Algo pkix.AlgorithmIdentifier
45 BitString asn1.BitString
48 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
50 // It returns a *rsa.PublicKey, *dsa.PublicKey, *ecdsa.PublicKey, or
51 // ed25519.PublicKey. More types might be supported in the future.
53 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
54 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
56 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
57 if _, err := asn1.Unmarshal(derBytes, &pkcs1PublicKey{}); err == nil {
58 return nil, errors.New("x509: failed to parse public key (use ParsePKCS1PublicKey instead for this key format)")
61 } else if len(rest) != 0 {
62 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
64 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
65 if algo == UnknownPublicKeyAlgorithm {
66 return nil, errors.New("x509: unknown public key algorithm")
68 return parsePublicKey(algo, &pki)
71 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
72 switch pub := pub.(type) {
74 publicKeyBytes, err = asn1.Marshal(pkcs1PublicKey{
79 return nil, pkix.AlgorithmIdentifier{}, err
81 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
82 // This is a NULL parameters value which is required by
83 // RFC 3279, Section 2.3.1.
84 publicKeyAlgorithm.Parameters = asn1.NullRawValue
85 case *ecdsa.PublicKey:
86 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
87 oid, ok := oidFromNamedCurve(pub.Curve)
89 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
91 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
93 paramBytes, err = asn1.Marshal(oid)
97 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
98 case ed25519.PublicKey:
100 publicKeyAlgorithm.Algorithm = oidPublicKeyEd25519
102 return nil, pkix.AlgorithmIdentifier{}, fmt.Errorf("x509: unsupported public key type: %T", pub)
105 return publicKeyBytes, publicKeyAlgorithm, nil
108 // MarshalPKIXPublicKey converts a public key to PKIX, ASN.1 DER form.
110 // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
111 // and ed25519.PublicKey. Unsupported key types result in an error.
113 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
114 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
115 var publicKeyBytes []byte
116 var publicKeyAlgorithm pkix.AlgorithmIdentifier
119 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
123 pkix := pkixPublicKey{
124 Algo: publicKeyAlgorithm,
125 BitString: asn1.BitString{
126 Bytes: publicKeyBytes,
127 BitLength: 8 * len(publicKeyBytes),
131 ret, _ := asn1.Marshal(pkix)
135 // These structures reflect the ASN.1 structure of X.509 certificates.:
137 type certificate struct {
139 TBSCertificate tbsCertificate
140 SignatureAlgorithm pkix.AlgorithmIdentifier
141 SignatureValue asn1.BitString
144 type tbsCertificate struct {
146 Version int `asn1:"optional,explicit,default:0,tag:0"`
147 SerialNumber *big.Int
148 SignatureAlgorithm pkix.AlgorithmIdentifier
151 Subject asn1.RawValue
152 PublicKey publicKeyInfo
153 UniqueId asn1.BitString `asn1:"optional,tag:1"`
154 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
155 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
158 type dsaAlgorithmParameters struct {
162 type dsaSignature struct {
166 type validity struct {
167 NotBefore, NotAfter time.Time
170 type publicKeyInfo struct {
172 Algorithm pkix.AlgorithmIdentifier
173 PublicKey asn1.BitString
177 type authKeyId struct {
178 Id []byte `asn1:"optional,tag:0"`
181 type SignatureAlgorithm int
184 UnknownSignatureAlgorithm SignatureAlgorithm = iota
203 func (algo SignatureAlgorithm) isRSAPSS() bool {
205 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
212 func (algo SignatureAlgorithm) String() string {
213 for _, details := range signatureAlgorithmDetails {
214 if details.algo == algo {
218 return strconv.Itoa(int(algo))
221 type PublicKeyAlgorithm int
224 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
231 var publicKeyAlgoName = [...]string{
238 func (algo PublicKeyAlgorithm) String() string {
239 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
240 return publicKeyAlgoName[algo]
242 return strconv.Itoa(int(algo))
245 // OIDs for signature algorithms
247 // pkcs-1 OBJECT IDENTIFIER ::= {
248 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
251 // RFC 3279 2.2.1 RSA Signature Algorithms
253 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
255 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
257 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
259 // dsaWithSha1 OBJECT IDENTIFIER ::= {
260 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
262 // RFC 3279 2.2.3 ECDSA Signature Algorithm
264 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
265 // iso(1) member-body(2) us(840) ansi-x962(10045)
266 // signatures(4) ecdsa-with-SHA1(1)}
269 // RFC 4055 5 PKCS #1 Version 1.5
271 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
273 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
275 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
278 // RFC 5758 3.1 DSA Signature Algorithms
280 // dsaWithSha256 OBJECT IDENTIFIER ::= {
281 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
282 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
284 // RFC 5758 3.2 ECDSA Signature Algorithm
286 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
287 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
289 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
290 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
292 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
293 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
296 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
298 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
301 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
302 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
303 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
304 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
305 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
306 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
307 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
308 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
309 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
310 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
311 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
312 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
313 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
314 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
316 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
317 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
318 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
320 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
322 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
323 // but it's specified by ISO. Microsoft's makecert.exe has been known
324 // to produce certificates with this OID.
325 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
328 var signatureAlgorithmDetails = []struct {
329 algo SignatureAlgorithm
331 oid asn1.ObjectIdentifier
332 pubKeyAlgo PublicKeyAlgorithm
335 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
336 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
337 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
338 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
339 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
340 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
341 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
342 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
343 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
344 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
345 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
346 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
347 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
348 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
349 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
350 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
351 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
354 // pssParameters reflects the parameters in an AlgorithmIdentifier that
355 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
356 type pssParameters struct {
357 // The following three fields are not marked as
358 // optional because the default values specify SHA-1,
359 // which is no longer suitable for use in signatures.
360 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
361 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
362 SaltLength int `asn1:"explicit,tag:2"`
363 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
366 // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
367 // in an AlgorithmIdentifier that specifies RSA PSS.
368 func rsaPSSParameters(hashFunc crypto.Hash) asn1.RawValue {
369 var hashOID asn1.ObjectIdentifier
380 params := pssParameters{
381 Hash: pkix.AlgorithmIdentifier{
383 Parameters: asn1.NullRawValue,
385 MGF: pkix.AlgorithmIdentifier{
388 SaltLength: hashFunc.Size(),
392 mgf1Params := pkix.AlgorithmIdentifier{
394 Parameters: asn1.NullRawValue,
398 params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
403 serialized, err := asn1.Marshal(params)
408 return asn1.RawValue{FullBytes: serialized}
411 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
412 if ai.Algorithm.Equal(oidSignatureEd25519) {
413 // RFC 8410, Section 3
414 // > For all of the OIDs, the parameters MUST be absent.
415 if len(ai.Parameters.FullBytes) != 0 {
416 return UnknownSignatureAlgorithm
420 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
421 for _, details := range signatureAlgorithmDetails {
422 if ai.Algorithm.Equal(details.oid) {
426 return UnknownSignatureAlgorithm
429 // RSA PSS is special because it encodes important parameters
430 // in the Parameters.
432 var params pssParameters
433 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
434 return UnknownSignatureAlgorithm
437 var mgf1HashFunc pkix.AlgorithmIdentifier
438 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
439 return UnknownSignatureAlgorithm
442 // PSS is greatly overburdened with options. This code forces them into
443 // three buckets by requiring that the MGF1 hash function always match the
444 // message hash function (as recommended in RFC 3447, Section 8.1), that the
445 // salt length matches the hash length, and that the trailer field has the
447 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
448 !params.MGF.Algorithm.Equal(oidMGF1) ||
449 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
450 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
451 params.TrailerField != 1 {
452 return UnknownSignatureAlgorithm
456 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
457 return SHA256WithRSAPSS
458 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
459 return SHA384WithRSAPSS
460 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
461 return SHA512WithRSAPSS
464 return UnknownSignatureAlgorithm
467 // RFC 3279, 2.3 Public Key Algorithms
469 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
470 // rsadsi(113549) pkcs(1) 1 }
472 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
474 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
475 // x9-57(10040) x9cm(4) 1 }
477 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
479 // id-ecPublicKey OBJECT IDENTIFIER ::= {
480 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
482 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
483 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
484 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
485 oidPublicKeyEd25519 = oidSignatureEd25519
488 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
490 case oid.Equal(oidPublicKeyRSA):
492 case oid.Equal(oidPublicKeyDSA):
494 case oid.Equal(oidPublicKeyECDSA):
496 case oid.Equal(oidPublicKeyEd25519):
499 return UnknownPublicKeyAlgorithm
502 // RFC 5480, 2.1.1.1. Named Curve
504 // secp224r1 OBJECT IDENTIFIER ::= {
505 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
507 // secp256r1 OBJECT IDENTIFIER ::= {
508 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
511 // secp384r1 OBJECT IDENTIFIER ::= {
512 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
514 // secp521r1 OBJECT IDENTIFIER ::= {
515 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
517 // NB: secp256r1 is equivalent to prime256v1
519 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
520 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
521 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
522 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
525 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
527 case oid.Equal(oidNamedCurveP224):
528 return elliptic.P224()
529 case oid.Equal(oidNamedCurveP256):
530 return elliptic.P256()
531 case oid.Equal(oidNamedCurveP384):
532 return elliptic.P384()
533 case oid.Equal(oidNamedCurveP521):
534 return elliptic.P521()
539 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
541 case elliptic.P224():
542 return oidNamedCurveP224, true
543 case elliptic.P256():
544 return oidNamedCurveP256, true
545 case elliptic.P384():
546 return oidNamedCurveP384, true
547 case elliptic.P521():
548 return oidNamedCurveP521, true
554 // KeyUsage represents the set of actions that are valid for a given key. It's
555 // a bitmap of the KeyUsage* constants.
559 KeyUsageDigitalSignature KeyUsage = 1 << iota
560 KeyUsageContentCommitment
561 KeyUsageKeyEncipherment
562 KeyUsageDataEncipherment
570 // RFC 5280, 4.2.1.12 Extended Key Usage
572 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
574 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
576 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
577 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
578 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
579 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
580 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
581 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
583 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
584 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
585 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
586 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
587 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
588 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
589 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
590 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
591 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
592 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
593 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
594 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
595 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
596 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
599 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
600 // Each of the ExtKeyUsage* constants define a unique action.
604 ExtKeyUsageAny ExtKeyUsage = iota
605 ExtKeyUsageServerAuth
606 ExtKeyUsageClientAuth
607 ExtKeyUsageCodeSigning
608 ExtKeyUsageEmailProtection
609 ExtKeyUsageIPSECEndSystem
610 ExtKeyUsageIPSECTunnel
612 ExtKeyUsageTimeStamping
613 ExtKeyUsageOCSPSigning
614 ExtKeyUsageMicrosoftServerGatedCrypto
615 ExtKeyUsageNetscapeServerGatedCrypto
616 ExtKeyUsageMicrosoftCommercialCodeSigning
617 ExtKeyUsageMicrosoftKernelCodeSigning
620 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
621 var extKeyUsageOIDs = []struct {
622 extKeyUsage ExtKeyUsage
623 oid asn1.ObjectIdentifier
625 {ExtKeyUsageAny, oidExtKeyUsageAny},
626 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
627 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
628 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
629 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
630 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
631 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
632 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
633 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
634 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
635 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
636 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
637 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
638 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
641 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
642 for _, pair := range extKeyUsageOIDs {
643 if oid.Equal(pair.oid) {
644 return pair.extKeyUsage, true
650 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
651 for _, pair := range extKeyUsageOIDs {
652 if eku == pair.extKeyUsage {
653 return pair.oid, true
659 // A Certificate represents an X.509 certificate.
660 type Certificate struct {
661 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
662 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
663 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
664 RawSubject []byte // DER encoded Subject
665 RawIssuer []byte // DER encoded Issuer
668 SignatureAlgorithm SignatureAlgorithm
670 PublicKeyAlgorithm PublicKeyAlgorithm
671 PublicKey interface{}
674 SerialNumber *big.Int
677 NotBefore, NotAfter time.Time // Validity bounds.
680 // Extensions contains raw X.509 extensions. When parsing certificates,
681 // this can be used to extract non-critical extensions that are not
682 // parsed by this package. When marshaling certificates, the Extensions
683 // field is ignored, see ExtraExtensions.
684 Extensions []pkix.Extension
686 // ExtraExtensions contains extensions to be copied, raw, into any
687 // marshaled certificates. Values override any extensions that would
688 // otherwise be produced based on the other fields. The ExtraExtensions
689 // field is not populated when parsing certificates, see Extensions.
690 ExtraExtensions []pkix.Extension
692 // UnhandledCriticalExtensions contains a list of extension IDs that
693 // were not (fully) processed when parsing. Verify will fail if this
694 // slice is non-empty, unless verification is delegated to an OS
695 // library which understands all the critical extensions.
697 // Users can access these extensions using Extensions and can remove
698 // elements from this slice if they believe that they have been
700 UnhandledCriticalExtensions []asn1.ObjectIdentifier
702 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
703 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
705 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
706 // and MaxPathLenZero are valid.
707 BasicConstraintsValid bool
710 // MaxPathLen and MaxPathLenZero indicate the presence and
711 // value of the BasicConstraints' "pathLenConstraint".
713 // When parsing a certificate, a positive non-zero MaxPathLen
714 // means that the field was specified, -1 means it was unset,
715 // and MaxPathLenZero being true mean that the field was
716 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
717 // should be treated equivalent to -1 (unset).
719 // When generating a certificate, an unset pathLenConstraint
720 // can be requested with either MaxPathLen == -1 or using the
721 // zero value for both MaxPathLen and MaxPathLenZero.
723 // MaxPathLenZero indicates that BasicConstraintsValid==true
724 // and MaxPathLen==0 should be interpreted as an actual
725 // maximum path length of zero. Otherwise, that combination is
726 // interpreted as MaxPathLen not being set.
730 AuthorityKeyId []byte
732 // RFC 5280, 4.2.2.1 (Authority Information Access)
734 IssuingCertificateURL []string
736 // Subject Alternate Name values. (Note that these values may not be valid
737 // if invalid values were contained within a parsed certificate. For
738 // example, an element of DNSNames may not be a valid DNS domain name.)
740 EmailAddresses []string
745 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
746 PermittedDNSDomains []string
747 ExcludedDNSDomains []string
748 PermittedIPRanges []*net.IPNet
749 ExcludedIPRanges []*net.IPNet
750 PermittedEmailAddresses []string
751 ExcludedEmailAddresses []string
752 PermittedURIDomains []string
753 ExcludedURIDomains []string
755 // CRL Distribution Points
756 CRLDistributionPoints []string
758 PolicyIdentifiers []asn1.ObjectIdentifier
761 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
762 // involves algorithms that are not currently implemented.
763 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
765 // An InsecureAlgorithmError
766 type InsecureAlgorithmError SignatureAlgorithm
768 func (e InsecureAlgorithmError) Error() string {
769 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
772 // ConstraintViolationError results when a requested usage is not permitted by
773 // a certificate. For example: checking a signature when the public key isn't a
774 // certificate signing key.
775 type ConstraintViolationError struct{}
777 func (ConstraintViolationError) Error() string {
778 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
781 func (c *Certificate) Equal(other *Certificate) bool {
782 if c == nil || other == nil {
785 return bytes.Equal(c.Raw, other.Raw)
788 func (c *Certificate) hasSANExtension() bool {
789 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
792 // CheckSignatureFrom verifies that the signature on c is a valid signature
794 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
795 // RFC 5280, 4.2.1.9:
796 // "If the basic constraints extension is not present in a version 3
797 // certificate, or the extension is present but the cA boolean is not
798 // asserted, then the certified public key MUST NOT be used to verify
799 // certificate signatures."
800 if parent.Version == 3 && !parent.BasicConstraintsValid ||
801 parent.BasicConstraintsValid && !parent.IsCA {
802 return ConstraintViolationError{}
805 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
806 return ConstraintViolationError{}
809 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
810 return ErrUnsupportedAlgorithm
813 // TODO(agl): don't ignore the path length constraint.
815 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
818 // CheckSignature verifies that signature is a valid signature over signed from
820 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
821 return checkSignature(algo, signed, signature, c.PublicKey)
824 func (c *Certificate) hasNameConstraints() bool {
825 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
828 func (c *Certificate) getSANExtension() []byte {
829 for _, e := range c.Extensions {
830 if e.Id.Equal(oidExtensionSubjectAltName) {
837 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
838 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
841 // CheckSignature verifies that signature is a valid signature over signed from
842 // a crypto.PublicKey.
843 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
844 var hashType crypto.Hash
845 var pubKeyAlgo PublicKeyAlgorithm
847 for _, details := range signatureAlgorithmDetails {
848 if details.algo == algo {
849 hashType = details.hash
850 pubKeyAlgo = details.pubKeyAlgo
856 if pubKeyAlgo != Ed25519 {
857 return ErrUnsupportedAlgorithm
860 return InsecureAlgorithmError(algo)
862 if !hashType.Available() {
863 return ErrUnsupportedAlgorithm
870 switch pub := publicKey.(type) {
872 if pubKeyAlgo != RSA {
873 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
876 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
878 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
881 if pubKeyAlgo != DSA {
882 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
884 dsaSig := new(dsaSignature)
885 if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
887 } else if len(rest) != 0 {
888 return errors.New("x509: trailing data after DSA signature")
890 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
891 return errors.New("x509: DSA signature contained zero or negative values")
893 // According to FIPS 186-3, section 4.6, the hash must be truncated if it is longer
894 // than the key length, but crypto/dsa doesn't do it automatically.
895 if maxHashLen := pub.Q.BitLen() / 8; maxHashLen < len(signed) {
896 signed = signed[:maxHashLen]
898 if !dsa.Verify(pub, signed, dsaSig.R, dsaSig.S) {
899 return errors.New("x509: DSA verification failure")
902 case *ecdsa.PublicKey:
903 if pubKeyAlgo != ECDSA {
904 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
906 if !ecdsa.VerifyASN1(pub, signed, signature) {
907 return errors.New("x509: ECDSA verification failure")
910 case ed25519.PublicKey:
911 if pubKeyAlgo != Ed25519 {
912 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
914 if !ed25519.Verify(pub, signed, signature) {
915 return errors.New("x509: Ed25519 verification failure")
919 return ErrUnsupportedAlgorithm
922 // CheckCRLSignature checks that the signature in crl is from c.
923 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
924 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
925 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
928 type UnhandledCriticalExtension struct{}
930 func (h UnhandledCriticalExtension) Error() string {
931 return "x509: unhandled critical extension"
934 type basicConstraints struct {
935 IsCA bool `asn1:"optional"`
936 MaxPathLen int `asn1:"optional,default:-1"`
940 type policyInformation struct {
941 Policy asn1.ObjectIdentifier
942 // policyQualifiers omitted
953 type authorityInfoAccess struct {
954 Method asn1.ObjectIdentifier
955 Location asn1.RawValue
958 // RFC 5280, 4.2.1.14
959 type distributionPoint struct {
960 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
961 Reason asn1.BitString `asn1:"optional,tag:1"`
962 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
965 type distributionPointName struct {
966 FullName []asn1.RawValue `asn1:"optional,tag:0"`
967 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
970 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
971 asn1Data := keyData.PublicKey.RightAlign()
974 // RSA public keys must have a NULL in the parameters.
975 // See RFC 3279, Section 2.3.1.
976 if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1.NullBytes) {
977 return nil, errors.New("x509: RSA key missing NULL parameters")
980 p := new(pkcs1PublicKey)
981 rest, err := asn1.Unmarshal(asn1Data, p)
986 return nil, errors.New("x509: trailing data after RSA public key")
990 return nil, errors.New("x509: RSA modulus is not a positive number")
993 return nil, errors.New("x509: RSA public exponent is not a positive number")
996 pub := &rsa.PublicKey{
1003 rest, err := asn1.Unmarshal(asn1Data, &p)
1008 return nil, errors.New("x509: trailing data after DSA public key")
1010 paramsData := keyData.Algorithm.Parameters.FullBytes
1011 params := new(dsaAlgorithmParameters)
1012 rest, err = asn1.Unmarshal(paramsData, params)
1017 return nil, errors.New("x509: trailing data after DSA parameters")
1019 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
1020 return nil, errors.New("x509: zero or negative DSA parameter")
1022 pub := &dsa.PublicKey{
1023 Parameters: dsa.Parameters{
1032 paramsData := keyData.Algorithm.Parameters.FullBytes
1033 namedCurveOID := new(asn1.ObjectIdentifier)
1034 rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
1036 return nil, errors.New("x509: failed to parse ECDSA parameters as named curve")
1039 return nil, errors.New("x509: trailing data after ECDSA parameters")
1041 namedCurve := namedCurveFromOID(*namedCurveOID)
1042 if namedCurve == nil {
1043 return nil, errors.New("x509: unsupported elliptic curve")
1045 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
1047 return nil, errors.New("x509: failed to unmarshal elliptic curve point")
1049 pub := &ecdsa.PublicKey{
1056 // RFC 8410, Section 3
1057 // > For all of the OIDs, the parameters MUST be absent.
1058 if len(keyData.Algorithm.Parameters.FullBytes) != 0 {
1059 return nil, errors.New("x509: Ed25519 key encoded with illegal parameters")
1061 if len(asn1Data) != ed25519.PublicKeySize {
1062 return nil, errors.New("x509: wrong Ed25519 public key size")
1064 pub := make([]byte, ed25519.PublicKeySize)
1066 return ed25519.PublicKey(pub), nil
1072 func forEachSAN(extension []byte, callback func(tag int, data []byte) error) error {
1073 // RFC 5280, 4.2.1.6
1075 // SubjectAltName ::= GeneralNames
1077 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1079 // GeneralName ::= CHOICE {
1080 // otherName [0] OtherName,
1081 // rfc822Name [1] IA5String,
1082 // dNSName [2] IA5String,
1083 // x400Address [3] ORAddress,
1084 // directoryName [4] Name,
1085 // ediPartyName [5] EDIPartyName,
1086 // uniformResourceIdentifier [6] IA5String,
1087 // iPAddress [7] OCTET STRING,
1088 // registeredID [8] OBJECT IDENTIFIER }
1089 var seq asn1.RawValue
1090 rest, err := asn1.Unmarshal(extension, &seq)
1093 } else if len(rest) != 0 {
1094 return errors.New("x509: trailing data after X.509 extension")
1096 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
1097 return asn1.StructuralError{Msg: "bad SAN sequence"}
1103 rest, err = asn1.Unmarshal(rest, &v)
1108 if err := callback(v.Tag, v.Bytes); err != nil {
1116 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL, err error) {
1117 err = forEachSAN(value, func(tag int, data []byte) error {
1120 emailAddresses = append(emailAddresses, string(data))
1122 dnsNames = append(dnsNames, string(data))
1124 uri, err := url.Parse(string(data))
1126 return fmt.Errorf("x509: cannot parse URI %q: %s", string(data), err)
1128 if len(uri.Host) > 0 {
1129 if _, ok := domainToReverseLabels(uri.Host); !ok {
1130 return fmt.Errorf("x509: cannot parse URI %q: invalid domain", string(data))
1133 uris = append(uris, uri)
1136 case net.IPv4len, net.IPv6len:
1137 ipAddresses = append(ipAddresses, data)
1139 return errors.New("x509: cannot parse IP address of length " + strconv.Itoa(len(data)))
1149 // isValidIPMask reports whether mask consists of zero or more 1 bits, followed by zero bits.
1150 func isValidIPMask(mask []byte) bool {
1153 for _, b := range mask {
1163 case 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe:
1174 func parseNameConstraintsExtension(out *Certificate, e pkix.Extension) (unhandled bool, err error) {
1175 // RFC 5280, 4.2.1.10
1177 // NameConstraints ::= SEQUENCE {
1178 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
1179 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
1181 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
1183 // GeneralSubtree ::= SEQUENCE {
1184 // base GeneralName,
1185 // minimum [0] BaseDistance DEFAULT 0,
1186 // maximum [1] BaseDistance OPTIONAL }
1188 // BaseDistance ::= INTEGER (0..MAX)
1190 outer := cryptobyte.String(e.Value)
1191 var toplevel, permitted, excluded cryptobyte.String
1192 var havePermitted, haveExcluded bool
1193 if !outer.ReadASN1(&toplevel, cryptobyte_asn1.SEQUENCE) ||
1195 !toplevel.ReadOptionalASN1(&permitted, &havePermitted, cryptobyte_asn1.Tag(0).ContextSpecific().Constructed()) ||
1196 !toplevel.ReadOptionalASN1(&excluded, &haveExcluded, cryptobyte_asn1.Tag(1).ContextSpecific().Constructed()) ||
1198 return false, errors.New("x509: invalid NameConstraints extension")
1201 if !havePermitted && !haveExcluded || len(permitted) == 0 && len(excluded) == 0 {
1202 // From RFC 5280, Section 4.2.1.10:
1203 // “either the permittedSubtrees field
1204 // or the excludedSubtrees MUST be
1206 return false, errors.New("x509: empty name constraints extension")
1209 getValues := func(subtrees cryptobyte.String) (dnsNames []string, ips []*net.IPNet, emails, uriDomains []string, err error) {
1210 for !subtrees.Empty() {
1211 var seq, value cryptobyte.String
1212 var tag cryptobyte_asn1.Tag
1213 if !subtrees.ReadASN1(&seq, cryptobyte_asn1.SEQUENCE) ||
1214 !seq.ReadAnyASN1(&value, &tag) {
1215 return nil, nil, nil, nil, fmt.Errorf("x509: invalid NameConstraints extension")
1219 dnsTag = cryptobyte_asn1.Tag(2).ContextSpecific()
1220 emailTag = cryptobyte_asn1.Tag(1).ContextSpecific()
1221 ipTag = cryptobyte_asn1.Tag(7).ContextSpecific()
1222 uriTag = cryptobyte_asn1.Tag(6).ContextSpecific()
1227 domain := string(value)
1228 if err := isIA5String(domain); err != nil {
1229 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1232 trimmedDomain := domain
1233 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1234 // constraints can have a leading
1235 // period to exclude the domain
1236 // itself, but that's not valid in a
1237 // normal domain name.
1238 trimmedDomain = trimmedDomain[1:]
1240 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1241 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse dnsName constraint %q", domain)
1243 dnsNames = append(dnsNames, domain)
1259 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained value of length %d", l)
1262 if !isValidIPMask(mask) {
1263 return nil, nil, nil, nil, fmt.Errorf("x509: IP constraint contained invalid mask %x", mask)
1266 ips = append(ips, &net.IPNet{IP: net.IP(ip), Mask: net.IPMask(mask)})
1269 constraint := string(value)
1270 if err := isIA5String(constraint); err != nil {
1271 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1274 // If the constraint contains an @ then
1275 // it specifies an exact mailbox name.
1276 if strings.Contains(constraint, "@") {
1277 if _, ok := parseRFC2821Mailbox(constraint); !ok {
1278 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1281 // Otherwise it's a domain name.
1282 domain := constraint
1283 if len(domain) > 0 && domain[0] == '.' {
1286 if _, ok := domainToReverseLabels(domain); !ok {
1287 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse rfc822Name constraint %q", constraint)
1290 emails = append(emails, constraint)
1293 domain := string(value)
1294 if err := isIA5String(domain); err != nil {
1295 return nil, nil, nil, nil, errors.New("x509: invalid constraint value: " + err.Error())
1298 if net.ParseIP(domain) != nil {
1299 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q: cannot be IP address", domain)
1302 trimmedDomain := domain
1303 if len(trimmedDomain) > 0 && trimmedDomain[0] == '.' {
1304 // constraints can have a leading
1305 // period to exclude the domain itself,
1306 // but that's not valid in a normal
1308 trimmedDomain = trimmedDomain[1:]
1310 if _, ok := domainToReverseLabels(trimmedDomain); !ok {
1311 return nil, nil, nil, nil, fmt.Errorf("x509: failed to parse URI constraint %q", domain)
1313 uriDomains = append(uriDomains, domain)
1320 return dnsNames, ips, emails, uriDomains, nil
1323 if out.PermittedDNSDomains, out.PermittedIPRanges, out.PermittedEmailAddresses, out.PermittedURIDomains, err = getValues(permitted); err != nil {
1326 if out.ExcludedDNSDomains, out.ExcludedIPRanges, out.ExcludedEmailAddresses, out.ExcludedURIDomains, err = getValues(excluded); err != nil {
1329 out.PermittedDNSDomainsCritical = e.Critical
1331 return unhandled, nil
1334 func parseCertificate(in *certificate) (*Certificate, error) {
1335 out := new(Certificate)
1337 out.RawTBSCertificate = in.TBSCertificate.Raw
1338 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
1339 out.RawSubject = in.TBSCertificate.Subject.FullBytes
1340 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
1342 out.Signature = in.SignatureValue.RightAlign()
1343 out.SignatureAlgorithm =
1344 getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
1346 out.PublicKeyAlgorithm =
1347 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
1349 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
1354 out.Version = in.TBSCertificate.Version + 1
1355 out.SerialNumber = in.TBSCertificate.SerialNumber
1357 var issuer, subject pkix.RDNSequence
1358 if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
1360 } else if len(rest) != 0 {
1361 return nil, errors.New("x509: trailing data after X.509 subject")
1363 if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
1365 } else if len(rest) != 0 {
1366 return nil, errors.New("x509: trailing data after X.509 issuer")
1369 out.Issuer.FillFromRDNSequence(&issuer)
1370 out.Subject.FillFromRDNSequence(&subject)
1372 out.NotBefore = in.TBSCertificate.Validity.NotBefore
1373 out.NotAfter = in.TBSCertificate.Validity.NotAfter
1375 for _, e := range in.TBSCertificate.Extensions {
1376 out.Extensions = append(out.Extensions, e)
1379 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
1382 // RFC 5280, 4.2.1.3
1383 var usageBits asn1.BitString
1384 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
1386 } else if len(rest) != 0 {
1387 return nil, errors.New("x509: trailing data after X.509 KeyUsage")
1391 for i := 0; i < 9; i++ {
1392 if usageBits.At(i) != 0 {
1393 usage |= 1 << uint(i)
1396 out.KeyUsage = KeyUsage(usage)
1399 // RFC 5280, 4.2.1.9
1400 var constraints basicConstraints
1401 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1403 } else if len(rest) != 0 {
1404 return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
1407 out.BasicConstraintsValid = true
1408 out.IsCA = constraints.IsCA
1409 out.MaxPathLen = constraints.MaxPathLen
1410 out.MaxPathLenZero = out.MaxPathLen == 0
1411 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
1413 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(e.Value)
1418 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 && len(out.URIs) == 0 {
1419 // If we didn't parse anything then we do the critical check, below.
1424 unhandled, err = parseNameConstraintsExtension(out, e)
1430 // RFC 5280, 4.2.1.13
1432 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1434 // DistributionPoint ::= SEQUENCE {
1435 // distributionPoint [0] DistributionPointName OPTIONAL,
1436 // reasons [1] ReasonFlags OPTIONAL,
1437 // cRLIssuer [2] GeneralNames OPTIONAL }
1439 // DistributionPointName ::= CHOICE {
1440 // fullName [0] GeneralNames,
1441 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
1443 var cdp []distributionPoint
1444 if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
1446 } else if len(rest) != 0 {
1447 return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
1450 for _, dp := range cdp {
1451 // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
1452 if len(dp.DistributionPoint.FullName) == 0 {
1456 for _, fullName := range dp.DistributionPoint.FullName {
1457 if fullName.Tag == 6 {
1458 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(fullName.Bytes))
1464 // RFC 5280, 4.2.1.1
1466 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
1468 } else if len(rest) != 0 {
1469 return nil, errors.New("x509: trailing data after X.509 authority key-id")
1471 out.AuthorityKeyId = a.Id
1474 // RFC 5280, 4.2.1.12. Extended Key Usage
1476 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1478 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1480 // KeyPurposeId ::= OBJECT IDENTIFIER
1482 var keyUsage []asn1.ObjectIdentifier
1483 if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
1485 } else if len(rest) != 0 {
1486 return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
1489 for _, u := range keyUsage {
1490 if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1491 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1493 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1498 // RFC 5280, 4.2.1.2
1500 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
1502 } else if len(rest) != 0 {
1503 return nil, errors.New("x509: trailing data after X.509 key-id")
1505 out.SubjectKeyId = keyid
1508 // RFC 5280 4.2.1.4: Certificate Policies
1509 var policies []policyInformation
1510 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
1512 } else if len(rest) != 0 {
1513 return nil, errors.New("x509: trailing data after X.509 certificate policies")
1515 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1516 for i, policy := range policies {
1517 out.PolicyIdentifiers[i] = policy.Policy
1521 // Unknown extensions are recorded if critical.
1524 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
1525 // RFC 5280 4.2.2.1: Authority Information Access
1526 var aia []authorityInfoAccess
1527 if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
1529 } else if len(rest) != 0 {
1530 return nil, errors.New("x509: trailing data after X.509 authority information")
1533 for _, v := range aia {
1534 // GeneralName: uniformResourceIdentifier [6] IA5String
1535 if v.Location.Tag != 6 {
1538 if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
1539 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
1540 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
1541 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
1545 // Unknown extensions are recorded if critical.
1549 if e.Critical && unhandled {
1550 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
1557 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1558 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
1559 var cert certificate
1560 rest, err := asn1.Unmarshal(asn1Data, &cert)
1565 return nil, asn1.SyntaxError{Msg: "trailing data"}
1568 return parseCertificate(&cert)
1571 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1572 // data. The certificates must be concatenated with no intermediate padding.
1573 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
1574 var v []*certificate
1576 for len(asn1Data) > 0 {
1577 cert := new(certificate)
1579 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
1586 ret := make([]*Certificate, len(v))
1587 for i, ci := range v {
1588 cert, err := parseCertificate(ci)
1598 func reverseBitsInAByte(in byte) byte {
1600 b2 := b1>>2&0x33 | b1<<2&0xcc
1601 b3 := b2>>1&0x55 | b2<<1&0xaa
1605 // asn1BitLength returns the bit-length of bitString by considering the
1606 // most-significant bit in a byte to be the "first" bit. This convention
1607 // matches ASN.1, but differs from almost everything else.
1608 func asn1BitLength(bitString []byte) int {
1609 bitLen := len(bitString) * 8
1611 for i := range bitString {
1612 b := bitString[len(bitString)-i-1]
1614 for bit := uint(0); bit < 8; bit++ {
1615 if (b>>bit)&1 == 1 {
1626 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1627 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1628 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1629 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1630 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1631 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1632 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1633 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1634 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1635 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1636 oidExtensionCRLNumber = []int{2, 5, 29, 20}
1640 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1641 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1644 // oidNotInExtensions reports whether an extension with the given oid exists in
1646 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1647 for _, e := range extensions {
1648 if e.Id.Equal(oid) {
1655 // marshalSANs marshals a list of addresses into a the contents of an X.509
1656 // SubjectAlternativeName extension.
1657 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
1658 var rawValues []asn1.RawValue
1659 for _, name := range dnsNames {
1660 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
1662 for _, email := range emailAddresses {
1663 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
1665 for _, rawIP := range ipAddresses {
1666 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1671 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
1673 for _, uri := range uris {
1674 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uri.String())})
1676 return asn1.Marshal(rawValues)
1679 func isIA5String(s string) error {
1680 for _, r := range s {
1681 if r >= utf8.RuneSelf {
1682 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1689 func buildExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte) (ret []pkix.Extension, err error) {
1690 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1693 if template.KeyUsage != 0 &&
1694 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1695 ret[n].Id = oidExtensionKeyUsage
1696 ret[n].Critical = true
1699 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1700 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1708 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1715 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1716 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1717 ret[n].Id = oidExtensionExtendedKeyUsage
1719 var oids []asn1.ObjectIdentifier
1720 for _, u := range template.ExtKeyUsage {
1721 if oid, ok := oidFromExtKeyUsage(u); ok {
1722 oids = append(oids, oid)
1724 panic("internal error")
1728 oids = append(oids, template.UnknownExtKeyUsage...)
1730 ret[n].Value, err = asn1.Marshal(oids)
1737 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1738 // Leaving MaxPathLen as zero indicates that no maximum path
1739 // length is desired, unless MaxPathLenZero is set. A value of
1740 // -1 causes encoding/asn1 to omit the value as desired.
1741 maxPathLen := template.MaxPathLen
1742 if maxPathLen == 0 && !template.MaxPathLenZero {
1745 ret[n].Id = oidExtensionBasicConstraints
1746 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
1747 ret[n].Critical = true
1754 if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1755 ret[n].Id = oidExtensionSubjectKeyId
1756 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
1763 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1764 ret[n].Id = oidExtensionAuthorityKeyId
1765 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1772 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1773 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1774 ret[n].Id = oidExtensionAuthorityInfoAccess
1775 var aiaValues []authorityInfoAccess
1776 for _, name := range template.OCSPServer {
1777 aiaValues = append(aiaValues, authorityInfoAccess{
1778 Method: oidAuthorityInfoAccessOcsp,
1779 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1782 for _, name := range template.IssuingCertificateURL {
1783 aiaValues = append(aiaValues, authorityInfoAccess{
1784 Method: oidAuthorityInfoAccessIssuers,
1785 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1788 ret[n].Value, err = asn1.Marshal(aiaValues)
1795 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1796 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1797 ret[n].Id = oidExtensionSubjectAltName
1798 // From RFC 5280, Section 4.2.1.6:
1799 // “If the subject field contains an empty sequence ... then
1800 // subjectAltName extension ... is marked as critical”
1801 ret[n].Critical = subjectIsEmpty
1802 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1809 if len(template.PolicyIdentifiers) > 0 &&
1810 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1811 ret[n].Id = oidExtensionCertificatePolicies
1812 policies := make([]policyInformation, len(template.PolicyIdentifiers))
1813 for i, policy := range template.PolicyIdentifiers {
1814 policies[i].Policy = policy
1816 ret[n].Value, err = asn1.Marshal(policies)
1823 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1824 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1825 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1826 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1827 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1828 ret[n].Id = oidExtensionNameConstraints
1829 ret[n].Critical = template.PermittedDNSDomainsCritical
1831 ipAndMask := func(ipNet *net.IPNet) []byte {
1832 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1833 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1834 ipAndMask = append(ipAndMask, maskedIP...)
1835 ipAndMask = append(ipAndMask, ipNet.Mask...)
1839 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1840 var b cryptobyte.Builder
1842 for _, name := range dns {
1843 if err = isIA5String(name); err != nil {
1847 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1848 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1849 b.AddBytes([]byte(name))
1854 for _, ipNet := range ips {
1855 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1856 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1857 b.AddBytes(ipAndMask(ipNet))
1862 for _, email := range emails {
1863 if err = isIA5String(email); err != nil {
1867 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1868 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1869 b.AddBytes([]byte(email))
1874 for _, uriDomain := range uriDomains {
1875 if err = isIA5String(uriDomain); err != nil {
1879 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1880 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1881 b.AddBytes([]byte(uriDomain))
1889 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1894 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1899 var b cryptobyte.Builder
1900 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1901 if len(permitted) > 0 {
1902 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1903 b.AddBytes(permitted)
1907 if len(excluded) > 0 {
1908 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1909 b.AddBytes(excluded)
1914 ret[n].Value, err = b.Bytes()
1921 if len(template.CRLDistributionPoints) > 0 &&
1922 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1923 ret[n].Id = oidExtensionCRLDistributionPoints
1925 var crlDp []distributionPoint
1926 for _, name := range template.CRLDistributionPoints {
1927 dp := distributionPoint{
1928 DistributionPoint: distributionPointName{
1929 FullName: []asn1.RawValue{
1930 {Tag: 6, Class: 2, Bytes: []byte(name)},
1934 crlDp = append(crlDp, dp)
1937 ret[n].Value, err = asn1.Marshal(crlDp)
1944 // Adding another extension here? Remember to update the maximum number
1945 // of elements in the make() at the top of the function and the list of
1946 // template fields used in CreateCertificate documentation.
1948 return append(ret[:n], template.ExtraExtensions...), nil
1951 func subjectBytes(cert *Certificate) ([]byte, error) {
1952 if len(cert.RawSubject) > 0 {
1953 return cert.RawSubject, nil
1956 return asn1.Marshal(cert.Subject.ToRDNSequence())
1959 // signingParamsForPublicKey returns the parameters to use for signing with
1960 // priv. If requestedSigAlgo is not zero then it overrides the default
1961 // signature algorithm.
1962 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1963 var pubType PublicKeyAlgorithm
1965 switch pub := pub.(type) {
1966 case *rsa.PublicKey:
1968 hashFunc = crypto.SHA256
1969 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1970 sigAlgo.Parameters = asn1.NullRawValue
1972 case *ecdsa.PublicKey:
1976 case elliptic.P224(), elliptic.P256():
1977 hashFunc = crypto.SHA256
1978 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1979 case elliptic.P384():
1980 hashFunc = crypto.SHA384
1981 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1982 case elliptic.P521():
1983 hashFunc = crypto.SHA512
1984 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1986 err = errors.New("x509: unknown elliptic curve")
1989 case ed25519.PublicKey:
1991 sigAlgo.Algorithm = oidSignatureEd25519
1994 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
2001 if requestedSigAlgo == 0 {
2006 for _, details := range signatureAlgorithmDetails {
2007 if details.algo == requestedSigAlgo {
2008 if details.pubKeyAlgo != pubType {
2009 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
2012 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
2013 if hashFunc == 0 && pubType != Ed25519 {
2014 err = errors.New("x509: cannot sign with hash function requested")
2017 if requestedSigAlgo.isRSAPSS() {
2018 sigAlgo.Parameters = rsaPSSParameters(hashFunc)
2026 err = errors.New("x509: unknown SignatureAlgorithm")
2032 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
2033 // just an empty SEQUENCE.
2034 var emptyASN1Subject = []byte{0x30, 0}
2036 // CreateCertificate creates a new X.509v3 certificate based on a template.
2037 // The following members of template are used:
2040 // - BasicConstraintsValid
2041 // - CRLDistributionPoints
2044 // - ExcludedDNSDomains
2045 // - ExcludedEmailAddresses
2046 // - ExcludedIPRanges
2047 // - ExcludedURIDomains
2049 // - ExtraExtensions
2052 // - IssuingCertificateURL
2059 // - PermittedDNSDomains
2060 // - PermittedDNSDomainsCritical
2061 // - PermittedEmailAddresses
2062 // - PermittedIPRanges
2063 // - PermittedURIDomains
2064 // - PolicyIdentifiers
2066 // - SignatureAlgorithm
2070 // - UnknownExtKeyUsage
2072 // The certificate is signed by parent. If parent is equal to template then the
2073 // certificate is self-signed. The parameter pub is the public key of the
2074 // signee and priv is the private key of the signer.
2076 // The returned slice is the certificate in DER encoding.
2078 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
2079 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
2080 // crypto.Signer with a supported public key.
2082 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
2083 // unless the resulting certificate is self-signed. Otherwise the value from
2084 // template will be used.
2085 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
2086 key, ok := priv.(crypto.Signer)
2088 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2091 if template.SerialNumber == nil {
2092 return nil, errors.New("x509: no SerialNumber given")
2095 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2100 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
2105 asn1Issuer, err := subjectBytes(parent)
2110 asn1Subject, err := subjectBytes(template)
2115 authorityKeyId := template.AuthorityKeyId
2116 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
2117 authorityKeyId = parent.SubjectKeyId
2120 extensions, err := buildExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId)
2125 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
2126 c := tbsCertificate{
2128 SerialNumber: template.SerialNumber,
2129 SignatureAlgorithm: signatureAlgorithm,
2130 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
2131 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
2132 Subject: asn1.RawValue{FullBytes: asn1Subject},
2133 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
2134 Extensions: extensions,
2137 tbsCertContents, err := asn1.Marshal(c)
2141 c.Raw = tbsCertContents
2143 signed := tbsCertContents
2150 var signerOpts crypto.SignerOpts = hashFunc
2151 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
2152 signerOpts = &rsa.PSSOptions{
2153 SaltLength: rsa.PSSSaltLengthEqualsHash,
2158 var signature []byte
2159 signature, err = key.Sign(rand, signed, signerOpts)
2164 return asn1.Marshal(certificate{
2168 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2172 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
2174 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
2176 // pemType is the type of a PEM encoded CRL.
2177 var pemType = "X509 CRL"
2179 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
2180 // encoded CRLs will appear where they should be DER encoded, so this function
2181 // will transparently handle PEM encoding as long as there isn't any leading
2183 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
2184 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
2185 block, _ := pem.Decode(crlBytes)
2186 if block != nil && block.Type == pemType {
2187 crlBytes = block.Bytes
2190 return ParseDERCRL(crlBytes)
2193 // ParseDERCRL parses a DER encoded CRL from the given bytes.
2194 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
2195 certList := new(pkix.CertificateList)
2196 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
2198 } else if len(rest) != 0 {
2199 return nil, errors.New("x509: trailing data after CRL")
2201 return certList, nil
2204 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
2205 // contains the given list of revoked certificates.
2207 // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
2208 // To generate a standards compliant CRL, use CreateRevocationList instead.
2209 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
2210 key, ok := priv.(crypto.Signer)
2212 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2215 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
2220 // Force revocation times to UTC per RFC 5280.
2221 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
2222 for i, rc := range revokedCerts {
2223 rc.RevocationTime = rc.RevocationTime.UTC()
2224 revokedCertsUTC[i] = rc
2227 tbsCertList := pkix.TBSCertificateList{
2229 Signature: signatureAlgorithm,
2230 Issuer: c.Subject.ToRDNSequence(),
2231 ThisUpdate: now.UTC(),
2232 NextUpdate: expiry.UTC(),
2233 RevokedCertificates: revokedCertsUTC,
2237 if len(c.SubjectKeyId) > 0 {
2238 var aki pkix.Extension
2239 aki.Id = oidExtensionAuthorityKeyId
2240 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
2244 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
2247 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2252 signed := tbsCertListContents
2259 var signature []byte
2260 signature, err = key.Sign(rand, signed, hashFunc)
2265 return asn1.Marshal(pkix.CertificateList{
2266 TBSCertList: tbsCertList,
2267 SignatureAlgorithm: signatureAlgorithm,
2268 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2272 // CertificateRequest represents a PKCS #10, certificate signature request.
2273 type CertificateRequest struct {
2274 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
2275 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
2276 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
2277 RawSubject []byte // DER encoded Subject.
2281 SignatureAlgorithm SignatureAlgorithm
2283 PublicKeyAlgorithm PublicKeyAlgorithm
2284 PublicKey interface{}
2288 // Attributes contains the CSR attributes that can parse as
2289 // pkix.AttributeTypeAndValueSET.
2291 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
2292 // generating the requestedExtensions attribute.
2293 Attributes []pkix.AttributeTypeAndValueSET
2295 // Extensions contains all requested extensions, in raw form. When parsing
2296 // CSRs, this can be used to extract extensions that are not parsed by this
2298 Extensions []pkix.Extension
2300 // ExtraExtensions contains extensions to be copied, raw, into any CSR
2301 // marshaled by CreateCertificateRequest. Values override any extensions
2302 // that would otherwise be produced based on the other fields but are
2303 // overridden by any extensions specified in Attributes.
2305 // The ExtraExtensions field is not populated by ParseCertificateRequest,
2306 // see Extensions instead.
2307 ExtraExtensions []pkix.Extension
2309 // Subject Alternate Name values.
2311 EmailAddresses []string
2312 IPAddresses []net.IP
2316 // These structures reflect the ASN.1 structure of X.509 certificate
2317 // signature requests (see RFC 2986):
2319 type tbsCertificateRequest struct {
2322 Subject asn1.RawValue
2323 PublicKey publicKeyInfo
2324 RawAttributes []asn1.RawValue `asn1:"tag:0"`
2327 type certificateRequest struct {
2329 TBSCSR tbsCertificateRequest
2330 SignatureAlgorithm pkix.AlgorithmIdentifier
2331 SignatureValue asn1.BitString
2334 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
2335 // extensions in a CSR.
2336 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2338 // newRawAttributes converts AttributeTypeAndValueSETs from a template
2339 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
2340 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2341 var rawAttributes []asn1.RawValue
2342 b, err := asn1.Marshal(attributes)
2346 rest, err := asn1.Unmarshal(b, &rawAttributes)
2351 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2353 return rawAttributes, nil
2356 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
2357 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2358 var attributes []pkix.AttributeTypeAndValueSET
2359 for _, rawAttr := range rawAttributes {
2360 var attr pkix.AttributeTypeAndValueSET
2361 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2362 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2363 // (i.e.: challengePassword or unstructuredName).
2364 if err == nil && len(rest) == 0 {
2365 attributes = append(attributes, attr)
2371 // parseCSRExtensions parses the attributes from a CSR and extracts any
2372 // requested extensions.
2373 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2374 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
2375 type pkcs10Attribute struct {
2376 Id asn1.ObjectIdentifier
2377 Values []asn1.RawValue `asn1:"set"`
2380 var ret []pkix.Extension
2381 for _, rawAttr := range rawAttributes {
2382 var attr pkcs10Attribute
2383 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2384 // Ignore attributes that don't parse.
2388 if !attr.Id.Equal(oidExtensionRequest) {
2392 var extensions []pkix.Extension
2393 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2396 ret = append(ret, extensions...)
2402 // CreateCertificateRequest creates a new certificate request based on a
2403 // template. The following members of template are used:
2405 // - SignatureAlgorithm
2411 // - ExtraExtensions
2412 // - Attributes (deprecated)
2414 // priv is the private key to sign the CSR with, and the corresponding public
2415 // key will be included in the CSR. It must implement crypto.Signer and its
2416 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
2417 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
2418 // ed25519.PrivateKey satisfies this.)
2420 // The returned slice is the certificate request in DER encoding.
2421 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
2422 key, ok := priv.(crypto.Signer)
2424 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2427 var hashFunc crypto.Hash
2428 var sigAlgo pkix.AlgorithmIdentifier
2429 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2434 var publicKeyBytes []byte
2435 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2436 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2441 var extensions []pkix.Extension
2443 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
2444 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
2445 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
2450 extensions = append(extensions, pkix.Extension{
2451 Id: oidExtensionSubjectAltName,
2456 extensions = append(extensions, template.ExtraExtensions...)
2458 // Make a copy of template.Attributes because we may alter it below.
2459 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
2460 for _, attr := range template.Attributes {
2461 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
2462 copy(values, attr.Value)
2463 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2469 extensionsAppended := false
2470 if len(extensions) > 0 {
2471 // Append the extensions to an existing attribute if possible.
2472 for _, atvSet := range attributes {
2473 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2477 // specifiedExtensions contains all the extensions that we
2478 // found specified via template.Attributes.
2479 specifiedExtensions := make(map[string]bool)
2481 for _, atvs := range atvSet.Value {
2482 for _, atv := range atvs {
2483 specifiedExtensions[atv.Type.String()] = true
2487 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
2488 newValue = append(newValue, atvSet.Value[0]...)
2490 for _, e := range extensions {
2491 if specifiedExtensions[e.Id.String()] {
2492 // Attributes already contained a value for
2493 // this extension and it takes priority.
2497 newValue = append(newValue, pkix.AttributeTypeAndValue{
2498 // There is no place for the critical
2499 // flag in an AttributeTypeAndValue.
2505 atvSet.Value[0] = newValue
2506 extensionsAppended = true
2511 rawAttributes, err := newRawAttributes(attributes)
2516 // If not included in attributes, add a new attribute for the
2518 if len(extensions) > 0 && !extensionsAppended {
2520 Type asn1.ObjectIdentifier
2521 Value [][]pkix.Extension `asn1:"set"`
2523 Type: oidExtensionRequest,
2524 Value: [][]pkix.Extension{extensions},
2527 b, err := asn1.Marshal(attr)
2529 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
2532 var rawValue asn1.RawValue
2533 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
2537 rawAttributes = append(rawAttributes, rawValue)
2540 asn1Subject := template.RawSubject
2541 if len(asn1Subject) == 0 {
2542 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2548 tbsCSR := tbsCertificateRequest{
2549 Version: 0, // PKCS #10, RFC 2986
2550 Subject: asn1.RawValue{FullBytes: asn1Subject},
2551 PublicKey: publicKeyInfo{
2552 Algorithm: publicKeyAlgorithm,
2553 PublicKey: asn1.BitString{
2554 Bytes: publicKeyBytes,
2555 BitLength: len(publicKeyBytes) * 8,
2558 RawAttributes: rawAttributes,
2561 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2565 tbsCSR.Raw = tbsCSRContents
2567 signed := tbsCSRContents
2574 var signature []byte
2575 signature, err = key.Sign(rand, signed, hashFunc)
2580 return asn1.Marshal(certificateRequest{
2582 SignatureAlgorithm: sigAlgo,
2583 SignatureValue: asn1.BitString{
2585 BitLength: len(signature) * 8,
2590 // ParseCertificateRequest parses a single certificate request from the
2591 // given ASN.1 DER data.
2592 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2593 var csr certificateRequest
2595 rest, err := asn1.Unmarshal(asn1Data, &csr)
2598 } else if len(rest) != 0 {
2599 return nil, asn1.SyntaxError{Msg: "trailing data"}
2602 return parseCertificateRequest(&csr)
2605 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2606 out := &CertificateRequest{
2608 RawTBSCertificateRequest: in.TBSCSR.Raw,
2609 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2610 RawSubject: in.TBSCSR.Subject.FullBytes,
2612 Signature: in.SignatureValue.RightAlign(),
2613 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2615 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2617 Version: in.TBSCSR.Version,
2618 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2622 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2627 var subject pkix.RDNSequence
2628 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2630 } else if len(rest) != 0 {
2631 return nil, errors.New("x509: trailing data after X.509 Subject")
2634 out.Subject.FillFromRDNSequence(&subject)
2636 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2640 for _, extension := range out.Extensions {
2641 if extension.Id.Equal(oidExtensionSubjectAltName) {
2642 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2652 // CheckSignature reports whether the signature on c is valid.
2653 func (c *CertificateRequest) CheckSignature() error {
2654 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
2657 // RevocationList contains the fields used to create an X.509 v2 Certificate
2658 // Revocation list with CreateRevocationList.
2659 type RevocationList struct {
2660 // SignatureAlgorithm is used to determine the signature algorithm to be
2661 // used when signing the CRL. If 0 the default algorithm for the signing
2662 // key will be used.
2663 SignatureAlgorithm SignatureAlgorithm
2665 // RevokedCertificates is used to populate the revokedCertificates
2666 // sequence in the CRL, it may be empty. RevokedCertificates may be nil,
2667 // in which case an empty CRL will be created.
2668 RevokedCertificates []pkix.RevokedCertificate
2670 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2671 // which should be a monotonically increasing sequence number for a given
2672 // CRL scope and CRL issuer.
2674 // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2675 // indicates the issuance date of the CRL.
2676 ThisUpdate time.Time
2677 // NextUpdate is used to populate the nextUpdate field in the CRL, which
2678 // indicates the date by which the next CRL will be issued. NextUpdate
2679 // must be greater than ThisUpdate.
2680 NextUpdate time.Time
2681 // ExtraExtensions contains any additional extensions to add directly to
2683 ExtraExtensions []pkix.Extension
2686 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
2687 // according to RFC 5280, based on template.
2689 // The CRL is signed by priv which should be the private key associated with
2690 // the public key in the issuer certificate.
2692 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
2693 // order to use it as a CRL issuer.
2695 // The issuer distinguished name CRL field and authority key identifier
2696 // extension are populated using the issuer certificate. issuer must have
2697 // SubjectKeyId set.
2698 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2699 if template == nil {
2700 return nil, errors.New("x509: template can not be nil")
2703 return nil, errors.New("x509: issuer can not be nil")
2705 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2706 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2708 if len(issuer.SubjectKeyId) == 0 {
2709 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2711 if template.NextUpdate.Before(template.ThisUpdate) {
2712 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2714 if template.Number == nil {
2715 return nil, errors.New("x509: template contains nil Number field")
2718 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2723 // Force revocation times to UTC per RFC 5280.
2724 revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2725 for i, rc := range template.RevokedCertificates {
2726 rc.RevocationTime = rc.RevocationTime.UTC()
2727 revokedCertsUTC[i] = rc
2730 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2734 crlNum, err := asn1.Marshal(template.Number)
2739 tbsCertList := pkix.TBSCertificateList{
2741 Signature: signatureAlgorithm,
2742 Issuer: issuer.Subject.ToRDNSequence(),
2743 ThisUpdate: template.ThisUpdate.UTC(),
2744 NextUpdate: template.NextUpdate.UTC(),
2745 Extensions: []pkix.Extension{
2747 Id: oidExtensionAuthorityKeyId,
2751 Id: oidExtensionCRLNumber,
2756 if len(revokedCertsUTC) > 0 {
2757 tbsCertList.RevokedCertificates = revokedCertsUTC
2760 if len(template.ExtraExtensions) > 0 {
2761 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2764 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2769 input := tbsCertListContents
2772 h.Write(tbsCertListContents)
2775 var signerOpts crypto.SignerOpts = hashFunc
2776 if template.SignatureAlgorithm.isRSAPSS() {
2777 signerOpts = &rsa.PSSOptions{
2778 SaltLength: rsa.PSSSaltLengthEqualsHash,
2783 signature, err := priv.Sign(rand, input, signerOpts)
2788 return asn1.Marshal(pkix.CertificateList{
2789 TBSCertList: tbsCertList,
2790 SignatureAlgorithm: signatureAlgorithm,
2791 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},