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.
29 // Explicitly import these for their crypto.RegisterHash init side-effects.
30 // Keep these as blank imports, even if they're imported above.
35 "golang.org/x/crypto/cryptobyte"
36 cryptobyte_asn1 "golang.org/x/crypto/cryptobyte/asn1"
39 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
41 type pkixPublicKey struct {
42 Algo pkix.AlgorithmIdentifier
43 BitString asn1.BitString
46 // ParsePKIXPublicKey parses a public key in PKIX, ASN.1 DER form.
47 // The encoded public key is a SubjectPublicKeyInfo structure
48 // (see RFC 5280, Section 4.1).
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.
109 // The encoded public key is a SubjectPublicKeyInfo structure
110 // (see RFC 5280, Section 4.1).
112 // The following key types are currently supported: *rsa.PublicKey, *ecdsa.PublicKey
113 // and ed25519.PublicKey. Unsupported key types result in an error.
115 // This kind of key is commonly encoded in PEM blocks of type "PUBLIC KEY".
116 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
117 var publicKeyBytes []byte
118 var publicKeyAlgorithm pkix.AlgorithmIdentifier
121 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
125 pkix := pkixPublicKey{
126 Algo: publicKeyAlgorithm,
127 BitString: asn1.BitString{
128 Bytes: publicKeyBytes,
129 BitLength: 8 * len(publicKeyBytes),
133 ret, _ := asn1.Marshal(pkix)
137 // These structures reflect the ASN.1 structure of X.509 certificates.:
139 type certificate struct {
141 TBSCertificate tbsCertificate
142 SignatureAlgorithm pkix.AlgorithmIdentifier
143 SignatureValue asn1.BitString
146 type tbsCertificate struct {
148 Version int `asn1:"optional,explicit,default:0,tag:0"`
149 SerialNumber *big.Int
150 SignatureAlgorithm pkix.AlgorithmIdentifier
153 Subject asn1.RawValue
154 PublicKey publicKeyInfo
155 UniqueId asn1.BitString `asn1:"optional,tag:1"`
156 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
157 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
160 type dsaAlgorithmParameters struct {
164 type validity struct {
165 NotBefore, NotAfter time.Time
168 type publicKeyInfo struct {
170 Algorithm pkix.AlgorithmIdentifier
171 PublicKey asn1.BitString
175 type authKeyId struct {
176 Id []byte `asn1:"optional,tag:0"`
179 type SignatureAlgorithm int
182 UnknownSignatureAlgorithm SignatureAlgorithm = iota
184 MD2WithRSA // Unsupported.
185 MD5WithRSA // Only supported for signing, not verification.
190 DSAWithSHA1 // Unsupported.
191 DSAWithSHA256 // Unsupported.
202 func (algo SignatureAlgorithm) isRSAPSS() bool {
204 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
211 func (algo SignatureAlgorithm) String() string {
212 for _, details := range signatureAlgorithmDetails {
213 if details.algo == algo {
217 return strconv.Itoa(int(algo))
220 type PublicKeyAlgorithm int
223 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
230 var publicKeyAlgoName = [...]string{
237 func (algo PublicKeyAlgorithm) String() string {
238 if 0 < algo && int(algo) < len(publicKeyAlgoName) {
239 return publicKeyAlgoName[algo]
241 return strconv.Itoa(int(algo))
244 // OIDs for signature algorithms
246 // pkcs-1 OBJECT IDENTIFIER ::= {
247 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
250 // RFC 3279 2.2.1 RSA Signature Algorithms
252 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
254 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
256 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
258 // dsaWithSha1 OBJECT IDENTIFIER ::= {
259 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
261 // RFC 3279 2.2.3 ECDSA Signature Algorithm
263 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
264 // iso(1) member-body(2) us(840) ansi-x962(10045)
265 // signatures(4) ecdsa-with-SHA1(1)}
268 // RFC 4055 5 PKCS #1 Version 1.5
270 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
272 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
274 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
277 // RFC 5758 3.1 DSA Signature Algorithms
279 // dsaWithSha256 OBJECT IDENTIFIER ::= {
280 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
281 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
283 // RFC 5758 3.2 ECDSA Signature Algorithm
285 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
286 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
288 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
289 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
291 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
292 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
295 // RFC 8410 3 Curve25519 and Curve448 Algorithm Identifiers
297 // id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 }
300 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
301 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
302 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
303 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
304 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
305 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
306 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
307 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
308 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
309 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
310 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
311 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
312 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
313 oidSignatureEd25519 = asn1.ObjectIdentifier{1, 3, 101, 112}
315 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
316 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
317 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
319 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
321 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
322 // but it's specified by ISO. Microsoft's makecert.exe has been known
323 // to produce certificates with this OID.
324 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
327 var signatureAlgorithmDetails = []struct {
328 algo SignatureAlgorithm
330 oid asn1.ObjectIdentifier
331 pubKeyAlgo PublicKeyAlgorithm
334 {MD2WithRSA, "MD2-RSA", oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */},
335 {MD5WithRSA, "MD5-RSA", oidSignatureMD5WithRSA, RSA, crypto.MD5},
336 {SHA1WithRSA, "SHA1-RSA", oidSignatureSHA1WithRSA, RSA, crypto.SHA1},
337 {SHA1WithRSA, "SHA1-RSA", oidISOSignatureSHA1WithRSA, RSA, crypto.SHA1},
338 {SHA256WithRSA, "SHA256-RSA", oidSignatureSHA256WithRSA, RSA, crypto.SHA256},
339 {SHA384WithRSA, "SHA384-RSA", oidSignatureSHA384WithRSA, RSA, crypto.SHA384},
340 {SHA512WithRSA, "SHA512-RSA", oidSignatureSHA512WithRSA, RSA, crypto.SHA512},
341 {SHA256WithRSAPSS, "SHA256-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA256},
342 {SHA384WithRSAPSS, "SHA384-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA384},
343 {SHA512WithRSAPSS, "SHA512-RSAPSS", oidSignatureRSAPSS, RSA, crypto.SHA512},
344 {DSAWithSHA1, "DSA-SHA1", oidSignatureDSAWithSHA1, DSA, crypto.SHA1},
345 {DSAWithSHA256, "DSA-SHA256", oidSignatureDSAWithSHA256, DSA, crypto.SHA256},
346 {ECDSAWithSHA1, "ECDSA-SHA1", oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1},
347 {ECDSAWithSHA256, "ECDSA-SHA256", oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256},
348 {ECDSAWithSHA384, "ECDSA-SHA384", oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384},
349 {ECDSAWithSHA512, "ECDSA-SHA512", oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512},
350 {PureEd25519, "Ed25519", oidSignatureEd25519, Ed25519, crypto.Hash(0) /* no pre-hashing */},
353 // hashToPSSParameters contains the DER encoded RSA PSS parameters for the
354 // SHA256, SHA384, and SHA512 hashes as defined in RFC 3447, Appendix A.2.3.
355 // The parameters contain the following values:
356 // * hashAlgorithm contains the associated hash identifier with NULL parameters
357 // * maskGenAlgorithm always contains the default mgf1SHA1 identifier
358 // * saltLength contains the length of the associated hash
359 // * trailerField always contains the default trailerFieldBC value
360 var hashToPSSParameters = map[crypto.Hash]asn1.RawValue{
361 crypto.SHA256: asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 1, 5, 0, 162, 3, 2, 1, 32}},
362 crypto.SHA384: asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 2, 5, 0, 162, 3, 2, 1, 48}},
363 crypto.SHA512: asn1.RawValue{FullBytes: []byte{48, 52, 160, 15, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 161, 28, 48, 26, 6, 9, 42, 134, 72, 134, 247, 13, 1, 1, 8, 48, 13, 6, 9, 96, 134, 72, 1, 101, 3, 4, 2, 3, 5, 0, 162, 3, 2, 1, 64}},
366 // pssParameters reflects the parameters in an AlgorithmIdentifier that
367 // specifies RSA PSS. See RFC 3447, Appendix A.2.3.
368 type pssParameters struct {
369 // The following three fields are not marked as
370 // optional because the default values specify SHA-1,
371 // which is no longer suitable for use in signatures.
372 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
373 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
374 SaltLength int `asn1:"explicit,tag:2"`
375 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
378 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
379 if ai.Algorithm.Equal(oidSignatureEd25519) {
380 // RFC 8410, Section 3
381 // > For all of the OIDs, the parameters MUST be absent.
382 if len(ai.Parameters.FullBytes) != 0 {
383 return UnknownSignatureAlgorithm
387 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
388 for _, details := range signatureAlgorithmDetails {
389 if ai.Algorithm.Equal(details.oid) {
393 return UnknownSignatureAlgorithm
396 // RSA PSS is special because it encodes important parameters
397 // in the Parameters.
399 var params pssParameters
400 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
401 return UnknownSignatureAlgorithm
404 var mgf1HashFunc pkix.AlgorithmIdentifier
405 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
406 return UnknownSignatureAlgorithm
409 // PSS is greatly overburdened with options. This code forces them into
410 // three buckets by requiring that the MGF1 hash function always match the
411 // message hash function (as recommended in RFC 3447, Section 8.1), that the
412 // salt length matches the hash length, and that the trailer field has the
414 if (len(params.Hash.Parameters.FullBytes) != 0 && !bytes.Equal(params.Hash.Parameters.FullBytes, asn1.NullBytes)) ||
415 !params.MGF.Algorithm.Equal(oidMGF1) ||
416 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
417 (len(mgf1HashFunc.Parameters.FullBytes) != 0 && !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1.NullBytes)) ||
418 params.TrailerField != 1 {
419 return UnknownSignatureAlgorithm
423 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
424 return SHA256WithRSAPSS
425 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
426 return SHA384WithRSAPSS
427 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
428 return SHA512WithRSAPSS
431 return UnknownSignatureAlgorithm
434 // RFC 3279, 2.3 Public Key Algorithms
436 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
437 // rsadsi(113549) pkcs(1) 1 }
439 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
441 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
442 // x9-57(10040) x9cm(4) 1 }
444 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
446 // id-ecPublicKey OBJECT IDENTIFIER ::= {
447 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
449 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
450 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
451 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
452 oidPublicKeyEd25519 = oidSignatureEd25519
455 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
457 case oid.Equal(oidPublicKeyRSA):
459 case oid.Equal(oidPublicKeyDSA):
461 case oid.Equal(oidPublicKeyECDSA):
463 case oid.Equal(oidPublicKeyEd25519):
466 return UnknownPublicKeyAlgorithm
469 // RFC 5480, 2.1.1.1. Named Curve
471 // secp224r1 OBJECT IDENTIFIER ::= {
472 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
474 // secp256r1 OBJECT IDENTIFIER ::= {
475 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
478 // secp384r1 OBJECT IDENTIFIER ::= {
479 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
481 // secp521r1 OBJECT IDENTIFIER ::= {
482 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
484 // NB: secp256r1 is equivalent to prime256v1
486 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
487 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
488 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
489 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
492 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
494 case oid.Equal(oidNamedCurveP224):
495 return elliptic.P224()
496 case oid.Equal(oidNamedCurveP256):
497 return elliptic.P256()
498 case oid.Equal(oidNamedCurveP384):
499 return elliptic.P384()
500 case oid.Equal(oidNamedCurveP521):
501 return elliptic.P521()
506 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
508 case elliptic.P224():
509 return oidNamedCurveP224, true
510 case elliptic.P256():
511 return oidNamedCurveP256, true
512 case elliptic.P384():
513 return oidNamedCurveP384, true
514 case elliptic.P521():
515 return oidNamedCurveP521, true
521 // KeyUsage represents the set of actions that are valid for a given key. It's
522 // a bitmap of the KeyUsage* constants.
526 KeyUsageDigitalSignature KeyUsage = 1 << iota
527 KeyUsageContentCommitment
528 KeyUsageKeyEncipherment
529 KeyUsageDataEncipherment
537 // RFC 5280, 4.2.1.12 Extended Key Usage
539 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
541 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
543 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
544 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
545 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
546 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
547 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
548 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
550 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
551 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
552 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
553 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
554 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
555 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
556 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
557 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
558 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
559 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
560 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
561 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
562 oidExtKeyUsageMicrosoftCommercialCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 2, 1, 22}
563 oidExtKeyUsageMicrosoftKernelCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 61, 1, 1}
566 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
567 // Each of the ExtKeyUsage* constants define a unique action.
571 ExtKeyUsageAny ExtKeyUsage = iota
572 ExtKeyUsageServerAuth
573 ExtKeyUsageClientAuth
574 ExtKeyUsageCodeSigning
575 ExtKeyUsageEmailProtection
576 ExtKeyUsageIPSECEndSystem
577 ExtKeyUsageIPSECTunnel
579 ExtKeyUsageTimeStamping
580 ExtKeyUsageOCSPSigning
581 ExtKeyUsageMicrosoftServerGatedCrypto
582 ExtKeyUsageNetscapeServerGatedCrypto
583 ExtKeyUsageMicrosoftCommercialCodeSigning
584 ExtKeyUsageMicrosoftKernelCodeSigning
587 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
588 var extKeyUsageOIDs = []struct {
589 extKeyUsage ExtKeyUsage
590 oid asn1.ObjectIdentifier
592 {ExtKeyUsageAny, oidExtKeyUsageAny},
593 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
594 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
595 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
596 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
597 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
598 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
599 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
600 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
601 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
602 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
603 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
604 {ExtKeyUsageMicrosoftCommercialCodeSigning, oidExtKeyUsageMicrosoftCommercialCodeSigning},
605 {ExtKeyUsageMicrosoftKernelCodeSigning, oidExtKeyUsageMicrosoftKernelCodeSigning},
608 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
609 for _, pair := range extKeyUsageOIDs {
610 if oid.Equal(pair.oid) {
611 return pair.extKeyUsage, true
617 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
618 for _, pair := range extKeyUsageOIDs {
619 if eku == pair.extKeyUsage {
620 return pair.oid, true
626 // A Certificate represents an X.509 certificate.
627 type Certificate struct {
628 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
629 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
630 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
631 RawSubject []byte // DER encoded Subject
632 RawIssuer []byte // DER encoded Issuer
635 SignatureAlgorithm SignatureAlgorithm
637 PublicKeyAlgorithm PublicKeyAlgorithm
638 PublicKey interface{}
641 SerialNumber *big.Int
644 NotBefore, NotAfter time.Time // Validity bounds.
647 // Extensions contains raw X.509 extensions. When parsing certificates,
648 // this can be used to extract non-critical extensions that are not
649 // parsed by this package. When marshaling certificates, the Extensions
650 // field is ignored, see ExtraExtensions.
651 Extensions []pkix.Extension
653 // ExtraExtensions contains extensions to be copied, raw, into any
654 // marshaled certificates. Values override any extensions that would
655 // otherwise be produced based on the other fields. The ExtraExtensions
656 // field is not populated when parsing certificates, see Extensions.
657 ExtraExtensions []pkix.Extension
659 // UnhandledCriticalExtensions contains a list of extension IDs that
660 // were not (fully) processed when parsing. Verify will fail if this
661 // slice is non-empty, unless verification is delegated to an OS
662 // library which understands all the critical extensions.
664 // Users can access these extensions using Extensions and can remove
665 // elements from this slice if they believe that they have been
667 UnhandledCriticalExtensions []asn1.ObjectIdentifier
669 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
670 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
672 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
673 // and MaxPathLenZero are valid.
674 BasicConstraintsValid bool
677 // MaxPathLen and MaxPathLenZero indicate the presence and
678 // value of the BasicConstraints' "pathLenConstraint".
680 // When parsing a certificate, a positive non-zero MaxPathLen
681 // means that the field was specified, -1 means it was unset,
682 // and MaxPathLenZero being true mean that the field was
683 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
684 // should be treated equivalent to -1 (unset).
686 // When generating a certificate, an unset pathLenConstraint
687 // can be requested with either MaxPathLen == -1 or using the
688 // zero value for both MaxPathLen and MaxPathLenZero.
690 // MaxPathLenZero indicates that BasicConstraintsValid==true
691 // and MaxPathLen==0 should be interpreted as an actual
692 // maximum path length of zero. Otherwise, that combination is
693 // interpreted as MaxPathLen not being set.
697 AuthorityKeyId []byte
699 // RFC 5280, 4.2.2.1 (Authority Information Access)
701 IssuingCertificateURL []string
703 // Subject Alternate Name values. (Note that these values may not be valid
704 // if invalid values were contained within a parsed certificate. For
705 // example, an element of DNSNames may not be a valid DNS domain name.)
707 EmailAddresses []string
712 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
713 PermittedDNSDomains []string
714 ExcludedDNSDomains []string
715 PermittedIPRanges []*net.IPNet
716 ExcludedIPRanges []*net.IPNet
717 PermittedEmailAddresses []string
718 ExcludedEmailAddresses []string
719 PermittedURIDomains []string
720 ExcludedURIDomains []string
722 // CRL Distribution Points
723 CRLDistributionPoints []string
725 PolicyIdentifiers []asn1.ObjectIdentifier
728 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
729 // involves algorithms that are not currently implemented.
730 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
732 // An InsecureAlgorithmError
733 type InsecureAlgorithmError SignatureAlgorithm
735 func (e InsecureAlgorithmError) Error() string {
736 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
739 // ConstraintViolationError results when a requested usage is not permitted by
740 // a certificate. For example: checking a signature when the public key isn't a
741 // certificate signing key.
742 type ConstraintViolationError struct{}
744 func (ConstraintViolationError) Error() string {
745 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
748 func (c *Certificate) Equal(other *Certificate) bool {
749 if c == nil || other == nil {
752 return bytes.Equal(c.Raw, other.Raw)
755 func (c *Certificate) hasSANExtension() bool {
756 return oidInExtensions(oidExtensionSubjectAltName, c.Extensions)
759 // CheckSignatureFrom verifies that the signature on c is a valid signature
761 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
762 // RFC 5280, 4.2.1.9:
763 // "If the basic constraints extension is not present in a version 3
764 // certificate, or the extension is present but the cA boolean is not
765 // asserted, then the certified public key MUST NOT be used to verify
766 // certificate signatures."
767 if parent.Version == 3 && !parent.BasicConstraintsValid ||
768 parent.BasicConstraintsValid && !parent.IsCA {
769 return ConstraintViolationError{}
772 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
773 return ConstraintViolationError{}
776 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
777 return ErrUnsupportedAlgorithm
780 // TODO(agl): don't ignore the path length constraint.
782 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
785 // CheckSignature verifies that signature is a valid signature over signed from
787 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
788 return checkSignature(algo, signed, signature, c.PublicKey)
791 func (c *Certificate) hasNameConstraints() bool {
792 return oidInExtensions(oidExtensionNameConstraints, c.Extensions)
795 func (c *Certificate) getSANExtension() []byte {
796 for _, e := range c.Extensions {
797 if e.Id.Equal(oidExtensionSubjectAltName) {
804 func signaturePublicKeyAlgoMismatchError(expectedPubKeyAlgo PublicKeyAlgorithm, pubKey interface{}) error {
805 return fmt.Errorf("x509: signature algorithm specifies an %s public key, but have public key of type %T", expectedPubKeyAlgo.String(), pubKey)
808 // CheckSignature verifies that signature is a valid signature over signed from
809 // a crypto.PublicKey.
810 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
811 var hashType crypto.Hash
812 var pubKeyAlgo PublicKeyAlgorithm
814 for _, details := range signatureAlgorithmDetails {
815 if details.algo == algo {
816 hashType = details.hash
817 pubKeyAlgo = details.pubKeyAlgo
823 if pubKeyAlgo != Ed25519 {
824 return ErrUnsupportedAlgorithm
827 return InsecureAlgorithmError(algo)
829 if !hashType.Available() {
830 return ErrUnsupportedAlgorithm
837 switch pub := publicKey.(type) {
839 if pubKeyAlgo != RSA {
840 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
843 return rsa.VerifyPSS(pub, hashType, signed, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
845 return rsa.VerifyPKCS1v15(pub, hashType, signed, signature)
847 case *ecdsa.PublicKey:
848 if pubKeyAlgo != ECDSA {
849 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
851 if !ecdsa.VerifyASN1(pub, signed, signature) {
852 return errors.New("x509: ECDSA verification failure")
855 case ed25519.PublicKey:
856 if pubKeyAlgo != Ed25519 {
857 return signaturePublicKeyAlgoMismatchError(pubKeyAlgo, pub)
859 if !ed25519.Verify(pub, signed, signature) {
860 return errors.New("x509: Ed25519 verification failure")
864 return ErrUnsupportedAlgorithm
867 // CheckCRLSignature checks that the signature in crl is from c.
868 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
869 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
870 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
873 type UnhandledCriticalExtension struct{}
875 func (h UnhandledCriticalExtension) Error() string {
876 return "x509: unhandled critical extension"
879 type basicConstraints struct {
880 IsCA bool `asn1:"optional"`
881 MaxPathLen int `asn1:"optional,default:-1"`
885 type policyInformation struct {
886 Policy asn1.ObjectIdentifier
887 // policyQualifiers omitted
898 type authorityInfoAccess struct {
899 Method asn1.ObjectIdentifier
900 Location asn1.RawValue
903 // RFC 5280, 4.2.1.14
904 type distributionPoint struct {
905 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
906 Reason asn1.BitString `asn1:"optional,tag:1"`
907 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
910 type distributionPointName struct {
911 FullName []asn1.RawValue `asn1:"optional,tag:0"`
912 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
915 func reverseBitsInAByte(in byte) byte {
917 b2 := b1>>2&0x33 | b1<<2&0xcc
918 b3 := b2>>1&0x55 | b2<<1&0xaa
922 // asn1BitLength returns the bit-length of bitString by considering the
923 // most-significant bit in a byte to be the "first" bit. This convention
924 // matches ASN.1, but differs from almost everything else.
925 func asn1BitLength(bitString []byte) int {
926 bitLen := len(bitString) * 8
928 for i := range bitString {
929 b := bitString[len(bitString)-i-1]
931 for bit := uint(0); bit < 8; bit++ {
943 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
944 oidExtensionKeyUsage = []int{2, 5, 29, 15}
945 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
946 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
947 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
948 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
949 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
950 oidExtensionNameConstraints = []int{2, 5, 29, 30}
951 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
952 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
953 oidExtensionCRLNumber = []int{2, 5, 29, 20}
957 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
958 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
961 // oidNotInExtensions reports whether an extension with the given oid exists in
963 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
964 for _, e := range extensions {
972 // marshalSANs marshals a list of addresses into a the contents of an X.509
973 // SubjectAlternativeName extension.
974 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP, uris []*url.URL) (derBytes []byte, err error) {
975 var rawValues []asn1.RawValue
976 for _, name := range dnsNames {
977 if err := isIA5String(name); err != nil {
980 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeDNS, Class: 2, Bytes: []byte(name)})
982 for _, email := range emailAddresses {
983 if err := isIA5String(email); err != nil {
986 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeEmail, Class: 2, Bytes: []byte(email)})
988 for _, rawIP := range ipAddresses {
989 // If possible, we always want to encode IPv4 addresses in 4 bytes.
994 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeIP, Class: 2, Bytes: ip})
996 for _, uri := range uris {
997 uriStr := uri.String()
998 if err := isIA5String(uriStr); err != nil {
1001 rawValues = append(rawValues, asn1.RawValue{Tag: nameTypeURI, Class: 2, Bytes: []byte(uriStr)})
1003 return asn1.Marshal(rawValues)
1006 func isIA5String(s string) error {
1007 for _, r := range s {
1008 // Per RFC5280 "IA5String is limited to the set of ASCII characters"
1009 if r > unicode.MaxASCII {
1010 return fmt.Errorf("x509: %q cannot be encoded as an IA5String", s)
1017 func buildCertExtensions(template *Certificate, subjectIsEmpty bool, authorityKeyId []byte, subjectKeyId []byte) (ret []pkix.Extension, err error) {
1018 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1021 if template.KeyUsage != 0 &&
1022 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1023 ret[n], err = marshalKeyUsage(template.KeyUsage)
1030 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1031 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1032 ret[n], err = marshalExtKeyUsage(template.ExtKeyUsage, template.UnknownExtKeyUsage)
1039 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1040 ret[n], err = marshalBasicConstraints(template.IsCA, template.MaxPathLen, template.MaxPathLenZero)
1047 if len(subjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1048 ret[n].Id = oidExtensionSubjectKeyId
1049 ret[n].Value, err = asn1.Marshal(subjectKeyId)
1056 if len(authorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1057 ret[n].Id = oidExtensionAuthorityKeyId
1058 ret[n].Value, err = asn1.Marshal(authKeyId{authorityKeyId})
1065 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1066 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1067 ret[n].Id = oidExtensionAuthorityInfoAccess
1068 var aiaValues []authorityInfoAccess
1069 for _, name := range template.OCSPServer {
1070 aiaValues = append(aiaValues, authorityInfoAccess{
1071 Method: oidAuthorityInfoAccessOcsp,
1072 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1075 for _, name := range template.IssuingCertificateURL {
1076 aiaValues = append(aiaValues, authorityInfoAccess{
1077 Method: oidAuthorityInfoAccessIssuers,
1078 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1081 ret[n].Value, err = asn1.Marshal(aiaValues)
1088 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1089 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1090 ret[n].Id = oidExtensionSubjectAltName
1091 // From RFC 5280, Section 4.2.1.6:
1092 // “If the subject field contains an empty sequence ... then
1093 // subjectAltName extension ... is marked as critical”
1094 ret[n].Critical = subjectIsEmpty
1095 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1102 if len(template.PolicyIdentifiers) > 0 &&
1103 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1104 ret[n], err = marshalCertificatePolicies(template.PolicyIdentifiers)
1111 if (len(template.PermittedDNSDomains) > 0 || len(template.ExcludedDNSDomains) > 0 ||
1112 len(template.PermittedIPRanges) > 0 || len(template.ExcludedIPRanges) > 0 ||
1113 len(template.PermittedEmailAddresses) > 0 || len(template.ExcludedEmailAddresses) > 0 ||
1114 len(template.PermittedURIDomains) > 0 || len(template.ExcludedURIDomains) > 0) &&
1115 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1116 ret[n].Id = oidExtensionNameConstraints
1117 ret[n].Critical = template.PermittedDNSDomainsCritical
1119 ipAndMask := func(ipNet *net.IPNet) []byte {
1120 maskedIP := ipNet.IP.Mask(ipNet.Mask)
1121 ipAndMask := make([]byte, 0, len(maskedIP)+len(ipNet.Mask))
1122 ipAndMask = append(ipAndMask, maskedIP...)
1123 ipAndMask = append(ipAndMask, ipNet.Mask...)
1127 serialiseConstraints := func(dns []string, ips []*net.IPNet, emails []string, uriDomains []string) (der []byte, err error) {
1128 var b cryptobyte.Builder
1130 for _, name := range dns {
1131 if err = isIA5String(name); err != nil {
1135 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1136 b.AddASN1(cryptobyte_asn1.Tag(2).ContextSpecific(), func(b *cryptobyte.Builder) {
1137 b.AddBytes([]byte(name))
1142 for _, ipNet := range ips {
1143 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1144 b.AddASN1(cryptobyte_asn1.Tag(7).ContextSpecific(), func(b *cryptobyte.Builder) {
1145 b.AddBytes(ipAndMask(ipNet))
1150 for _, email := range emails {
1151 if err = isIA5String(email); err != nil {
1155 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1156 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific(), func(b *cryptobyte.Builder) {
1157 b.AddBytes([]byte(email))
1162 for _, uriDomain := range uriDomains {
1163 if err = isIA5String(uriDomain); err != nil {
1167 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1168 b.AddASN1(cryptobyte_asn1.Tag(6).ContextSpecific(), func(b *cryptobyte.Builder) {
1169 b.AddBytes([]byte(uriDomain))
1177 permitted, err := serialiseConstraints(template.PermittedDNSDomains, template.PermittedIPRanges, template.PermittedEmailAddresses, template.PermittedURIDomains)
1182 excluded, err := serialiseConstraints(template.ExcludedDNSDomains, template.ExcludedIPRanges, template.ExcludedEmailAddresses, template.ExcludedURIDomains)
1187 var b cryptobyte.Builder
1188 b.AddASN1(cryptobyte_asn1.SEQUENCE, func(b *cryptobyte.Builder) {
1189 if len(permitted) > 0 {
1190 b.AddASN1(cryptobyte_asn1.Tag(0).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1191 b.AddBytes(permitted)
1195 if len(excluded) > 0 {
1196 b.AddASN1(cryptobyte_asn1.Tag(1).ContextSpecific().Constructed(), func(b *cryptobyte.Builder) {
1197 b.AddBytes(excluded)
1202 ret[n].Value, err = b.Bytes()
1209 if len(template.CRLDistributionPoints) > 0 &&
1210 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1211 ret[n].Id = oidExtensionCRLDistributionPoints
1213 var crlDp []distributionPoint
1214 for _, name := range template.CRLDistributionPoints {
1215 dp := distributionPoint{
1216 DistributionPoint: distributionPointName{
1217 FullName: []asn1.RawValue{
1218 {Tag: 6, Class: 2, Bytes: []byte(name)},
1222 crlDp = append(crlDp, dp)
1225 ret[n].Value, err = asn1.Marshal(crlDp)
1232 // Adding another extension here? Remember to update the maximum number
1233 // of elements in the make() at the top of the function and the list of
1234 // template fields used in CreateCertificate documentation.
1236 return append(ret[:n], template.ExtraExtensions...), nil
1239 func marshalKeyUsage(ku KeyUsage) (pkix.Extension, error) {
1240 ext := pkix.Extension{Id: oidExtensionKeyUsage, Critical: true}
1243 a[0] = reverseBitsInAByte(byte(ku))
1244 a[1] = reverseBitsInAByte(byte(ku >> 8))
1253 ext.Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1260 func marshalExtKeyUsage(extUsages []ExtKeyUsage, unknownUsages []asn1.ObjectIdentifier) (pkix.Extension, error) {
1261 ext := pkix.Extension{Id: oidExtensionExtendedKeyUsage}
1263 oids := make([]asn1.ObjectIdentifier, len(extUsages)+len(unknownUsages))
1264 for i, u := range extUsages {
1265 if oid, ok := oidFromExtKeyUsage(u); ok {
1268 return ext, errors.New("x509: unknown extended key usage")
1272 copy(oids[len(extUsages):], unknownUsages)
1275 ext.Value, err = asn1.Marshal(oids)
1282 func marshalBasicConstraints(isCA bool, maxPathLen int, maxPathLenZero bool) (pkix.Extension, error) {
1283 ext := pkix.Extension{Id: oidExtensionBasicConstraints, Critical: true}
1284 // Leaving MaxPathLen as zero indicates that no maximum path
1285 // length is desired, unless MaxPathLenZero is set. A value of
1286 // -1 causes encoding/asn1 to omit the value as desired.
1287 if maxPathLen == 0 && !maxPathLenZero {
1291 ext.Value, err = asn1.Marshal(basicConstraints{isCA, maxPathLen})
1298 func marshalCertificatePolicies(policyIdentifiers []asn1.ObjectIdentifier) (pkix.Extension, error) {
1299 ext := pkix.Extension{Id: oidExtensionCertificatePolicies}
1300 policies := make([]policyInformation, len(policyIdentifiers))
1301 for i, policy := range policyIdentifiers {
1302 policies[i].Policy = policy
1305 ext.Value, err = asn1.Marshal(policies)
1312 func buildCSRExtensions(template *CertificateRequest) ([]pkix.Extension, error) {
1313 var ret []pkix.Extension
1315 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 || len(template.URIs) > 0) &&
1316 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1317 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses, template.URIs)
1322 ret = append(ret, pkix.Extension{
1323 Id: oidExtensionSubjectAltName,
1328 return append(ret, template.ExtraExtensions...), nil
1331 func subjectBytes(cert *Certificate) ([]byte, error) {
1332 if len(cert.RawSubject) > 0 {
1333 return cert.RawSubject, nil
1336 return asn1.Marshal(cert.Subject.ToRDNSequence())
1339 // signingParamsForPublicKey returns the parameters to use for signing with
1340 // priv. If requestedSigAlgo is not zero then it overrides the default
1341 // signature algorithm.
1342 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1343 var pubType PublicKeyAlgorithm
1345 switch pub := pub.(type) {
1346 case *rsa.PublicKey:
1348 hashFunc = crypto.SHA256
1349 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1350 sigAlgo.Parameters = asn1.NullRawValue
1352 case *ecdsa.PublicKey:
1356 case elliptic.P224(), elliptic.P256():
1357 hashFunc = crypto.SHA256
1358 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1359 case elliptic.P384():
1360 hashFunc = crypto.SHA384
1361 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1362 case elliptic.P521():
1363 hashFunc = crypto.SHA512
1364 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1366 err = errors.New("x509: unknown elliptic curve")
1369 case ed25519.PublicKey:
1371 sigAlgo.Algorithm = oidSignatureEd25519
1374 err = errors.New("x509: only RSA, ECDSA and Ed25519 keys supported")
1381 if requestedSigAlgo == 0 {
1386 for _, details := range signatureAlgorithmDetails {
1387 if details.algo == requestedSigAlgo {
1388 if details.pubKeyAlgo != pubType {
1389 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
1392 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
1393 if hashFunc == 0 && pubType != Ed25519 {
1394 err = errors.New("x509: cannot sign with hash function requested")
1397 if requestedSigAlgo.isRSAPSS() {
1398 sigAlgo.Parameters = hashToPSSParameters[hashFunc]
1406 err = errors.New("x509: unknown SignatureAlgorithm")
1412 // emptyASN1Subject is the ASN.1 DER encoding of an empty Subject, which is
1413 // just an empty SEQUENCE.
1414 var emptyASN1Subject = []byte{0x30, 0}
1416 // CreateCertificate creates a new X.509 v3 certificate based on a template.
1417 // The following members of template are currently used:
1420 // - BasicConstraintsValid
1421 // - CRLDistributionPoints
1424 // - ExcludedDNSDomains
1425 // - ExcludedEmailAddresses
1426 // - ExcludedIPRanges
1427 // - ExcludedURIDomains
1429 // - ExtraExtensions
1432 // - IssuingCertificateURL
1439 // - PermittedDNSDomains
1440 // - PermittedDNSDomainsCritical
1441 // - PermittedEmailAddresses
1442 // - PermittedIPRanges
1443 // - PermittedURIDomains
1444 // - PolicyIdentifiers
1446 // - SignatureAlgorithm
1450 // - UnknownExtKeyUsage
1452 // The certificate is signed by parent. If parent is equal to template then the
1453 // certificate is self-signed. The parameter pub is the public key of the
1454 // certificate to be generated and priv is the private key of the signer.
1456 // The returned slice is the certificate in DER encoding.
1458 // The currently supported key types are *rsa.PublicKey, *ecdsa.PublicKey and
1459 // ed25519.PublicKey. pub must be a supported key type, and priv must be a
1460 // crypto.Signer with a supported public key.
1462 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
1463 // unless the resulting certificate is self-signed. Otherwise the value from
1464 // template will be used.
1466 // If SubjectKeyId from template is empty and the template is a CA, SubjectKeyId
1467 // will be generated from the hash of the public key.
1468 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) ([]byte, error) {
1469 key, ok := priv.(crypto.Signer)
1471 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1474 if template.SerialNumber == nil {
1475 return nil, errors.New("x509: no SerialNumber given")
1478 if template.BasicConstraintsValid && !template.IsCA && template.MaxPathLen != -1 && (template.MaxPathLen != 0 || template.MaxPathLenZero) {
1479 return nil, errors.New("x509: only CAs are allowed to specify MaxPathLen")
1482 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1487 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1492 asn1Issuer, err := subjectBytes(parent)
1497 asn1Subject, err := subjectBytes(template)
1502 authorityKeyId := template.AuthorityKeyId
1503 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1504 authorityKeyId = parent.SubjectKeyId
1507 subjectKeyId := template.SubjectKeyId
1508 if len(subjectKeyId) == 0 && template.IsCA {
1509 // SubjectKeyId generated using method 1 in RFC 5280, Section 4.2.1.2:
1510 // (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the
1511 // value of the BIT STRING subjectPublicKey (excluding the tag,
1512 // length, and number of unused bits).
1513 h := sha1.Sum(publicKeyBytes)
1517 // Check that the signer's public key matches the private key, if available.
1518 type privateKey interface {
1519 Equal(crypto.PublicKey) bool
1521 if privPub, ok := key.Public().(privateKey); !ok {
1522 return nil, errors.New("x509: internal error: supported public key does not implement Equal")
1523 } else if parent.PublicKey != nil && !privPub.Equal(parent.PublicKey) {
1524 return nil, errors.New("x509: provided PrivateKey doesn't match parent's PublicKey")
1527 extensions, err := buildCertExtensions(template, bytes.Equal(asn1Subject, emptyASN1Subject), authorityKeyId, subjectKeyId)
1532 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1533 c := tbsCertificate{
1535 SerialNumber: template.SerialNumber,
1536 SignatureAlgorithm: signatureAlgorithm,
1537 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1538 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1539 Subject: asn1.RawValue{FullBytes: asn1Subject},
1540 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1541 Extensions: extensions,
1544 tbsCertContents, err := asn1.Marshal(c)
1548 c.Raw = tbsCertContents
1550 signed := tbsCertContents
1557 var signerOpts crypto.SignerOpts = hashFunc
1558 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
1559 signerOpts = &rsa.PSSOptions{
1560 SaltLength: rsa.PSSSaltLengthEqualsHash,
1565 var signature []byte
1566 signature, err = key.Sign(rand, signed, signerOpts)
1571 signedCert, err := asn1.Marshal(certificate{
1575 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1581 // Check the signature to ensure the crypto.Signer behaved correctly.
1582 // We skip this check if the signature algorithm is MD5WithRSA as we
1583 // only support this algorithm for signing, and not verification.
1584 if sigAlg := getSignatureAlgorithmFromAI(signatureAlgorithm); sigAlg != MD5WithRSA {
1585 if err := checkSignature(sigAlg, c.Raw, signature, key.Public()); err != nil {
1586 return nil, fmt.Errorf("x509: signature over certificate returned by signer is invalid: %w", err)
1590 return signedCert, nil
1593 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1595 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1597 // pemType is the type of a PEM encoded CRL.
1598 var pemType = "X509 CRL"
1600 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1601 // encoded CRLs will appear where they should be DER encoded, so this function
1602 // will transparently handle PEM encoding as long as there isn't any leading
1604 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1605 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1606 block, _ := pem.Decode(crlBytes)
1607 if block != nil && block.Type == pemType {
1608 crlBytes = block.Bytes
1611 return ParseDERCRL(crlBytes)
1614 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1615 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1616 certList := new(pkix.CertificateList)
1617 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
1619 } else if len(rest) != 0 {
1620 return nil, errors.New("x509: trailing data after CRL")
1622 return certList, nil
1625 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1626 // contains the given list of revoked certificates.
1628 // Note: this method does not generate an RFC 5280 conformant X.509 v2 CRL.
1629 // To generate a standards compliant CRL, use CreateRevocationList instead.
1630 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1631 key, ok := priv.(crypto.Signer)
1633 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1636 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
1641 // Force revocation times to UTC per RFC 5280.
1642 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
1643 for i, rc := range revokedCerts {
1644 rc.RevocationTime = rc.RevocationTime.UTC()
1645 revokedCertsUTC[i] = rc
1648 tbsCertList := pkix.TBSCertificateList{
1650 Signature: signatureAlgorithm,
1651 Issuer: c.Subject.ToRDNSequence(),
1652 ThisUpdate: now.UTC(),
1653 NextUpdate: expiry.UTC(),
1654 RevokedCertificates: revokedCertsUTC,
1658 if len(c.SubjectKeyId) > 0 {
1659 var aki pkix.Extension
1660 aki.Id = oidExtensionAuthorityKeyId
1661 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
1665 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
1668 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1673 signed := tbsCertListContents
1680 var signature []byte
1681 signature, err = key.Sign(rand, signed, hashFunc)
1686 return asn1.Marshal(pkix.CertificateList{
1687 TBSCertList: tbsCertList,
1688 SignatureAlgorithm: signatureAlgorithm,
1689 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1693 // CertificateRequest represents a PKCS #10, certificate signature request.
1694 type CertificateRequest struct {
1695 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
1696 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
1697 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
1698 RawSubject []byte // DER encoded Subject.
1702 SignatureAlgorithm SignatureAlgorithm
1704 PublicKeyAlgorithm PublicKeyAlgorithm
1705 PublicKey interface{}
1709 // Attributes contains the CSR attributes that can parse as
1710 // pkix.AttributeTypeAndValueSET.
1712 // Deprecated: Use Extensions and ExtraExtensions instead for parsing and
1713 // generating the requestedExtensions attribute.
1714 Attributes []pkix.AttributeTypeAndValueSET
1716 // Extensions contains all requested extensions, in raw form. When parsing
1717 // CSRs, this can be used to extract extensions that are not parsed by this
1719 Extensions []pkix.Extension
1721 // ExtraExtensions contains extensions to be copied, raw, into any CSR
1722 // marshaled by CreateCertificateRequest. Values override any extensions
1723 // that would otherwise be produced based on the other fields but are
1724 // overridden by any extensions specified in Attributes.
1726 // The ExtraExtensions field is not populated by ParseCertificateRequest,
1727 // see Extensions instead.
1728 ExtraExtensions []pkix.Extension
1730 // Subject Alternate Name values.
1732 EmailAddresses []string
1733 IPAddresses []net.IP
1737 // These structures reflect the ASN.1 structure of X.509 certificate
1738 // signature requests (see RFC 2986):
1740 type tbsCertificateRequest struct {
1743 Subject asn1.RawValue
1744 PublicKey publicKeyInfo
1745 RawAttributes []asn1.RawValue `asn1:"tag:0"`
1748 type certificateRequest struct {
1750 TBSCSR tbsCertificateRequest
1751 SignatureAlgorithm pkix.AlgorithmIdentifier
1752 SignatureValue asn1.BitString
1755 // oidExtensionRequest is a PKCS #9 OBJECT IDENTIFIER that indicates requested
1756 // extensions in a CSR.
1757 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
1759 // newRawAttributes converts AttributeTypeAndValueSETs from a template
1760 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
1761 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
1762 var rawAttributes []asn1.RawValue
1763 b, err := asn1.Marshal(attributes)
1767 rest, err := asn1.Unmarshal(b, &rawAttributes)
1772 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
1774 return rawAttributes, nil
1777 // parseRawAttributes Unmarshals RawAttributes into AttributeTypeAndValueSETs.
1778 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
1779 var attributes []pkix.AttributeTypeAndValueSET
1780 for _, rawAttr := range rawAttributes {
1781 var attr pkix.AttributeTypeAndValueSET
1782 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
1783 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
1784 // (i.e.: challengePassword or unstructuredName).
1785 if err == nil && len(rest) == 0 {
1786 attributes = append(attributes, attr)
1792 // parseCSRExtensions parses the attributes from a CSR and extracts any
1793 // requested extensions.
1794 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
1795 // pkcs10Attribute reflects the Attribute structure from RFC 2986, Section 4.1.
1796 type pkcs10Attribute struct {
1797 Id asn1.ObjectIdentifier
1798 Values []asn1.RawValue `asn1:"set"`
1801 var ret []pkix.Extension
1802 for _, rawAttr := range rawAttributes {
1803 var attr pkcs10Attribute
1804 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
1805 // Ignore attributes that don't parse.
1809 if !attr.Id.Equal(oidExtensionRequest) {
1813 var extensions []pkix.Extension
1814 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
1817 ret = append(ret, extensions...)
1823 // CreateCertificateRequest creates a new certificate request based on a
1824 // template. The following members of template are used:
1826 // - SignatureAlgorithm
1832 // - ExtraExtensions
1833 // - Attributes (deprecated)
1835 // priv is the private key to sign the CSR with, and the corresponding public
1836 // key will be included in the CSR. It must implement crypto.Signer and its
1837 // Public() method must return a *rsa.PublicKey or a *ecdsa.PublicKey or a
1838 // ed25519.PublicKey. (A *rsa.PrivateKey, *ecdsa.PrivateKey or
1839 // ed25519.PrivateKey satisfies this.)
1841 // The returned slice is the certificate request in DER encoding.
1842 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
1843 key, ok := priv.(crypto.Signer)
1845 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1848 var hashFunc crypto.Hash
1849 var sigAlgo pkix.AlgorithmIdentifier
1850 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1855 var publicKeyBytes []byte
1856 var publicKeyAlgorithm pkix.AlgorithmIdentifier
1857 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
1862 extensions, err := buildCSRExtensions(template)
1867 // Make a copy of template.Attributes because we may alter it below.
1868 attributes := make([]pkix.AttributeTypeAndValueSET, 0, len(template.Attributes))
1869 for _, attr := range template.Attributes {
1870 values := make([][]pkix.AttributeTypeAndValue, len(attr.Value))
1871 copy(values, attr.Value)
1872 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
1878 extensionsAppended := false
1879 if len(extensions) > 0 {
1880 // Append the extensions to an existing attribute if possible.
1881 for _, atvSet := range attributes {
1882 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
1886 // specifiedExtensions contains all the extensions that we
1887 // found specified via template.Attributes.
1888 specifiedExtensions := make(map[string]bool)
1890 for _, atvs := range atvSet.Value {
1891 for _, atv := range atvs {
1892 specifiedExtensions[atv.Type.String()] = true
1896 newValue := make([]pkix.AttributeTypeAndValue, 0, len(atvSet.Value[0])+len(extensions))
1897 newValue = append(newValue, atvSet.Value[0]...)
1899 for _, e := range extensions {
1900 if specifiedExtensions[e.Id.String()] {
1901 // Attributes already contained a value for
1902 // this extension and it takes priority.
1906 newValue = append(newValue, pkix.AttributeTypeAndValue{
1907 // There is no place for the critical
1908 // flag in an AttributeTypeAndValue.
1914 atvSet.Value[0] = newValue
1915 extensionsAppended = true
1920 rawAttributes, err := newRawAttributes(attributes)
1925 // If not included in attributes, add a new attribute for the
1927 if len(extensions) > 0 && !extensionsAppended {
1929 Type asn1.ObjectIdentifier
1930 Value [][]pkix.Extension `asn1:"set"`
1932 Type: oidExtensionRequest,
1933 Value: [][]pkix.Extension{extensions},
1936 b, err := asn1.Marshal(attr)
1938 return nil, errors.New("x509: failed to serialise extensions attribute: " + err.Error())
1941 var rawValue asn1.RawValue
1942 if _, err := asn1.Unmarshal(b, &rawValue); err != nil {
1946 rawAttributes = append(rawAttributes, rawValue)
1949 asn1Subject := template.RawSubject
1950 if len(asn1Subject) == 0 {
1951 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
1957 tbsCSR := tbsCertificateRequest{
1958 Version: 0, // PKCS #10, RFC 2986
1959 Subject: asn1.RawValue{FullBytes: asn1Subject},
1960 PublicKey: publicKeyInfo{
1961 Algorithm: publicKeyAlgorithm,
1962 PublicKey: asn1.BitString{
1963 Bytes: publicKeyBytes,
1964 BitLength: len(publicKeyBytes) * 8,
1967 RawAttributes: rawAttributes,
1970 tbsCSRContents, err := asn1.Marshal(tbsCSR)
1974 tbsCSR.Raw = tbsCSRContents
1976 signed := tbsCSRContents
1983 var signature []byte
1984 signature, err = key.Sign(rand, signed, hashFunc)
1989 return asn1.Marshal(certificateRequest{
1991 SignatureAlgorithm: sigAlgo,
1992 SignatureValue: asn1.BitString{
1994 BitLength: len(signature) * 8,
1999 // ParseCertificateRequest parses a single certificate request from the
2000 // given ASN.1 DER data.
2001 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2002 var csr certificateRequest
2004 rest, err := asn1.Unmarshal(asn1Data, &csr)
2007 } else if len(rest) != 0 {
2008 return nil, asn1.SyntaxError{Msg: "trailing data"}
2011 return parseCertificateRequest(&csr)
2014 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2015 out := &CertificateRequest{
2017 RawTBSCertificateRequest: in.TBSCSR.Raw,
2018 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2019 RawSubject: in.TBSCSR.Subject.FullBytes,
2021 Signature: in.SignatureValue.RightAlign(),
2022 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2024 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2026 Version: in.TBSCSR.Version,
2027 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2031 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2036 var subject pkix.RDNSequence
2037 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2039 } else if len(rest) != 0 {
2040 return nil, errors.New("x509: trailing data after X.509 Subject")
2043 out.Subject.FillFromRDNSequence(&subject)
2045 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2049 for _, extension := range out.Extensions {
2051 case extension.Id.Equal(oidExtensionSubjectAltName):
2052 out.DNSNames, out.EmailAddresses, out.IPAddresses, out.URIs, err = parseSANExtension(extension.Value)
2062 // CheckSignature reports whether the signature on c is valid.
2063 func (c *CertificateRequest) CheckSignature() error {
2064 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
2067 // RevocationList contains the fields used to create an X.509 v2 Certificate
2068 // Revocation list with CreateRevocationList.
2069 type RevocationList struct {
2070 // SignatureAlgorithm is used to determine the signature algorithm to be
2071 // used when signing the CRL. If 0 the default algorithm for the signing
2072 // key will be used.
2073 SignatureAlgorithm SignatureAlgorithm
2075 // RevokedCertificates is used to populate the revokedCertificates
2076 // sequence in the CRL, it may be empty. RevokedCertificates may be nil,
2077 // in which case an empty CRL will be created.
2078 RevokedCertificates []pkix.RevokedCertificate
2080 // Number is used to populate the X.509 v2 cRLNumber extension in the CRL,
2081 // which should be a monotonically increasing sequence number for a given
2082 // CRL scope and CRL issuer.
2084 // ThisUpdate is used to populate the thisUpdate field in the CRL, which
2085 // indicates the issuance date of the CRL.
2086 ThisUpdate time.Time
2087 // NextUpdate is used to populate the nextUpdate field in the CRL, which
2088 // indicates the date by which the next CRL will be issued. NextUpdate
2089 // must be greater than ThisUpdate.
2090 NextUpdate time.Time
2091 // ExtraExtensions contains any additional extensions to add directly to
2093 ExtraExtensions []pkix.Extension
2096 // CreateRevocationList creates a new X.509 v2 Certificate Revocation List,
2097 // according to RFC 5280, based on template.
2099 // The CRL is signed by priv which should be the private key associated with
2100 // the public key in the issuer certificate.
2102 // The issuer may not be nil, and the crlSign bit must be set in KeyUsage in
2103 // order to use it as a CRL issuer.
2105 // The issuer distinguished name CRL field and authority key identifier
2106 // extension are populated using the issuer certificate. issuer must have
2107 // SubjectKeyId set.
2108 func CreateRevocationList(rand io.Reader, template *RevocationList, issuer *Certificate, priv crypto.Signer) ([]byte, error) {
2109 if template == nil {
2110 return nil, errors.New("x509: template can not be nil")
2113 return nil, errors.New("x509: issuer can not be nil")
2115 if (issuer.KeyUsage & KeyUsageCRLSign) == 0 {
2116 return nil, errors.New("x509: issuer must have the crlSign key usage bit set")
2118 if len(issuer.SubjectKeyId) == 0 {
2119 return nil, errors.New("x509: issuer certificate doesn't contain a subject key identifier")
2121 if template.NextUpdate.Before(template.ThisUpdate) {
2122 return nil, errors.New("x509: template.ThisUpdate is after template.NextUpdate")
2124 if template.Number == nil {
2125 return nil, errors.New("x509: template contains nil Number field")
2128 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
2133 // Force revocation times to UTC per RFC 5280.
2134 revokedCertsUTC := make([]pkix.RevokedCertificate, len(template.RevokedCertificates))
2135 for i, rc := range template.RevokedCertificates {
2136 rc.RevocationTime = rc.RevocationTime.UTC()
2137 revokedCertsUTC[i] = rc
2140 aki, err := asn1.Marshal(authKeyId{Id: issuer.SubjectKeyId})
2144 crlNum, err := asn1.Marshal(template.Number)
2149 tbsCertList := pkix.TBSCertificateList{
2151 Signature: signatureAlgorithm,
2152 Issuer: issuer.Subject.ToRDNSequence(),
2153 ThisUpdate: template.ThisUpdate.UTC(),
2154 NextUpdate: template.NextUpdate.UTC(),
2155 Extensions: []pkix.Extension{
2157 Id: oidExtensionAuthorityKeyId,
2161 Id: oidExtensionCRLNumber,
2166 if len(revokedCertsUTC) > 0 {
2167 tbsCertList.RevokedCertificates = revokedCertsUTC
2170 if len(template.ExtraExtensions) > 0 {
2171 tbsCertList.Extensions = append(tbsCertList.Extensions, template.ExtraExtensions...)
2174 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2179 input := tbsCertListContents
2182 h.Write(tbsCertListContents)
2185 var signerOpts crypto.SignerOpts = hashFunc
2186 if template.SignatureAlgorithm.isRSAPSS() {
2187 signerOpts = &rsa.PSSOptions{
2188 SaltLength: rsa.PSSSaltLengthEqualsHash,
2193 signature, err := priv.Sign(rand, input, signerOpts)
2198 return asn1.Marshal(pkix.CertificateList{
2199 TBSCertList: tbsCertList,
2200 SignatureAlgorithm: signatureAlgorithm,
2201 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},