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.
34 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
36 type pkixPublicKey
struct {
37 Algo pkix
.AlgorithmIdentifier
38 BitString asn1
.BitString
41 // ParsePKIXPublicKey parses a DER encoded public key. These values are
42 // typically found in PEM blocks with "BEGIN PUBLIC KEY".
44 // Supported key types include RSA, DSA, and ECDSA. Unknown key
45 // types result in an error.
47 // On success, pub will be of type *rsa.PublicKey, *dsa.PublicKey,
48 // or *ecdsa.PublicKey.
49 func ParsePKIXPublicKey(derBytes
[]byte) (pub
interface{}, err error
) {
51 if rest
, err
:= asn1
.Unmarshal(derBytes
, &pki
); err
!= nil {
53 } else if len(rest
) != 0 {
54 return nil, errors
.New("x509: trailing data after ASN.1 of public-key")
56 algo
:= getPublicKeyAlgorithmFromOID(pki
.Algorithm
.Algorithm
)
57 if algo
== UnknownPublicKeyAlgorithm
{
58 return nil, errors
.New("x509: unknown public key algorithm")
60 return parsePublicKey(algo
, &pki
)
63 func marshalPublicKey(pub
interface{}) (publicKeyBytes
[]byte, publicKeyAlgorithm pkix
.AlgorithmIdentifier
, err error
) {
64 switch pub
:= pub
.(type) {
66 publicKeyBytes
, err
= asn1
.Marshal(pkcs1PublicKey
{
71 return nil, pkix
.AlgorithmIdentifier
{}, err
73 publicKeyAlgorithm
.Algorithm
= oidPublicKeyRSA
74 // This is a NULL parameters value which is required by
75 // https://tools.ietf.org/html/rfc3279#section-2.3.1.
76 publicKeyAlgorithm
.Parameters
= asn1
.NullRawValue
77 case *ecdsa
.PublicKey
:
78 publicKeyBytes
= elliptic
.Marshal(pub
.Curve
, pub
.X
, pub
.Y
)
79 oid
, ok
:= oidFromNamedCurve(pub
.Curve
)
81 return nil, pkix
.AlgorithmIdentifier
{}, errors
.New("x509: unsupported elliptic curve")
83 publicKeyAlgorithm
.Algorithm
= oidPublicKeyECDSA
85 paramBytes
, err
= asn1
.Marshal(oid
)
89 publicKeyAlgorithm
.Parameters
.FullBytes
= paramBytes
91 return nil, pkix
.AlgorithmIdentifier
{}, errors
.New("x509: only RSA and ECDSA public keys supported")
94 return publicKeyBytes
, publicKeyAlgorithm
, nil
97 // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
98 func MarshalPKIXPublicKey(pub
interface{}) ([]byte, error
) {
99 var publicKeyBytes
[]byte
100 var publicKeyAlgorithm pkix
.AlgorithmIdentifier
103 if publicKeyBytes
, publicKeyAlgorithm
, err
= marshalPublicKey(pub
); err
!= nil {
107 pkix
:= pkixPublicKey
{
108 Algo
: publicKeyAlgorithm
,
109 BitString
: asn1
.BitString
{
110 Bytes
: publicKeyBytes
,
111 BitLength
: 8 * len(publicKeyBytes
),
115 ret
, _
:= asn1
.Marshal(pkix
)
119 // These structures reflect the ASN.1 structure of X.509 certificates.:
121 type certificate
struct {
123 TBSCertificate tbsCertificate
124 SignatureAlgorithm pkix
.AlgorithmIdentifier
125 SignatureValue asn1
.BitString
128 type tbsCertificate
struct {
130 Version
int `asn1:"optional,explicit,default:0,tag:0"`
131 SerialNumber
*big
.Int
132 SignatureAlgorithm pkix
.AlgorithmIdentifier
135 Subject asn1
.RawValue
136 PublicKey publicKeyInfo
137 UniqueId asn1
.BitString
`asn1:"optional,tag:1"`
138 SubjectUniqueId asn1
.BitString
`asn1:"optional,tag:2"`
139 Extensions
[]pkix
.Extension
`asn1:"optional,explicit,tag:3"`
142 type dsaAlgorithmParameters
struct {
146 type dsaSignature
struct {
150 type ecdsaSignature dsaSignature
152 type validity
struct {
153 NotBefore
, NotAfter time
.Time
156 type publicKeyInfo
struct {
158 Algorithm pkix
.AlgorithmIdentifier
159 PublicKey asn1
.BitString
163 type authKeyId
struct {
164 Id
[]byte `asn1:"optional,tag:0"`
167 type SignatureAlgorithm
int
170 UnknownSignatureAlgorithm SignatureAlgorithm
= iota
188 func (algo SignatureAlgorithm
) isRSAPSS() bool {
190 case SHA256WithRSAPSS
, SHA384WithRSAPSS
, SHA512WithRSAPSS
:
197 var algoName
= [...]string{
198 MD2WithRSA
: "MD2-RSA",
199 MD5WithRSA
: "MD5-RSA",
200 SHA1WithRSA
: "SHA1-RSA",
201 SHA256WithRSA
: "SHA256-RSA",
202 SHA384WithRSA
: "SHA384-RSA",
203 SHA512WithRSA
: "SHA512-RSA",
204 SHA256WithRSAPSS
: "SHA256-RSAPSS",
205 SHA384WithRSAPSS
: "SHA384-RSAPSS",
206 SHA512WithRSAPSS
: "SHA512-RSAPSS",
207 DSAWithSHA1
: "DSA-SHA1",
208 DSAWithSHA256
: "DSA-SHA256",
209 ECDSAWithSHA1
: "ECDSA-SHA1",
210 ECDSAWithSHA256
: "ECDSA-SHA256",
211 ECDSAWithSHA384
: "ECDSA-SHA384",
212 ECDSAWithSHA512
: "ECDSA-SHA512",
215 func (algo SignatureAlgorithm
) String() string {
216 if 0 < algo
&& int(algo
) < len(algoName
) {
217 return algoName
[algo
]
219 return strconv
.Itoa(int(algo
))
222 type PublicKeyAlgorithm
int
225 UnknownPublicKeyAlgorithm PublicKeyAlgorithm
= iota
231 // OIDs for signature algorithms
233 // pkcs-1 OBJECT IDENTIFIER ::= {
234 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
237 // RFC 3279 2.2.1 RSA Signature Algorithms
239 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
241 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
243 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
245 // dsaWithSha1 OBJECT IDENTIFIER ::= {
246 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
248 // RFC 3279 2.2.3 ECDSA Signature Algorithm
250 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
251 // iso(1) member-body(2) us(840) ansi-x962(10045)
252 // signatures(4) ecdsa-with-SHA1(1)}
255 // RFC 4055 5 PKCS #1 Version 1.5
257 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
259 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
261 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
264 // RFC 5758 3.1 DSA Signature Algorithms
266 // dsaWithSha256 OBJECT IDENTIFIER ::= {
267 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
268 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
270 // RFC 5758 3.2 ECDSA Signature Algorithm
272 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
273 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
275 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
276 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
278 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
279 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
282 oidSignatureMD2WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 2}
283 oidSignatureMD5WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 4}
284 oidSignatureSHA1WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 5}
285 oidSignatureSHA256WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 11}
286 oidSignatureSHA384WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 12}
287 oidSignatureSHA512WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 13}
288 oidSignatureRSAPSS
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 10}
289 oidSignatureDSAWithSHA1
= asn1
.ObjectIdentifier
{1, 2, 840, 10040, 4, 3}
290 oidSignatureDSAWithSHA256
= asn1
.ObjectIdentifier
{2, 16, 840, 1, 101, 3, 4, 3, 2}
291 oidSignatureECDSAWithSHA1
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 1}
292 oidSignatureECDSAWithSHA256
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 3, 2}
293 oidSignatureECDSAWithSHA384
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 3, 3}
294 oidSignatureECDSAWithSHA512
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 3, 4}
296 oidSHA256
= asn1
.ObjectIdentifier
{2, 16, 840, 1, 101, 3, 4, 2, 1}
297 oidSHA384
= asn1
.ObjectIdentifier
{2, 16, 840, 1, 101, 3, 4, 2, 2}
298 oidSHA512
= asn1
.ObjectIdentifier
{2, 16, 840, 1, 101, 3, 4, 2, 3}
300 oidMGF1
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 8}
302 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
303 // but it's specified by ISO. Microsoft's makecert.exe has been known
304 // to produce certificates with this OID.
305 oidISOSignatureSHA1WithRSA
= asn1
.ObjectIdentifier
{1, 3, 14, 3, 2, 29}
308 var signatureAlgorithmDetails
= []struct {
309 algo SignatureAlgorithm
310 oid asn1
.ObjectIdentifier
311 pubKeyAlgo PublicKeyAlgorithm
314 {MD2WithRSA
, oidSignatureMD2WithRSA
, RSA
, crypto
.Hash(0) /* no value for MD2 */},
315 {MD5WithRSA
, oidSignatureMD5WithRSA
, RSA
, crypto
.MD5
},
316 {SHA1WithRSA
, oidSignatureSHA1WithRSA
, RSA
, crypto
.SHA1
},
317 {SHA1WithRSA
, oidISOSignatureSHA1WithRSA
, RSA
, crypto
.SHA1
},
318 {SHA256WithRSA
, oidSignatureSHA256WithRSA
, RSA
, crypto
.SHA256
},
319 {SHA384WithRSA
, oidSignatureSHA384WithRSA
, RSA
, crypto
.SHA384
},
320 {SHA512WithRSA
, oidSignatureSHA512WithRSA
, RSA
, crypto
.SHA512
},
321 {SHA256WithRSAPSS
, oidSignatureRSAPSS
, RSA
, crypto
.SHA256
},
322 {SHA384WithRSAPSS
, oidSignatureRSAPSS
, RSA
, crypto
.SHA384
},
323 {SHA512WithRSAPSS
, oidSignatureRSAPSS
, RSA
, crypto
.SHA512
},
324 {DSAWithSHA1
, oidSignatureDSAWithSHA1
, DSA
, crypto
.SHA1
},
325 {DSAWithSHA256
, oidSignatureDSAWithSHA256
, DSA
, crypto
.SHA256
},
326 {ECDSAWithSHA1
, oidSignatureECDSAWithSHA1
, ECDSA
, crypto
.SHA1
},
327 {ECDSAWithSHA256
, oidSignatureECDSAWithSHA256
, ECDSA
, crypto
.SHA256
},
328 {ECDSAWithSHA384
, oidSignatureECDSAWithSHA384
, ECDSA
, crypto
.SHA384
},
329 {ECDSAWithSHA512
, oidSignatureECDSAWithSHA512
, ECDSA
, crypto
.SHA512
},
332 // pssParameters reflects the parameters in an AlgorithmIdentifier that
333 // specifies RSA PSS. See https://tools.ietf.org/html/rfc3447#appendix-A.2.3
334 type pssParameters
struct {
335 // The following three fields are not marked as
336 // optional because the default values specify SHA-1,
337 // which is no longer suitable for use in signatures.
338 Hash pkix
.AlgorithmIdentifier
`asn1:"explicit,tag:0"`
339 MGF pkix
.AlgorithmIdentifier
`asn1:"explicit,tag:1"`
340 SaltLength
int `asn1:"explicit,tag:2"`
341 TrailerField
int `asn1:"optional,explicit,tag:3,default:1"`
344 // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
345 // in an AlgorithmIdentifier that specifies RSA PSS.
346 func rsaPSSParameters(hashFunc crypto
.Hash
) asn1
.RawValue
{
347 var hashOID asn1
.ObjectIdentifier
358 params
:= pssParameters
{
359 Hash
: pkix
.AlgorithmIdentifier
{
361 Parameters
: asn1
.NullRawValue
,
363 MGF
: pkix
.AlgorithmIdentifier
{
366 SaltLength
: hashFunc
.Size(),
370 mgf1Params
:= pkix
.AlgorithmIdentifier
{
372 Parameters
: asn1
.NullRawValue
,
376 params
.MGF
.Parameters
.FullBytes
, err
= asn1
.Marshal(mgf1Params
)
381 serialized
, err
:= asn1
.Marshal(params
)
386 return asn1
.RawValue
{FullBytes
: serialized
}
389 func getSignatureAlgorithmFromAI(ai pkix
.AlgorithmIdentifier
) SignatureAlgorithm
{
390 if !ai
.Algorithm
.Equal(oidSignatureRSAPSS
) {
391 for _
, details
:= range signatureAlgorithmDetails
{
392 if ai
.Algorithm
.Equal(details
.oid
) {
396 return UnknownSignatureAlgorithm
399 // RSA PSS is special because it encodes important parameters
400 // in the Parameters.
402 var params pssParameters
403 if _
, err
:= asn1
.Unmarshal(ai
.Parameters
.FullBytes
, ¶ms
); err
!= nil {
404 return UnknownSignatureAlgorithm
407 var mgf1HashFunc pkix
.AlgorithmIdentifier
408 if _
, err
:= asn1
.Unmarshal(params
.MGF
.Parameters
.FullBytes
, &mgf1HashFunc
); err
!= nil {
409 return UnknownSignatureAlgorithm
412 // PSS is greatly overburdened with options. This code forces
413 // them into three buckets by requiring that the MGF1 hash
414 // function always match the message hash function (as
416 // https://tools.ietf.org/html/rfc3447#section-8.1), that the
417 // salt length matches the hash length, and that the trailer
418 // field has the default value.
419 if !bytes
.Equal(params
.Hash
.Parameters
.FullBytes
, asn1
.NullBytes
) ||
420 !params
.MGF
.Algorithm
.Equal(oidMGF1
) ||
421 !mgf1HashFunc
.Algorithm
.Equal(params
.Hash
.Algorithm
) ||
422 !bytes
.Equal(mgf1HashFunc
.Parameters
.FullBytes
, asn1
.NullBytes
) ||
423 params
.TrailerField
!= 1 {
424 return UnknownSignatureAlgorithm
428 case params
.Hash
.Algorithm
.Equal(oidSHA256
) && params
.SaltLength
== 32:
429 return SHA256WithRSAPSS
430 case params
.Hash
.Algorithm
.Equal(oidSHA384
) && params
.SaltLength
== 48:
431 return SHA384WithRSAPSS
432 case params
.Hash
.Algorithm
.Equal(oidSHA512
) && params
.SaltLength
== 64:
433 return SHA512WithRSAPSS
436 return UnknownSignatureAlgorithm
439 // RFC 3279, 2.3 Public Key Algorithms
441 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
442 // rsadsi(113549) pkcs(1) 1 }
444 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
446 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
447 // x9-57(10040) x9cm(4) 1 }
449 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
451 // id-ecPublicKey OBJECT IDENTIFIER ::= {
452 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
454 oidPublicKeyRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 1}
455 oidPublicKeyDSA
= asn1
.ObjectIdentifier
{1, 2, 840, 10040, 4, 1}
456 oidPublicKeyECDSA
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 2, 1}
459 func getPublicKeyAlgorithmFromOID(oid asn1
.ObjectIdentifier
) PublicKeyAlgorithm
{
461 case oid
.Equal(oidPublicKeyRSA
):
463 case oid
.Equal(oidPublicKeyDSA
):
465 case oid
.Equal(oidPublicKeyECDSA
):
468 return UnknownPublicKeyAlgorithm
471 // RFC 5480, 2.1.1.1. Named Curve
473 // secp224r1 OBJECT IDENTIFIER ::= {
474 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
476 // secp256r1 OBJECT IDENTIFIER ::= {
477 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
480 // secp384r1 OBJECT IDENTIFIER ::= {
481 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
483 // secp521r1 OBJECT IDENTIFIER ::= {
484 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
486 // NB: secp256r1 is equivalent to prime256v1
488 oidNamedCurveP224
= asn1
.ObjectIdentifier
{1, 3, 132, 0, 33}
489 oidNamedCurveP256
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 3, 1, 7}
490 oidNamedCurveP384
= asn1
.ObjectIdentifier
{1, 3, 132, 0, 34}
491 oidNamedCurveP521
= asn1
.ObjectIdentifier
{1, 3, 132, 0, 35}
494 func namedCurveFromOID(oid asn1
.ObjectIdentifier
) elliptic
.Curve
{
496 case oid
.Equal(oidNamedCurveP224
):
497 return elliptic
.P224()
498 case oid
.Equal(oidNamedCurveP256
):
499 return elliptic
.P256()
500 case oid
.Equal(oidNamedCurveP384
):
501 return elliptic
.P384()
502 case oid
.Equal(oidNamedCurveP521
):
503 return elliptic
.P521()
508 func oidFromNamedCurve(curve elliptic
.Curve
) (asn1
.ObjectIdentifier
, bool) {
510 case elliptic
.P224():
511 return oidNamedCurveP224
, true
512 case elliptic
.P256():
513 return oidNamedCurveP256
, true
514 case elliptic
.P384():
515 return oidNamedCurveP384
, true
516 case elliptic
.P521():
517 return oidNamedCurveP521
, true
523 // KeyUsage represents the set of actions that are valid for a given key. It's
524 // a bitmap of the KeyUsage* constants.
528 KeyUsageDigitalSignature KeyUsage
= 1 << iota
529 KeyUsageContentCommitment
530 KeyUsageKeyEncipherment
531 KeyUsageDataEncipherment
539 // RFC 5280, 4.2.1.12 Extended Key Usage
541 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
543 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
545 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
546 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
547 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
548 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
549 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
550 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
552 oidExtKeyUsageAny
= asn1
.ObjectIdentifier
{2, 5, 29, 37, 0}
553 oidExtKeyUsageServerAuth
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 1}
554 oidExtKeyUsageClientAuth
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 2}
555 oidExtKeyUsageCodeSigning
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 3}
556 oidExtKeyUsageEmailProtection
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 4}
557 oidExtKeyUsageIPSECEndSystem
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 5}
558 oidExtKeyUsageIPSECTunnel
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 6}
559 oidExtKeyUsageIPSECUser
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 7}
560 oidExtKeyUsageTimeStamping
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 8}
561 oidExtKeyUsageOCSPSigning
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 9}
562 oidExtKeyUsageMicrosoftServerGatedCrypto
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
563 oidExtKeyUsageNetscapeServerGatedCrypto
= asn1
.ObjectIdentifier
{2, 16, 840, 1, 113730, 4, 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
585 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
586 var extKeyUsageOIDs
= []struct {
587 extKeyUsage ExtKeyUsage
588 oid asn1
.ObjectIdentifier
590 {ExtKeyUsageAny
, oidExtKeyUsageAny
},
591 {ExtKeyUsageServerAuth
, oidExtKeyUsageServerAuth
},
592 {ExtKeyUsageClientAuth
, oidExtKeyUsageClientAuth
},
593 {ExtKeyUsageCodeSigning
, oidExtKeyUsageCodeSigning
},
594 {ExtKeyUsageEmailProtection
, oidExtKeyUsageEmailProtection
},
595 {ExtKeyUsageIPSECEndSystem
, oidExtKeyUsageIPSECEndSystem
},
596 {ExtKeyUsageIPSECTunnel
, oidExtKeyUsageIPSECTunnel
},
597 {ExtKeyUsageIPSECUser
, oidExtKeyUsageIPSECUser
},
598 {ExtKeyUsageTimeStamping
, oidExtKeyUsageTimeStamping
},
599 {ExtKeyUsageOCSPSigning
, oidExtKeyUsageOCSPSigning
},
600 {ExtKeyUsageMicrosoftServerGatedCrypto
, oidExtKeyUsageMicrosoftServerGatedCrypto
},
601 {ExtKeyUsageNetscapeServerGatedCrypto
, oidExtKeyUsageNetscapeServerGatedCrypto
},
604 func extKeyUsageFromOID(oid asn1
.ObjectIdentifier
) (eku ExtKeyUsage
, ok
bool) {
605 for _
, pair
:= range extKeyUsageOIDs
{
606 if oid
.Equal(pair
.oid
) {
607 return pair
.extKeyUsage
, true
613 func oidFromExtKeyUsage(eku ExtKeyUsage
) (oid asn1
.ObjectIdentifier
, ok
bool) {
614 for _
, pair
:= range extKeyUsageOIDs
{
615 if eku
== pair
.extKeyUsage
{
616 return pair
.oid
, true
622 // A Certificate represents an X.509 certificate.
623 type Certificate
struct {
624 Raw
[]byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
625 RawTBSCertificate
[]byte // Certificate part of raw ASN.1 DER content.
626 RawSubjectPublicKeyInfo
[]byte // DER encoded SubjectPublicKeyInfo.
627 RawSubject
[]byte // DER encoded Subject
628 RawIssuer
[]byte // DER encoded Issuer
631 SignatureAlgorithm SignatureAlgorithm
633 PublicKeyAlgorithm PublicKeyAlgorithm
634 PublicKey
interface{}
637 SerialNumber
*big
.Int
640 NotBefore
, NotAfter time
.Time
// Validity bounds.
643 // Extensions contains raw X.509 extensions. When parsing certificates,
644 // this can be used to extract non-critical extensions that are not
645 // parsed by this package. When marshaling certificates, the Extensions
646 // field is ignored, see ExtraExtensions.
647 Extensions
[]pkix
.Extension
649 // ExtraExtensions contains extensions to be copied, raw, into any
650 // marshaled certificates. Values override any extensions that would
651 // otherwise be produced based on the other fields. The ExtraExtensions
652 // field is not populated when parsing certificates, see Extensions.
653 ExtraExtensions
[]pkix
.Extension
655 // UnhandledCriticalExtensions contains a list of extension IDs that
656 // were not (fully) processed when parsing. Verify will fail if this
657 // slice is non-empty, unless verification is delegated to an OS
658 // library which understands all the critical extensions.
660 // Users can access these extensions using Extensions and can remove
661 // elements from this slice if they believe that they have been
663 UnhandledCriticalExtensions
[]asn1
.ObjectIdentifier
665 ExtKeyUsage
[]ExtKeyUsage
// Sequence of extended key usages.
666 UnknownExtKeyUsage
[]asn1
.ObjectIdentifier
// Encountered extended key usages unknown to this package.
668 // BasicConstraintsValid indicates whether IsCA, MaxPathLen,
669 // and MaxPathLenZero are valid.
670 BasicConstraintsValid
bool
673 // MaxPathLen and MaxPathLenZero indicate the presence and
674 // value of the BasicConstraints' "pathLenConstraint".
676 // When parsing a certificate, a positive non-zero MaxPathLen
677 // means that the field was specified, -1 means it was unset,
678 // and MaxPathLenZero being true mean that the field was
679 // explicitly set to zero. The case of MaxPathLen==0 with MaxPathLenZero==false
680 // should be treated equivalent to -1 (unset).
682 // When generating a certificate, an unset pathLenConstraint
683 // can be requested with either MaxPathLen == -1 or using the
684 // zero value for both MaxPathLen and MaxPathLenZero.
686 // MaxPathLenZero indicates that BasicConstraintsValid==true
687 // and MaxPathLen==0 should be interpreted as an actual
688 // maximum path length of zero. Otherwise, that combination is
689 // interpreted as MaxPathLen not being set.
693 AuthorityKeyId
[]byte
695 // RFC 5280, 4.2.2.1 (Authority Information Access)
697 IssuingCertificateURL
[]string
699 // Subject Alternate Name values
701 EmailAddresses
[]string
705 PermittedDNSDomainsCritical
bool // if true then the name constraints are marked critical.
706 PermittedDNSDomains
[]string
707 ExcludedDNSDomains
[]string
709 // CRL Distribution Points
710 CRLDistributionPoints
[]string
712 PolicyIdentifiers
[]asn1
.ObjectIdentifier
715 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
716 // involves algorithms that are not currently implemented.
717 var ErrUnsupportedAlgorithm
= errors
.New("x509: cannot verify signature: algorithm unimplemented")
719 // An InsecureAlgorithmError
720 type InsecureAlgorithmError SignatureAlgorithm
722 func (e InsecureAlgorithmError
) Error() string {
723 return fmt
.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e
))
726 // ConstraintViolationError results when a requested usage is not permitted by
727 // a certificate. For example: checking a signature when the public key isn't a
728 // certificate signing key.
729 type ConstraintViolationError
struct{}
731 func (ConstraintViolationError
) Error() string {
732 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
735 func (c
*Certificate
) Equal(other
*Certificate
) bool {
736 return bytes
.Equal(c
.Raw
, other
.Raw
)
739 func (c
*Certificate
) hasSANExtension() bool {
740 return oidInExtensions(oidExtensionSubjectAltName
, c
.Extensions
)
743 // Entrust have a broken root certificate (CN=Entrust.net Certification
744 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
745 // according to PKIX.
746 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
747 // from the Basic Constraints requirement.
748 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
750 // TODO(agl): remove this hack once their reissued root is sufficiently
752 var entrustBrokenSPKI
= []byte{
753 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
754 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
755 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
756 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
757 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
758 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
759 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
760 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
761 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
762 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
763 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
764 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
765 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
766 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
767 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
768 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
769 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
770 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
771 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
772 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
773 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
774 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
775 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
776 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
777 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
778 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
779 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
780 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
781 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
782 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
783 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
784 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
785 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
786 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
787 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
788 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
789 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
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 // (except for Entrust, see comment above entrustBrokenSPKI)
801 if (parent
.Version
== 3 && !parent
.BasicConstraintsValid ||
802 parent
.BasicConstraintsValid
&& !parent
.IsCA
) &&
803 !bytes
.Equal(c
.RawSubjectPublicKeyInfo
, entrustBrokenSPKI
) {
804 return ConstraintViolationError
{}
807 if parent
.KeyUsage
!= 0 && parent
.KeyUsage
&KeyUsageCertSign
== 0 {
808 return ConstraintViolationError
{}
811 if parent
.PublicKeyAlgorithm
== UnknownPublicKeyAlgorithm
{
812 return ErrUnsupportedAlgorithm
815 // TODO(agl): don't ignore the path length constraint.
817 return parent
.CheckSignature(c
.SignatureAlgorithm
, c
.RawTBSCertificate
, c
.Signature
)
820 // CheckSignature verifies that signature is a valid signature over signed from
822 func (c
*Certificate
) CheckSignature(algo SignatureAlgorithm
, signed
, signature
[]byte) error
{
823 return checkSignature(algo
, signed
, signature
, c
.PublicKey
)
826 // CheckSignature verifies that signature is a valid signature over signed from
827 // a crypto.PublicKey.
828 func checkSignature(algo SignatureAlgorithm
, signed
, signature
[]byte, publicKey crypto
.PublicKey
) (err error
) {
829 var hashType crypto
.Hash
832 case SHA1WithRSA
, DSAWithSHA1
, ECDSAWithSHA1
:
833 hashType
= crypto
.SHA1
834 case SHA256WithRSA
, SHA256WithRSAPSS
, DSAWithSHA256
, ECDSAWithSHA256
:
835 hashType
= crypto
.SHA256
836 case SHA384WithRSA
, SHA384WithRSAPSS
, ECDSAWithSHA384
:
837 hashType
= crypto
.SHA384
838 case SHA512WithRSA
, SHA512WithRSAPSS
, ECDSAWithSHA512
:
839 hashType
= crypto
.SHA512
840 case MD2WithRSA
, MD5WithRSA
:
841 return InsecureAlgorithmError(algo
)
843 return ErrUnsupportedAlgorithm
846 if !hashType
.Available() {
847 return ErrUnsupportedAlgorithm
854 switch pub
:= publicKey
.(type) {
857 return rsa
.VerifyPSS(pub
, hashType
, digest
, signature
, &rsa
.PSSOptions
{SaltLength
: rsa
.PSSSaltLengthEqualsHash
})
859 return rsa
.VerifyPKCS1v15(pub
, hashType
, digest
, signature
)
862 dsaSig
:= new(dsaSignature
)
863 if rest
, err
:= asn1
.Unmarshal(signature
, dsaSig
); err
!= nil {
865 } else if len(rest
) != 0 {
866 return errors
.New("x509: trailing data after DSA signature")
868 if dsaSig
.R
.Sign() <= 0 || dsaSig
.S
.Sign() <= 0 {
869 return errors
.New("x509: DSA signature contained zero or negative values")
871 if !dsa
.Verify(pub
, digest
, dsaSig
.R
, dsaSig
.S
) {
872 return errors
.New("x509: DSA verification failure")
875 case *ecdsa
.PublicKey
:
876 ecdsaSig
:= new(ecdsaSignature
)
877 if rest
, err
:= asn1
.Unmarshal(signature
, ecdsaSig
); err
!= nil {
879 } else if len(rest
) != 0 {
880 return errors
.New("x509: trailing data after ECDSA signature")
882 if ecdsaSig
.R
.Sign() <= 0 || ecdsaSig
.S
.Sign() <= 0 {
883 return errors
.New("x509: ECDSA signature contained zero or negative values")
885 if !ecdsa
.Verify(pub
, digest
, ecdsaSig
.R
, ecdsaSig
.S
) {
886 return errors
.New("x509: ECDSA verification failure")
890 return ErrUnsupportedAlgorithm
893 // CheckCRLSignature checks that the signature in crl is from c.
894 func (c
*Certificate
) CheckCRLSignature(crl
*pkix
.CertificateList
) error
{
895 algo
:= getSignatureAlgorithmFromAI(crl
.SignatureAlgorithm
)
896 return c
.CheckSignature(algo
, crl
.TBSCertList
.Raw
, crl
.SignatureValue
.RightAlign())
899 type UnhandledCriticalExtension
struct{}
901 func (h UnhandledCriticalExtension
) Error() string {
902 return "x509: unhandled critical extension"
905 type basicConstraints
struct {
906 IsCA
bool `asn1:"optional"`
907 MaxPathLen
int `asn1:"optional,default:-1"`
911 type policyInformation
struct {
912 Policy asn1
.ObjectIdentifier
913 // policyQualifiers omitted
916 // RFC 5280, 4.2.1.10
917 type nameConstraints
struct {
918 Permitted
[]generalSubtree
`asn1:"optional,tag:0"`
919 Excluded
[]generalSubtree
`asn1:"optional,tag:1"`
922 type generalSubtree
struct {
923 Name
string `asn1:"tag:2,optional,ia5"`
927 type authorityInfoAccess
struct {
928 Method asn1
.ObjectIdentifier
929 Location asn1
.RawValue
932 // RFC 5280, 4.2.1.14
933 type distributionPoint
struct {
934 DistributionPoint distributionPointName
`asn1:"optional,tag:0"`
935 Reason asn1
.BitString
`asn1:"optional,tag:1"`
936 CRLIssuer asn1
.RawValue
`asn1:"optional,tag:2"`
939 type distributionPointName
struct {
940 FullName asn1
.RawValue
`asn1:"optional,tag:0"`
941 RelativeName pkix
.RDNSequence
`asn1:"optional,tag:1"`
944 func parsePublicKey(algo PublicKeyAlgorithm
, keyData
*publicKeyInfo
) (interface{}, error
) {
945 asn1Data
:= keyData
.PublicKey
.RightAlign()
948 // RSA public keys must have a NULL in the parameters
949 // (https://tools.ietf.org/html/rfc3279#section-2.3.1).
950 if !bytes
.Equal(keyData
.Algorithm
.Parameters
.FullBytes
, asn1
.NullBytes
) {
951 return nil, errors
.New("x509: RSA key missing NULL parameters")
954 p
:= new(pkcs1PublicKey
)
955 rest
, err
:= asn1
.Unmarshal(asn1Data
, p
)
960 return nil, errors
.New("x509: trailing data after RSA public key")
964 return nil, errors
.New("x509: RSA modulus is not a positive number")
967 return nil, errors
.New("x509: RSA public exponent is not a positive number")
970 pub
:= &rsa
.PublicKey
{
977 rest
, err
:= asn1
.Unmarshal(asn1Data
, &p
)
982 return nil, errors
.New("x509: trailing data after DSA public key")
984 paramsData
:= keyData
.Algorithm
.Parameters
.FullBytes
985 params
:= new(dsaAlgorithmParameters
)
986 rest
, err
= asn1
.Unmarshal(paramsData
, params
)
991 return nil, errors
.New("x509: trailing data after DSA parameters")
993 if p
.Sign() <= 0 || params
.P
.Sign() <= 0 || params
.Q
.Sign() <= 0 || params
.G
.Sign() <= 0 {
994 return nil, errors
.New("x509: zero or negative DSA parameter")
996 pub
:= &dsa
.PublicKey
{
997 Parameters
: dsa
.Parameters
{
1006 paramsData
:= keyData
.Algorithm
.Parameters
.FullBytes
1007 namedCurveOID
:= new(asn1
.ObjectIdentifier
)
1008 rest
, err
:= asn1
.Unmarshal(paramsData
, namedCurveOID
)
1013 return nil, errors
.New("x509: trailing data after ECDSA parameters")
1015 namedCurve
:= namedCurveFromOID(*namedCurveOID
)
1016 if namedCurve
== nil {
1017 return nil, errors
.New("x509: unsupported elliptic curve")
1019 x
, y
:= elliptic
.Unmarshal(namedCurve
, asn1Data
)
1021 return nil, errors
.New("x509: failed to unmarshal elliptic curve point")
1023 pub
:= &ecdsa
.PublicKey
{
1034 func parseSANExtension(value
[]byte) (dnsNames
, emailAddresses
[]string, ipAddresses
[]net
.IP
, err error
) {
1035 // RFC 5280, 4.2.1.6
1037 // SubjectAltName ::= GeneralNames
1039 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1041 // GeneralName ::= CHOICE {
1042 // otherName [0] OtherName,
1043 // rfc822Name [1] IA5String,
1044 // dNSName [2] IA5String,
1045 // x400Address [3] ORAddress,
1046 // directoryName [4] Name,
1047 // ediPartyName [5] EDIPartyName,
1048 // uniformResourceIdentifier [6] IA5String,
1049 // iPAddress [7] OCTET STRING,
1050 // registeredID [8] OBJECT IDENTIFIER }
1051 var seq asn1
.RawValue
1053 if rest
, err
= asn1
.Unmarshal(value
, &seq
); err
!= nil {
1055 } else if len(rest
) != 0 {
1056 err
= errors
.New("x509: trailing data after X.509 extension")
1059 if !seq
.IsCompound || seq
.Tag
!= 16 || seq
.Class
!= 0 {
1060 err
= asn1
.StructuralError
{Msg
: "bad SAN sequence"}
1067 rest
, err
= asn1
.Unmarshal(rest
, &v
)
1073 emailAddresses
= append(emailAddresses
, string(v
.Bytes
))
1075 dnsNames
= append(dnsNames
, string(v
.Bytes
))
1077 switch len(v
.Bytes
) {
1078 case net
.IPv4len
, net
.IPv6len
:
1079 ipAddresses
= append(ipAddresses
, v
.Bytes
)
1081 err
= errors
.New("x509: certificate contained IP address of length " + strconv
.Itoa(len(v
.Bytes
)))
1090 func parseCertificate(in
*certificate
) (*Certificate
, error
) {
1091 out
:= new(Certificate
)
1093 out
.RawTBSCertificate
= in
.TBSCertificate
.Raw
1094 out
.RawSubjectPublicKeyInfo
= in
.TBSCertificate
.PublicKey
.Raw
1095 out
.RawSubject
= in
.TBSCertificate
.Subject
.FullBytes
1096 out
.RawIssuer
= in
.TBSCertificate
.Issuer
.FullBytes
1098 out
.Signature
= in
.SignatureValue
.RightAlign()
1099 out
.SignatureAlgorithm
=
1100 getSignatureAlgorithmFromAI(in
.TBSCertificate
.SignatureAlgorithm
)
1102 out
.PublicKeyAlgorithm
=
1103 getPublicKeyAlgorithmFromOID(in
.TBSCertificate
.PublicKey
.Algorithm
.Algorithm
)
1105 out
.PublicKey
, err
= parsePublicKey(out
.PublicKeyAlgorithm
, &in
.TBSCertificate
.PublicKey
)
1110 out
.Version
= in
.TBSCertificate
.Version
+ 1
1111 out
.SerialNumber
= in
.TBSCertificate
.SerialNumber
1113 var issuer
, subject pkix
.RDNSequence
1114 if rest
, err
:= asn1
.Unmarshal(in
.TBSCertificate
.Subject
.FullBytes
, &subject
); err
!= nil {
1116 } else if len(rest
) != 0 {
1117 return nil, errors
.New("x509: trailing data after X.509 subject")
1119 if rest
, err
:= asn1
.Unmarshal(in
.TBSCertificate
.Issuer
.FullBytes
, &issuer
); err
!= nil {
1121 } else if len(rest
) != 0 {
1122 return nil, errors
.New("x509: trailing data after X.509 subject")
1125 out
.Issuer
.FillFromRDNSequence(&issuer
)
1126 out
.Subject
.FillFromRDNSequence(&subject
)
1128 out
.NotBefore
= in
.TBSCertificate
.Validity
.NotBefore
1129 out
.NotAfter
= in
.TBSCertificate
.Validity
.NotAfter
1131 for _
, e
:= range in
.TBSCertificate
.Extensions
{
1132 out
.Extensions
= append(out
.Extensions
, e
)
1135 if len(e
.Id
) == 4 && e
.Id
[0] == 2 && e
.Id
[1] == 5 && e
.Id
[2] == 29 {
1138 // RFC 5280, 4.2.1.3
1139 var usageBits asn1
.BitString
1140 if rest
, err
:= asn1
.Unmarshal(e
.Value
, &usageBits
); err
!= nil {
1142 } else if len(rest
) != 0 {
1143 return nil, errors
.New("x509: trailing data after X.509 KeyUsage")
1147 for i
:= 0; i
< 9; i
++ {
1148 if usageBits
.At(i
) != 0 {
1149 usage |
= 1 << uint(i
)
1152 out
.KeyUsage
= KeyUsage(usage
)
1155 // RFC 5280, 4.2.1.9
1156 var constraints basicConstraints
1157 if rest
, err
:= asn1
.Unmarshal(e
.Value
, &constraints
); err
!= nil {
1159 } else if len(rest
) != 0 {
1160 return nil, errors
.New("x509: trailing data after X.509 BasicConstraints")
1163 out
.BasicConstraintsValid
= true
1164 out
.IsCA
= constraints
.IsCA
1165 out
.MaxPathLen
= constraints
.MaxPathLen
1166 out
.MaxPathLenZero
= out
.MaxPathLen
== 0
1167 // TODO: map out.MaxPathLen to 0 if it has the -1 default value? (Issue 19285)
1169 out
.DNSNames
, out
.EmailAddresses
, out
.IPAddresses
, err
= parseSANExtension(e
.Value
)
1174 if len(out
.DNSNames
) == 0 && len(out
.EmailAddresses
) == 0 && len(out
.IPAddresses
) == 0 {
1175 // If we didn't parse anything then we do the critical check, below.
1180 // RFC 5280, 4.2.1.10
1182 // NameConstraints ::= SEQUENCE {
1183 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
1184 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
1186 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
1188 // GeneralSubtree ::= SEQUENCE {
1189 // base GeneralName,
1190 // minimum [0] BaseDistance DEFAULT 0,
1191 // maximum [1] BaseDistance OPTIONAL }
1193 // BaseDistance ::= INTEGER (0..MAX)
1195 var constraints nameConstraints
1196 if rest
, err
:= asn1
.Unmarshal(e
.Value
, &constraints
); err
!= nil {
1198 } else if len(rest
) != 0 {
1199 return nil, errors
.New("x509: trailing data after X.509 NameConstraints")
1202 getDNSNames
:= func(subtrees
[]generalSubtree
, isCritical
bool) (dnsNames
[]string, err error
) {
1203 for _
, subtree
:= range subtrees
{
1204 if len(subtree
.Name
) == 0 {
1206 return nil, UnhandledCriticalExtension
{}
1210 dnsNames
= append(dnsNames
, subtree
.Name
)
1213 return dnsNames
, nil
1216 if out
.PermittedDNSDomains
, err
= getDNSNames(constraints
.Permitted
, e
.Critical
); err
!= nil {
1219 if out
.ExcludedDNSDomains
, err
= getDNSNames(constraints
.Excluded
, e
.Critical
); err
!= nil {
1222 out
.PermittedDNSDomainsCritical
= e
.Critical
1225 // RFC 5280, 4.2.1.13
1227 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1229 // DistributionPoint ::= SEQUENCE {
1230 // distributionPoint [0] DistributionPointName OPTIONAL,
1231 // reasons [1] ReasonFlags OPTIONAL,
1232 // cRLIssuer [2] GeneralNames OPTIONAL }
1234 // DistributionPointName ::= CHOICE {
1235 // fullName [0] GeneralNames,
1236 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
1238 var cdp
[]distributionPoint
1239 if rest
, err
:= asn1
.Unmarshal(e
.Value
, &cdp
); err
!= nil {
1241 } else if len(rest
) != 0 {
1242 return nil, errors
.New("x509: trailing data after X.509 CRL distribution point")
1245 for _
, dp
:= range cdp
{
1246 // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
1247 if len(dp
.DistributionPoint
.FullName
.Bytes
) == 0 {
1252 if _
, err
:= asn1
.Unmarshal(dp
.DistributionPoint
.FullName
.Bytes
, &n
); err
!= nil {
1255 // Trailing data after the fullName is
1256 // allowed because other elements of
1257 // the SEQUENCE can appear.
1260 out
.CRLDistributionPoints
= append(out
.CRLDistributionPoints
, string(n
.Bytes
))
1265 // RFC 5280, 4.2.1.1
1267 if rest
, err
:= asn1
.Unmarshal(e
.Value
, &a
); err
!= nil {
1269 } else if len(rest
) != 0 {
1270 return nil, errors
.New("x509: trailing data after X.509 authority key-id")
1272 out
.AuthorityKeyId
= a
.Id
1275 // RFC 5280, 4.2.1.12. Extended Key Usage
1277 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1279 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1281 // KeyPurposeId ::= OBJECT IDENTIFIER
1283 var keyUsage
[]asn1
.ObjectIdentifier
1284 if rest
, err
:= asn1
.Unmarshal(e
.Value
, &keyUsage
); err
!= nil {
1286 } else if len(rest
) != 0 {
1287 return nil, errors
.New("x509: trailing data after X.509 ExtendedKeyUsage")
1290 for _
, u
:= range keyUsage
{
1291 if extKeyUsage
, ok
:= extKeyUsageFromOID(u
); ok
{
1292 out
.ExtKeyUsage
= append(out
.ExtKeyUsage
, extKeyUsage
)
1294 out
.UnknownExtKeyUsage
= append(out
.UnknownExtKeyUsage
, u
)
1299 // RFC 5280, 4.2.1.2
1301 if rest
, err
:= asn1
.Unmarshal(e
.Value
, &keyid
); err
!= nil {
1303 } else if len(rest
) != 0 {
1304 return nil, errors
.New("x509: trailing data after X.509 key-id")
1306 out
.SubjectKeyId
= keyid
1309 // RFC 5280 4.2.1.4: Certificate Policies
1310 var policies
[]policyInformation
1311 if rest
, err
:= asn1
.Unmarshal(e
.Value
, &policies
); err
!= nil {
1313 } else if len(rest
) != 0 {
1314 return nil, errors
.New("x509: trailing data after X.509 certificate policies")
1316 out
.PolicyIdentifiers
= make([]asn1
.ObjectIdentifier
, len(policies
))
1317 for i
, policy
:= range policies
{
1318 out
.PolicyIdentifiers
[i
] = policy
.Policy
1322 // Unknown extensions are recorded if critical.
1325 } else if e
.Id
.Equal(oidExtensionAuthorityInfoAccess
) {
1326 // RFC 5280 4.2.2.1: Authority Information Access
1327 var aia
[]authorityInfoAccess
1328 if rest
, err
:= asn1
.Unmarshal(e
.Value
, &aia
); err
!= nil {
1330 } else if len(rest
) != 0 {
1331 return nil, errors
.New("x509: trailing data after X.509 authority information")
1334 for _
, v
:= range aia
{
1335 // GeneralName: uniformResourceIdentifier [6] IA5String
1336 if v
.Location
.Tag
!= 6 {
1339 if v
.Method
.Equal(oidAuthorityInfoAccessOcsp
) {
1340 out
.OCSPServer
= append(out
.OCSPServer
, string(v
.Location
.Bytes
))
1341 } else if v
.Method
.Equal(oidAuthorityInfoAccessIssuers
) {
1342 out
.IssuingCertificateURL
= append(out
.IssuingCertificateURL
, string(v
.Location
.Bytes
))
1346 // Unknown extensions are recorded if critical.
1350 if e
.Critical
&& unhandled
{
1351 out
.UnhandledCriticalExtensions
= append(out
.UnhandledCriticalExtensions
, e
.Id
)
1358 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1359 func ParseCertificate(asn1Data
[]byte) (*Certificate
, error
) {
1360 var cert certificate
1361 rest
, err
:= asn1
.Unmarshal(asn1Data
, &cert
)
1366 return nil, asn1
.SyntaxError
{Msg
: "trailing data"}
1369 return parseCertificate(&cert
)
1372 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1373 // data. The certificates must be concatenated with no intermediate padding.
1374 func ParseCertificates(asn1Data
[]byte) ([]*Certificate
, error
) {
1375 var v
[]*certificate
1377 for len(asn1Data
) > 0 {
1378 cert
:= new(certificate
)
1380 asn1Data
, err
= asn1
.Unmarshal(asn1Data
, cert
)
1387 ret
:= make([]*Certificate
, len(v
))
1388 for i
, ci
:= range v
{
1389 cert
, err
:= parseCertificate(ci
)
1399 func reverseBitsInAByte(in
byte) byte {
1401 b2
:= b1
>>2&0x33 | b1
<<2&0xcc
1402 b3
:= b2
>>1&0x55 | b2
<<1&0xaa
1406 // asn1BitLength returns the bit-length of bitString by considering the
1407 // most-significant bit in a byte to be the "first" bit. This convention
1408 // matches ASN.1, but differs from almost everything else.
1409 func asn1BitLength(bitString
[]byte) int {
1410 bitLen
:= len(bitString
) * 8
1412 for i
:= range bitString
{
1413 b
:= bitString
[len(bitString
)-i
-1]
1415 for bit
:= uint(0); bit
< 8; bit
++ {
1416 if (b
>>bit
)&1 == 1 {
1427 oidExtensionSubjectKeyId
= []int{2, 5, 29, 14}
1428 oidExtensionKeyUsage
= []int{2, 5, 29, 15}
1429 oidExtensionExtendedKeyUsage
= []int{2, 5, 29, 37}
1430 oidExtensionAuthorityKeyId
= []int{2, 5, 29, 35}
1431 oidExtensionBasicConstraints
= []int{2, 5, 29, 19}
1432 oidExtensionSubjectAltName
= []int{2, 5, 29, 17}
1433 oidExtensionCertificatePolicies
= []int{2, 5, 29, 32}
1434 oidExtensionNameConstraints
= []int{2, 5, 29, 30}
1435 oidExtensionCRLDistributionPoints
= []int{2, 5, 29, 31}
1436 oidExtensionAuthorityInfoAccess
= []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1440 oidAuthorityInfoAccessOcsp
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 48, 1}
1441 oidAuthorityInfoAccessIssuers
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 48, 2}
1444 // oidNotInExtensions returns whether an extension with the given oid exists in
1446 func oidInExtensions(oid asn1
.ObjectIdentifier
, extensions
[]pkix
.Extension
) bool {
1447 for _
, e
:= range extensions
{
1448 if e
.Id
.Equal(oid
) {
1455 // marshalSANs marshals a list of addresses into a the contents of an X.509
1456 // SubjectAlternativeName extension.
1457 func marshalSANs(dnsNames
, emailAddresses
[]string, ipAddresses
[]net
.IP
) (derBytes
[]byte, err error
) {
1458 var rawValues
[]asn1
.RawValue
1459 for _
, name
:= range dnsNames
{
1460 rawValues
= append(rawValues
, asn1
.RawValue
{Tag
: 2, Class
: 2, Bytes
: []byte(name
)})
1462 for _
, email
:= range emailAddresses
{
1463 rawValues
= append(rawValues
, asn1
.RawValue
{Tag
: 1, Class
: 2, Bytes
: []byte(email
)})
1465 for _
, rawIP
:= range ipAddresses
{
1466 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1471 rawValues
= append(rawValues
, asn1
.RawValue
{Tag
: 7, Class
: 2, Bytes
: ip
})
1473 return asn1
.Marshal(rawValues
)
1476 func buildExtensions(template
*Certificate
, authorityKeyId
[]byte) (ret
[]pkix
.Extension
, err error
) {
1477 ret
= make([]pkix
.Extension
, 10 /* maximum number of elements. */)
1480 if template
.KeyUsage
!= 0 &&
1481 !oidInExtensions(oidExtensionKeyUsage
, template
.ExtraExtensions
) {
1482 ret
[n
].Id
= oidExtensionKeyUsage
1483 ret
[n
].Critical
= true
1486 a
[0] = reverseBitsInAByte(byte(template
.KeyUsage
))
1487 a
[1] = reverseBitsInAByte(byte(template
.KeyUsage
>> 8))
1495 ret
[n
].Value
, err
= asn1
.Marshal(asn1
.BitString
{Bytes
: bitString
, BitLength
: asn1BitLength(bitString
)})
1502 if (len(template
.ExtKeyUsage
) > 0 ||
len(template
.UnknownExtKeyUsage
) > 0) &&
1503 !oidInExtensions(oidExtensionExtendedKeyUsage
, template
.ExtraExtensions
) {
1504 ret
[n
].Id
= oidExtensionExtendedKeyUsage
1506 var oids
[]asn1
.ObjectIdentifier
1507 for _
, u
:= range template
.ExtKeyUsage
{
1508 if oid
, ok
:= oidFromExtKeyUsage(u
); ok
{
1509 oids
= append(oids
, oid
)
1511 panic("internal error")
1515 oids
= append(oids
, template
.UnknownExtKeyUsage
...)
1517 ret
[n
].Value
, err
= asn1
.Marshal(oids
)
1524 if template
.BasicConstraintsValid
&& !oidInExtensions(oidExtensionBasicConstraints
, template
.ExtraExtensions
) {
1525 // Leaving MaxPathLen as zero indicates that no maximum path
1526 // length is desired, unless MaxPathLenZero is set. A value of
1527 // -1 causes encoding/asn1 to omit the value as desired.
1528 maxPathLen
:= template
.MaxPathLen
1529 if maxPathLen
== 0 && !template
.MaxPathLenZero
{
1532 ret
[n
].Id
= oidExtensionBasicConstraints
1533 ret
[n
].Value
, err
= asn1
.Marshal(basicConstraints
{template
.IsCA
, maxPathLen
})
1534 ret
[n
].Critical
= true
1541 if len(template
.SubjectKeyId
) > 0 && !oidInExtensions(oidExtensionSubjectKeyId
, template
.ExtraExtensions
) {
1542 ret
[n
].Id
= oidExtensionSubjectKeyId
1543 ret
[n
].Value
, err
= asn1
.Marshal(template
.SubjectKeyId
)
1550 if len(authorityKeyId
) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId
, template
.ExtraExtensions
) {
1551 ret
[n
].Id
= oidExtensionAuthorityKeyId
1552 ret
[n
].Value
, err
= asn1
.Marshal(authKeyId
{authorityKeyId
})
1559 if (len(template
.OCSPServer
) > 0 ||
len(template
.IssuingCertificateURL
) > 0) &&
1560 !oidInExtensions(oidExtensionAuthorityInfoAccess
, template
.ExtraExtensions
) {
1561 ret
[n
].Id
= oidExtensionAuthorityInfoAccess
1562 var aiaValues
[]authorityInfoAccess
1563 for _
, name
:= range template
.OCSPServer
{
1564 aiaValues
= append(aiaValues
, authorityInfoAccess
{
1565 Method
: oidAuthorityInfoAccessOcsp
,
1566 Location
: asn1
.RawValue
{Tag
: 6, Class
: 2, Bytes
: []byte(name
)},
1569 for _
, name
:= range template
.IssuingCertificateURL
{
1570 aiaValues
= append(aiaValues
, authorityInfoAccess
{
1571 Method
: oidAuthorityInfoAccessIssuers
,
1572 Location
: asn1
.RawValue
{Tag
: 6, Class
: 2, Bytes
: []byte(name
)},
1575 ret
[n
].Value
, err
= asn1
.Marshal(aiaValues
)
1582 if (len(template
.DNSNames
) > 0 ||
len(template
.EmailAddresses
) > 0 ||
len(template
.IPAddresses
) > 0) &&
1583 !oidInExtensions(oidExtensionSubjectAltName
, template
.ExtraExtensions
) {
1584 ret
[n
].Id
= oidExtensionSubjectAltName
1585 ret
[n
].Value
, err
= marshalSANs(template
.DNSNames
, template
.EmailAddresses
, template
.IPAddresses
)
1592 if len(template
.PolicyIdentifiers
) > 0 &&
1593 !oidInExtensions(oidExtensionCertificatePolicies
, template
.ExtraExtensions
) {
1594 ret
[n
].Id
= oidExtensionCertificatePolicies
1595 policies
:= make([]policyInformation
, len(template
.PolicyIdentifiers
))
1596 for i
, policy
:= range template
.PolicyIdentifiers
{
1597 policies
[i
].Policy
= policy
1599 ret
[n
].Value
, err
= asn1
.Marshal(policies
)
1606 if (len(template
.PermittedDNSDomains
) > 0 ||
len(template
.ExcludedDNSDomains
) > 0) &&
1607 !oidInExtensions(oidExtensionNameConstraints
, template
.ExtraExtensions
) {
1608 ret
[n
].Id
= oidExtensionNameConstraints
1609 ret
[n
].Critical
= template
.PermittedDNSDomainsCritical
1611 var out nameConstraints
1613 out
.Permitted
= make([]generalSubtree
, len(template
.PermittedDNSDomains
))
1614 for i
, permitted
:= range template
.PermittedDNSDomains
{
1615 out
.Permitted
[i
] = generalSubtree
{Name
: permitted
}
1617 out
.Excluded
= make([]generalSubtree
, len(template
.ExcludedDNSDomains
))
1618 for i
, excluded
:= range template
.ExcludedDNSDomains
{
1619 out
.Excluded
[i
] = generalSubtree
{Name
: excluded
}
1622 ret
[n
].Value
, err
= asn1
.Marshal(out
)
1629 if len(template
.CRLDistributionPoints
) > 0 &&
1630 !oidInExtensions(oidExtensionCRLDistributionPoints
, template
.ExtraExtensions
) {
1631 ret
[n
].Id
= oidExtensionCRLDistributionPoints
1633 var crlDp
[]distributionPoint
1634 for _
, name
:= range template
.CRLDistributionPoints
{
1635 rawFullName
, _
:= asn1
.Marshal(asn1
.RawValue
{Tag
: 6, Class
: 2, Bytes
: []byte(name
)})
1637 dp
:= distributionPoint
{
1638 DistributionPoint
: distributionPointName
{
1639 FullName
: asn1
.RawValue
{Tag
: 0, Class
: 2, IsCompound
: true, Bytes
: rawFullName
},
1642 crlDp
= append(crlDp
, dp
)
1645 ret
[n
].Value
, err
= asn1
.Marshal(crlDp
)
1652 // Adding another extension here? Remember to update the maximum number
1653 // of elements in the make() at the top of the function.
1655 return append(ret
[:n
], template
.ExtraExtensions
...), nil
1658 func subjectBytes(cert
*Certificate
) ([]byte, error
) {
1659 if len(cert
.RawSubject
) > 0 {
1660 return cert
.RawSubject
, nil
1663 return asn1
.Marshal(cert
.Subject
.ToRDNSequence())
1666 // signingParamsForPublicKey returns the parameters to use for signing with
1667 // priv. If requestedSigAlgo is not zero then it overrides the default
1668 // signature algorithm.
1669 func signingParamsForPublicKey(pub
interface{}, requestedSigAlgo SignatureAlgorithm
) (hashFunc crypto
.Hash
, sigAlgo pkix
.AlgorithmIdentifier
, err error
) {
1670 var pubType PublicKeyAlgorithm
1672 switch pub
:= pub
.(type) {
1673 case *rsa
.PublicKey
:
1675 hashFunc
= crypto
.SHA256
1676 sigAlgo
.Algorithm
= oidSignatureSHA256WithRSA
1677 sigAlgo
.Parameters
= asn1
.NullRawValue
1679 case *ecdsa
.PublicKey
:
1683 case elliptic
.P224(), elliptic
.P256():
1684 hashFunc
= crypto
.SHA256
1685 sigAlgo
.Algorithm
= oidSignatureECDSAWithSHA256
1686 case elliptic
.P384():
1687 hashFunc
= crypto
.SHA384
1688 sigAlgo
.Algorithm
= oidSignatureECDSAWithSHA384
1689 case elliptic
.P521():
1690 hashFunc
= crypto
.SHA512
1691 sigAlgo
.Algorithm
= oidSignatureECDSAWithSHA512
1693 err
= errors
.New("x509: unknown elliptic curve")
1697 err
= errors
.New("x509: only RSA and ECDSA keys supported")
1704 if requestedSigAlgo
== 0 {
1709 for _
, details
:= range signatureAlgorithmDetails
{
1710 if details
.algo
== requestedSigAlgo
{
1711 if details
.pubKeyAlgo
!= pubType
{
1712 err
= errors
.New("x509: requested SignatureAlgorithm does not match private key type")
1715 sigAlgo
.Algorithm
, hashFunc
= details
.oid
, details
.hash
1717 err
= errors
.New("x509: cannot sign with hash function requested")
1720 if requestedSigAlgo
.isRSAPSS() {
1721 sigAlgo
.Parameters
= rsaPSSParameters(hashFunc
)
1729 err
= errors
.New("x509: unknown SignatureAlgorithm")
1735 // CreateCertificate creates a new certificate based on a template.
1736 // The following members of template are used: AuthorityKeyId,
1737 // BasicConstraintsValid, DNSNames, ExcludedDNSDomains, ExtKeyUsage,
1738 // IsCA, KeyUsage, MaxPathLen, MaxPathLenZero, NotAfter, NotBefore,
1739 // PermittedDNSDomains, PermittedDNSDomainsCritical, SerialNumber,
1740 // SignatureAlgorithm, Subject, SubjectKeyId, and UnknownExtKeyUsage.
1742 // The certificate is signed by parent. If parent is equal to template then the
1743 // certificate is self-signed. The parameter pub is the public key of the
1744 // signee and priv is the private key of the signer.
1746 // The returned slice is the certificate in DER encoding.
1748 // All keys types that are implemented via crypto.Signer are supported (This
1749 // includes *rsa.PublicKey and *ecdsa.PublicKey.)
1751 // The AuthorityKeyId will be taken from the SubjectKeyId of parent, if any,
1752 // unless the resulting certificate is self-signed. Otherwise the value from
1753 // template will be used.
1754 func CreateCertificate(rand io
.Reader
, template
, parent
*Certificate
, pub
, priv
interface{}) (cert
[]byte, err error
) {
1755 key
, ok
:= priv
.(crypto
.Signer
)
1757 return nil, errors
.New("x509: certificate private key does not implement crypto.Signer")
1760 if template
.SerialNumber
== nil {
1761 return nil, errors
.New("x509: no SerialNumber given")
1764 hashFunc
, signatureAlgorithm
, err
:= signingParamsForPublicKey(key
.Public(), template
.SignatureAlgorithm
)
1769 publicKeyBytes
, publicKeyAlgorithm
, err
:= marshalPublicKey(pub
)
1774 asn1Issuer
, err
:= subjectBytes(parent
)
1779 asn1Subject
, err
:= subjectBytes(template
)
1784 authorityKeyId
:= template
.AuthorityKeyId
1785 if !bytes
.Equal(asn1Issuer
, asn1Subject
) && len(parent
.SubjectKeyId
) > 0 {
1786 authorityKeyId
= parent
.SubjectKeyId
1789 extensions
, err
:= buildExtensions(template
, authorityKeyId
)
1794 encodedPublicKey
:= asn1
.BitString
{BitLength
: len(publicKeyBytes
) * 8, Bytes
: publicKeyBytes
}
1795 c
:= tbsCertificate
{
1797 SerialNumber
: template
.SerialNumber
,
1798 SignatureAlgorithm
: signatureAlgorithm
,
1799 Issuer
: asn1
.RawValue
{FullBytes
: asn1Issuer
},
1800 Validity
: validity
{template
.NotBefore
.UTC(), template
.NotAfter
.UTC()},
1801 Subject
: asn1
.RawValue
{FullBytes
: asn1Subject
},
1802 PublicKey
: publicKeyInfo
{nil, publicKeyAlgorithm
, encodedPublicKey
},
1803 Extensions
: extensions
,
1806 tbsCertContents
, err
:= asn1
.Marshal(c
)
1811 c
.Raw
= tbsCertContents
1814 h
.Write(tbsCertContents
)
1815 digest
:= h
.Sum(nil)
1817 var signerOpts crypto
.SignerOpts
1818 signerOpts
= hashFunc
1819 if template
.SignatureAlgorithm
!= 0 && template
.SignatureAlgorithm
.isRSAPSS() {
1820 signerOpts
= &rsa
.PSSOptions
{
1821 SaltLength
: rsa
.PSSSaltLengthEqualsHash
,
1826 var signature
[]byte
1827 signature
, err
= key
.Sign(rand
, digest
, signerOpts
)
1832 return asn1
.Marshal(certificate
{
1836 asn1
.BitString
{Bytes
: signature
, BitLength
: len(signature
) * 8},
1840 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1842 var pemCRLPrefix
= []byte("-----BEGIN X509 CRL")
1844 // pemType is the type of a PEM encoded CRL.
1845 var pemType
= "X509 CRL"
1847 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1848 // encoded CRLs will appear where they should be DER encoded, so this function
1849 // will transparently handle PEM encoding as long as there isn't any leading
1851 func ParseCRL(crlBytes
[]byte) (*pkix
.CertificateList
, error
) {
1852 if bytes
.HasPrefix(crlBytes
, pemCRLPrefix
) {
1853 block
, _
:= pem
.Decode(crlBytes
)
1854 if block
!= nil && block
.Type
== pemType
{
1855 crlBytes
= block
.Bytes
1858 return ParseDERCRL(crlBytes
)
1861 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1862 func ParseDERCRL(derBytes
[]byte) (*pkix
.CertificateList
, error
) {
1863 certList
:= new(pkix
.CertificateList
)
1864 if rest
, err
:= asn1
.Unmarshal(derBytes
, certList
); err
!= nil {
1866 } else if len(rest
) != 0 {
1867 return nil, errors
.New("x509: trailing data after CRL")
1869 return certList
, nil
1872 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1873 // contains the given list of revoked certificates.
1874 func (c
*Certificate
) CreateCRL(rand io
.Reader
, priv
interface{}, revokedCerts
[]pkix
.RevokedCertificate
, now
, expiry time
.Time
) (crlBytes
[]byte, err error
) {
1875 key
, ok
:= priv
.(crypto
.Signer
)
1877 return nil, errors
.New("x509: certificate private key does not implement crypto.Signer")
1880 hashFunc
, signatureAlgorithm
, err
:= signingParamsForPublicKey(key
.Public(), 0)
1885 // Force revocation times to UTC per RFC 5280.
1886 revokedCertsUTC
:= make([]pkix
.RevokedCertificate
, len(revokedCerts
))
1887 for i
, rc
:= range revokedCerts
{
1888 rc
.RevocationTime
= rc
.RevocationTime
.UTC()
1889 revokedCertsUTC
[i
] = rc
1892 tbsCertList
:= pkix
.TBSCertificateList
{
1894 Signature
: signatureAlgorithm
,
1895 Issuer
: c
.Subject
.ToRDNSequence(),
1896 ThisUpdate
: now
.UTC(),
1897 NextUpdate
: expiry
.UTC(),
1898 RevokedCertificates
: revokedCertsUTC
,
1902 if len(c
.SubjectKeyId
) > 0 {
1903 var aki pkix
.Extension
1904 aki
.Id
= oidExtensionAuthorityKeyId
1905 aki
.Value
, err
= asn1
.Marshal(authKeyId
{Id
: c
.SubjectKeyId
})
1909 tbsCertList
.Extensions
= append(tbsCertList
.Extensions
, aki
)
1912 tbsCertListContents
, err
:= asn1
.Marshal(tbsCertList
)
1918 h
.Write(tbsCertListContents
)
1919 digest
:= h
.Sum(nil)
1921 var signature
[]byte
1922 signature
, err
= key
.Sign(rand
, digest
, hashFunc
)
1927 return asn1
.Marshal(pkix
.CertificateList
{
1928 TBSCertList
: tbsCertList
,
1929 SignatureAlgorithm
: signatureAlgorithm
,
1930 SignatureValue
: asn1
.BitString
{Bytes
: signature
, BitLength
: len(signature
) * 8},
1934 // CertificateRequest represents a PKCS #10, certificate signature request.
1935 type CertificateRequest
struct {
1936 Raw
[]byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
1937 RawTBSCertificateRequest
[]byte // Certificate request info part of raw ASN.1 DER content.
1938 RawSubjectPublicKeyInfo
[]byte // DER encoded SubjectPublicKeyInfo.
1939 RawSubject
[]byte // DER encoded Subject.
1943 SignatureAlgorithm SignatureAlgorithm
1945 PublicKeyAlgorithm PublicKeyAlgorithm
1946 PublicKey
interface{}
1950 // Attributes is the dried husk of a bug and shouldn't be used.
1951 Attributes
[]pkix
.AttributeTypeAndValueSET
1953 // Extensions contains raw X.509 extensions. When parsing CSRs, this
1954 // can be used to extract extensions that are not parsed by this
1956 Extensions
[]pkix
.Extension
1958 // ExtraExtensions contains extensions to be copied, raw, into any
1959 // marshaled CSR. Values override any extensions that would otherwise
1960 // be produced based on the other fields but are overridden by any
1961 // extensions specified in Attributes.
1963 // The ExtraExtensions field is not populated when parsing CSRs, see
1965 ExtraExtensions
[]pkix
.Extension
1967 // Subject Alternate Name values.
1969 EmailAddresses
[]string
1970 IPAddresses
[]net
.IP
1973 // These structures reflect the ASN.1 structure of X.509 certificate
1974 // signature requests (see RFC 2986):
1976 type tbsCertificateRequest
struct {
1979 Subject asn1
.RawValue
1980 PublicKey publicKeyInfo
1981 RawAttributes
[]asn1
.RawValue
`asn1:"tag:0"`
1984 type certificateRequest
struct {
1986 TBSCSR tbsCertificateRequest
1987 SignatureAlgorithm pkix
.AlgorithmIdentifier
1988 SignatureValue asn1
.BitString
1991 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
1992 // extensions in a CSR.
1993 var oidExtensionRequest
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 9, 14}
1995 // newRawAttributes converts AttributeTypeAndValueSETs from a template
1996 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
1997 func newRawAttributes(attributes
[]pkix
.AttributeTypeAndValueSET
) ([]asn1
.RawValue
, error
) {
1998 var rawAttributes
[]asn1
.RawValue
1999 b
, err
:= asn1
.Marshal(attributes
)
2003 rest
, err
:= asn1
.Unmarshal(b
, &rawAttributes
)
2008 return nil, errors
.New("x509: failed to unmarshal raw CSR Attributes")
2010 return rawAttributes
, nil
2013 // parseRawAttributes Unmarshals RawAttributes intos AttributeTypeAndValueSETs.
2014 func parseRawAttributes(rawAttributes
[]asn1
.RawValue
) []pkix
.AttributeTypeAndValueSET
{
2015 var attributes
[]pkix
.AttributeTypeAndValueSET
2016 for _
, rawAttr
:= range rawAttributes
{
2017 var attr pkix
.AttributeTypeAndValueSET
2018 rest
, err
:= asn1
.Unmarshal(rawAttr
.FullBytes
, &attr
)
2019 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2020 // (i.e.: challengePassword or unstructuredName).
2021 if err
== nil && len(rest
) == 0 {
2022 attributes
= append(attributes
, attr
)
2028 // parseCSRExtensions parses the attributes from a CSR and extracts any
2029 // requested extensions.
2030 func parseCSRExtensions(rawAttributes
[]asn1
.RawValue
) ([]pkix
.Extension
, error
) {
2031 // pkcs10Attribute reflects the Attribute structure from section 4.1 of
2032 // https://tools.ietf.org/html/rfc2986.
2033 type pkcs10Attribute
struct {
2034 Id asn1
.ObjectIdentifier
2035 Values
[]asn1
.RawValue
`asn1:"set"`
2038 var ret
[]pkix
.Extension
2039 for _
, rawAttr
:= range rawAttributes
{
2040 var attr pkcs10Attribute
2041 if rest
, err
:= asn1
.Unmarshal(rawAttr
.FullBytes
, &attr
); err
!= nil ||
len(rest
) != 0 ||
len(attr
.Values
) == 0 {
2042 // Ignore attributes that don't parse.
2046 if !attr
.Id
.Equal(oidExtensionRequest
) {
2050 var extensions
[]pkix
.Extension
2051 if _
, err
:= asn1
.Unmarshal(attr
.Values
[0].FullBytes
, &extensions
); err
!= nil {
2054 ret
= append(ret
, extensions
...)
2060 // CreateCertificateRequest creates a new certificate request based on a
2061 // template. The following members of template are used: Attributes, DNSNames,
2062 // EmailAddresses, ExtraExtensions, IPAddresses, SignatureAlgorithm, and
2063 // Subject. The private key is the private key of the signer.
2065 // The returned slice is the certificate request in DER encoding.
2067 // All keys types that are implemented via crypto.Signer are supported (This
2068 // includes *rsa.PublicKey and *ecdsa.PublicKey.)
2069 func CreateCertificateRequest(rand io
.Reader
, template
*CertificateRequest
, priv
interface{}) (csr
[]byte, err error
) {
2070 key
, ok
:= priv
.(crypto
.Signer
)
2072 return nil, errors
.New("x509: certificate private key does not implement crypto.Signer")
2075 var hashFunc crypto
.Hash
2076 var sigAlgo pkix
.AlgorithmIdentifier
2077 hashFunc
, sigAlgo
, err
= signingParamsForPublicKey(key
.Public(), template
.SignatureAlgorithm
)
2082 var publicKeyBytes
[]byte
2083 var publicKeyAlgorithm pkix
.AlgorithmIdentifier
2084 publicKeyBytes
, publicKeyAlgorithm
, err
= marshalPublicKey(key
.Public())
2089 var extensions
[]pkix
.Extension
2091 if (len(template
.DNSNames
) > 0 ||
len(template
.EmailAddresses
) > 0 ||
len(template
.IPAddresses
) > 0) &&
2092 !oidInExtensions(oidExtensionSubjectAltName
, template
.ExtraExtensions
) {
2093 sanBytes
, err
:= marshalSANs(template
.DNSNames
, template
.EmailAddresses
, template
.IPAddresses
)
2098 extensions
= append(extensions
, pkix
.Extension
{
2099 Id
: oidExtensionSubjectAltName
,
2104 extensions
= append(extensions
, template
.ExtraExtensions
...)
2106 var attributes
[]pkix
.AttributeTypeAndValueSET
2107 attributes
= append(attributes
, template
.Attributes
...)
2109 if len(extensions
) > 0 {
2110 // specifiedExtensions contains all the extensions that we
2111 // found specified via template.Attributes.
2112 specifiedExtensions
:= make(map[string]bool)
2114 for _
, atvSet
:= range template
.Attributes
{
2115 if !atvSet
.Type
.Equal(oidExtensionRequest
) {
2119 for _
, atvs
:= range atvSet
.Value
{
2120 for _
, atv
:= range atvs
{
2121 specifiedExtensions
[atv
.Type
.String()] = true
2126 atvs
:= make([]pkix
.AttributeTypeAndValue
, 0, len(extensions
))
2127 for _
, e
:= range extensions
{
2128 if specifiedExtensions
[e
.Id
.String()] {
2129 // Attributes already contained a value for
2130 // this extension and it takes priority.
2134 atvs
= append(atvs
, pkix
.AttributeTypeAndValue
{
2135 // There is no place for the critical flag in a CSR.
2141 // Append the extensions to an existing attribute if possible.
2143 for _
, atvSet
:= range attributes
{
2144 if !atvSet
.Type
.Equal(oidExtensionRequest
) ||
len(atvSet
.Value
) == 0 {
2148 atvSet
.Value
[0] = append(atvSet
.Value
[0], atvs
...)
2153 // Otherwise, add a new attribute for the extensions.
2155 attributes
= append(attributes
, pkix
.AttributeTypeAndValueSET
{
2156 Type
: oidExtensionRequest
,
2157 Value
: [][]pkix
.AttributeTypeAndValue
{
2164 asn1Subject
:= template
.RawSubject
2165 if len(asn1Subject
) == 0 {
2166 asn1Subject
, err
= asn1
.Marshal(template
.Subject
.ToRDNSequence())
2172 rawAttributes
, err
:= newRawAttributes(attributes
)
2177 tbsCSR
:= tbsCertificateRequest
{
2178 Version
: 0, // PKCS #10, RFC 2986
2179 Subject
: asn1
.RawValue
{FullBytes
: asn1Subject
},
2180 PublicKey
: publicKeyInfo
{
2181 Algorithm
: publicKeyAlgorithm
,
2182 PublicKey
: asn1
.BitString
{
2183 Bytes
: publicKeyBytes
,
2184 BitLength
: len(publicKeyBytes
) * 8,
2187 RawAttributes
: rawAttributes
,
2190 tbsCSRContents
, err
:= asn1
.Marshal(tbsCSR
)
2194 tbsCSR
.Raw
= tbsCSRContents
2197 h
.Write(tbsCSRContents
)
2198 digest
:= h
.Sum(nil)
2200 var signature
[]byte
2201 signature
, err
= key
.Sign(rand
, digest
, hashFunc
)
2206 return asn1
.Marshal(certificateRequest
{
2208 SignatureAlgorithm
: sigAlgo
,
2209 SignatureValue
: asn1
.BitString
{
2211 BitLength
: len(signature
) * 8,
2216 // ParseCertificateRequest parses a single certificate request from the
2217 // given ASN.1 DER data.
2218 func ParseCertificateRequest(asn1Data
[]byte) (*CertificateRequest
, error
) {
2219 var csr certificateRequest
2221 rest
, err
:= asn1
.Unmarshal(asn1Data
, &csr
)
2224 } else if len(rest
) != 0 {
2225 return nil, asn1
.SyntaxError
{Msg
: "trailing data"}
2228 return parseCertificateRequest(&csr
)
2231 func parseCertificateRequest(in
*certificateRequest
) (*CertificateRequest
, error
) {
2232 out
:= &CertificateRequest
{
2234 RawTBSCertificateRequest
: in
.TBSCSR
.Raw
,
2235 RawSubjectPublicKeyInfo
: in
.TBSCSR
.PublicKey
.Raw
,
2236 RawSubject
: in
.TBSCSR
.Subject
.FullBytes
,
2238 Signature
: in
.SignatureValue
.RightAlign(),
2239 SignatureAlgorithm
: getSignatureAlgorithmFromAI(in
.SignatureAlgorithm
),
2241 PublicKeyAlgorithm
: getPublicKeyAlgorithmFromOID(in
.TBSCSR
.PublicKey
.Algorithm
.Algorithm
),
2243 Version
: in
.TBSCSR
.Version
,
2244 Attributes
: parseRawAttributes(in
.TBSCSR
.RawAttributes
),
2248 out
.PublicKey
, err
= parsePublicKey(out
.PublicKeyAlgorithm
, &in
.TBSCSR
.PublicKey
)
2253 var subject pkix
.RDNSequence
2254 if rest
, err
:= asn1
.Unmarshal(in
.TBSCSR
.Subject
.FullBytes
, &subject
); err
!= nil {
2256 } else if len(rest
) != 0 {
2257 return nil, errors
.New("x509: trailing data after X.509 Subject")
2260 out
.Subject
.FillFromRDNSequence(&subject
)
2262 if out
.Extensions
, err
= parseCSRExtensions(in
.TBSCSR
.RawAttributes
); err
!= nil {
2266 for _
, extension
:= range out
.Extensions
{
2267 if extension
.Id
.Equal(oidExtensionSubjectAltName
) {
2268 out
.DNSNames
, out
.EmailAddresses
, out
.IPAddresses
, err
= parseSANExtension(extension
.Value
)
2278 // CheckSignature reports whether the signature on c is valid.
2279 func (c
*CertificateRequest
) CheckSignature() error
{
2280 return checkSignature(c
.SignatureAlgorithm
, c
.RawTBSCertificateRequest
, c
.Signature
, c
.PublicKey
)