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.
28 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
30 type pkixPublicKey
struct {
31 Algo pkix
.AlgorithmIdentifier
32 BitString asn1
.BitString
35 // ParsePKIXPublicKey parses a DER encoded public key. These values are
36 // typically found in PEM blocks with "BEGIN PUBLIC KEY".
37 func ParsePKIXPublicKey(derBytes
[]byte) (pub
interface{}, err error
) {
39 if _
, err
= asn1
.Unmarshal(derBytes
, &pki
); err
!= nil {
42 algo
:= getPublicKeyAlgorithmFromOID(pki
.Algorithm
.Algorithm
)
43 if algo
== UnknownPublicKeyAlgorithm
{
44 return nil, errors
.New("x509: unknown public key algorithm")
46 return parsePublicKey(algo
, &pki
)
49 func marshalPublicKey(pub
interface{}) (publicKeyBytes
[]byte, publicKeyAlgorithm pkix
.AlgorithmIdentifier
, err error
) {
50 switch pub
:= pub
.(type) {
52 publicKeyBytes
, err
= asn1
.Marshal(rsaPublicKey
{
56 publicKeyAlgorithm
.Algorithm
= oidPublicKeyRSA
57 // This is a NULL parameters value which is technically
58 // superfluous, but most other code includes it and, by
59 // doing this, we match their public key hashes.
60 publicKeyAlgorithm
.Parameters
= asn1
.RawValue
{
63 case *ecdsa
.PublicKey
:
64 publicKeyBytes
= elliptic
.Marshal(pub
.Curve
, pub
.X
, pub
.Y
)
65 oid
, ok
:= oidFromNamedCurve(pub
.Curve
)
67 return nil, pkix
.AlgorithmIdentifier
{}, errors
.New("x509: unsupported elliptic curve")
69 publicKeyAlgorithm
.Algorithm
= oidPublicKeyECDSA
71 paramBytes
, err
= asn1
.Marshal(oid
)
75 publicKeyAlgorithm
.Parameters
.FullBytes
= paramBytes
77 return nil, pkix
.AlgorithmIdentifier
{}, errors
.New("x509: only RSA and ECDSA public keys supported")
80 return publicKeyBytes
, publicKeyAlgorithm
, nil
83 // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
84 func MarshalPKIXPublicKey(pub
interface{}) ([]byte, error
) {
85 var publicKeyBytes
[]byte
86 var publicKeyAlgorithm pkix
.AlgorithmIdentifier
89 if publicKeyBytes
, publicKeyAlgorithm
, err
= marshalPublicKey(pub
); err
!= nil {
93 pkix
:= pkixPublicKey
{
94 Algo
: publicKeyAlgorithm
,
95 BitString
: asn1
.BitString
{
96 Bytes
: publicKeyBytes
,
97 BitLength
: 8 * len(publicKeyBytes
),
101 ret
, _
:= asn1
.Marshal(pkix
)
105 // These structures reflect the ASN.1 structure of X.509 certificates.:
107 type certificate
struct {
109 TBSCertificate tbsCertificate
110 SignatureAlgorithm pkix
.AlgorithmIdentifier
111 SignatureValue asn1
.BitString
114 type tbsCertificate
struct {
116 Version
int `asn1:"optional,explicit,default:1,tag:0"`
117 SerialNumber
*big
.Int
118 SignatureAlgorithm pkix
.AlgorithmIdentifier
121 Subject asn1
.RawValue
122 PublicKey publicKeyInfo
123 UniqueId asn1
.BitString
`asn1:"optional,tag:1"`
124 SubjectUniqueId asn1
.BitString
`asn1:"optional,tag:2"`
125 Extensions
[]pkix
.Extension
`asn1:"optional,explicit,tag:3"`
128 type dsaAlgorithmParameters
struct {
132 type dsaSignature
struct {
136 type ecdsaSignature dsaSignature
138 type validity
struct {
139 NotBefore
, NotAfter time
.Time
142 type publicKeyInfo
struct {
144 Algorithm pkix
.AlgorithmIdentifier
145 PublicKey asn1
.BitString
149 type authKeyId
struct {
150 Id
[]byte `asn1:"optional,tag:0"`
153 type SignatureAlgorithm
int
156 UnknownSignatureAlgorithm SignatureAlgorithm
= iota
171 type PublicKeyAlgorithm
int
174 UnknownPublicKeyAlgorithm PublicKeyAlgorithm
= iota
180 // OIDs for signature algorithms
182 // pkcs-1 OBJECT IDENTIFIER ::= {
183 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
186 // RFC 3279 2.2.1 RSA Signature Algorithms
188 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
190 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
192 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
194 // dsaWithSha1 OBJECT IDENTIFIER ::= {
195 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
197 // RFC 3279 2.2.3 ECDSA Signature Algorithm
199 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
200 // iso(1) member-body(2) us(840) ansi-x962(10045)
201 // signatures(4) ecdsa-with-SHA1(1)}
204 // RFC 4055 5 PKCS #1 Version 1.5
206 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
208 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
210 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
213 // RFC 5758 3.1 DSA Signature Algorithms
215 // dsaWithSha256 OBJECT IDENTIFIER ::= {
216 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
217 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
219 // RFC 5758 3.2 ECDSA Signature Algorithm
221 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
222 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
224 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
225 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
227 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
228 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
231 oidSignatureMD2WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 2}
232 oidSignatureMD5WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 4}
233 oidSignatureSHA1WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 5}
234 oidSignatureSHA256WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 11}
235 oidSignatureSHA384WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 12}
236 oidSignatureSHA512WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 13}
237 oidSignatureDSAWithSHA1
= asn1
.ObjectIdentifier
{1, 2, 840, 10040, 4, 3}
238 oidSignatureDSAWithSHA256
= asn1
.ObjectIdentifier
{2, 16, 840, 1, 101, 4, 3, 2}
239 oidSignatureECDSAWithSHA1
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 1}
240 oidSignatureECDSAWithSHA256
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 3, 2}
241 oidSignatureECDSAWithSHA384
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 3, 3}
242 oidSignatureECDSAWithSHA512
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 3, 4}
245 var signatureAlgorithmDetails
= []struct {
246 algo SignatureAlgorithm
247 oid asn1
.ObjectIdentifier
248 pubKeyAlgo PublicKeyAlgorithm
251 {MD2WithRSA
, oidSignatureMD2WithRSA
, RSA
, crypto
.Hash(0) /* no value for MD2 */},
252 {MD5WithRSA
, oidSignatureMD5WithRSA
, RSA
, crypto
.MD5
},
253 {SHA1WithRSA
, oidSignatureSHA1WithRSA
, RSA
, crypto
.SHA1
},
254 {SHA256WithRSA
, oidSignatureSHA256WithRSA
, RSA
, crypto
.SHA256
},
255 {SHA384WithRSA
, oidSignatureSHA384WithRSA
, RSA
, crypto
.SHA384
},
256 {SHA512WithRSA
, oidSignatureSHA512WithRSA
, RSA
, crypto
.SHA512
},
257 {DSAWithSHA1
, oidSignatureDSAWithSHA1
, DSA
, crypto
.SHA1
},
258 {DSAWithSHA256
, oidSignatureDSAWithSHA256
, DSA
, crypto
.SHA256
},
259 {ECDSAWithSHA1
, oidSignatureECDSAWithSHA1
, ECDSA
, crypto
.SHA1
},
260 {ECDSAWithSHA256
, oidSignatureECDSAWithSHA256
, ECDSA
, crypto
.SHA256
},
261 {ECDSAWithSHA384
, oidSignatureECDSAWithSHA384
, ECDSA
, crypto
.SHA384
},
262 {ECDSAWithSHA512
, oidSignatureECDSAWithSHA512
, ECDSA
, crypto
.SHA512
},
265 func getSignatureAlgorithmFromOID(oid asn1
.ObjectIdentifier
) SignatureAlgorithm
{
266 for _
, details
:= range signatureAlgorithmDetails
{
267 if oid
.Equal(details
.oid
) {
271 return UnknownSignatureAlgorithm
274 // RFC 3279, 2.3 Public Key Algorithms
276 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
277 // rsadsi(113549) pkcs(1) 1 }
279 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
281 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
282 // x9-57(10040) x9cm(4) 1 }
284 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
286 // id-ecPublicKey OBJECT IDENTIFIER ::= {
287 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
289 oidPublicKeyRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 1}
290 oidPublicKeyDSA
= asn1
.ObjectIdentifier
{1, 2, 840, 10040, 4, 1}
291 oidPublicKeyECDSA
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 2, 1}
294 func getPublicKeyAlgorithmFromOID(oid asn1
.ObjectIdentifier
) PublicKeyAlgorithm
{
296 case oid
.Equal(oidPublicKeyRSA
):
298 case oid
.Equal(oidPublicKeyDSA
):
300 case oid
.Equal(oidPublicKeyECDSA
):
303 return UnknownPublicKeyAlgorithm
306 // RFC 5480, 2.1.1.1. Named Curve
308 // secp224r1 OBJECT IDENTIFIER ::= {
309 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
311 // secp256r1 OBJECT IDENTIFIER ::= {
312 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
315 // secp384r1 OBJECT IDENTIFIER ::= {
316 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
318 // secp521r1 OBJECT IDENTIFIER ::= {
319 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
321 // NB: secp256r1 is equivalent to prime256v1
323 oidNamedCurveP224
= asn1
.ObjectIdentifier
{1, 3, 132, 0, 33}
324 oidNamedCurveP256
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 3, 1, 7}
325 oidNamedCurveP384
= asn1
.ObjectIdentifier
{1, 3, 132, 0, 34}
326 oidNamedCurveP521
= asn1
.ObjectIdentifier
{1, 3, 132, 0, 35}
329 func namedCurveFromOID(oid asn1
.ObjectIdentifier
) elliptic
.Curve
{
331 case oid
.Equal(oidNamedCurveP224
):
332 return elliptic
.P224()
333 case oid
.Equal(oidNamedCurveP256
):
334 return elliptic
.P256()
335 case oid
.Equal(oidNamedCurveP384
):
336 return elliptic
.P384()
337 case oid
.Equal(oidNamedCurveP521
):
338 return elliptic
.P521()
343 func oidFromNamedCurve(curve elliptic
.Curve
) (asn1
.ObjectIdentifier
, bool) {
345 case elliptic
.P224():
346 return oidNamedCurveP224
, true
347 case elliptic
.P256():
348 return oidNamedCurveP256
, true
349 case elliptic
.P384():
350 return oidNamedCurveP384
, true
351 case elliptic
.P521():
352 return oidNamedCurveP521
, true
358 // KeyUsage represents the set of actions that are valid for a given key. It's
359 // a bitmap of the KeyUsage* constants.
363 KeyUsageDigitalSignature KeyUsage
= 1 << iota
364 KeyUsageContentCommitment
365 KeyUsageKeyEncipherment
366 KeyUsageDataEncipherment
374 // RFC 5280, 4.2.1.12 Extended Key Usage
376 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
378 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
380 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
381 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
382 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
383 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
384 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
385 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
387 oidExtKeyUsageAny
= asn1
.ObjectIdentifier
{2, 5, 29, 37, 0}
388 oidExtKeyUsageServerAuth
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 1}
389 oidExtKeyUsageClientAuth
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 2}
390 oidExtKeyUsageCodeSigning
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 3}
391 oidExtKeyUsageEmailProtection
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 4}
392 oidExtKeyUsageIPSECEndSystem
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 5}
393 oidExtKeyUsageIPSECTunnel
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 6}
394 oidExtKeyUsageIPSECUser
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 7}
395 oidExtKeyUsageTimeStamping
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 8}
396 oidExtKeyUsageOCSPSigning
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 9}
397 oidExtKeyUsageMicrosoftServerGatedCrypto
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
398 oidExtKeyUsageNetscapeServerGatedCrypto
= asn1
.ObjectIdentifier
{2, 16, 840, 1, 113730, 4, 1}
401 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
402 // Each of the ExtKeyUsage* constants define a unique action.
406 ExtKeyUsageAny ExtKeyUsage
= iota
407 ExtKeyUsageServerAuth
408 ExtKeyUsageClientAuth
409 ExtKeyUsageCodeSigning
410 ExtKeyUsageEmailProtection
411 ExtKeyUsageIPSECEndSystem
412 ExtKeyUsageIPSECTunnel
414 ExtKeyUsageTimeStamping
415 ExtKeyUsageOCSPSigning
416 ExtKeyUsageMicrosoftServerGatedCrypto
417 ExtKeyUsageNetscapeServerGatedCrypto
420 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
421 var extKeyUsageOIDs
= []struct {
422 extKeyUsage ExtKeyUsage
423 oid asn1
.ObjectIdentifier
425 {ExtKeyUsageAny
, oidExtKeyUsageAny
},
426 {ExtKeyUsageServerAuth
, oidExtKeyUsageServerAuth
},
427 {ExtKeyUsageClientAuth
, oidExtKeyUsageClientAuth
},
428 {ExtKeyUsageCodeSigning
, oidExtKeyUsageCodeSigning
},
429 {ExtKeyUsageEmailProtection
, oidExtKeyUsageEmailProtection
},
430 {ExtKeyUsageIPSECEndSystem
, oidExtKeyUsageIPSECEndSystem
},
431 {ExtKeyUsageIPSECTunnel
, oidExtKeyUsageIPSECTunnel
},
432 {ExtKeyUsageIPSECUser
, oidExtKeyUsageIPSECUser
},
433 {ExtKeyUsageTimeStamping
, oidExtKeyUsageTimeStamping
},
434 {ExtKeyUsageOCSPSigning
, oidExtKeyUsageOCSPSigning
},
435 {ExtKeyUsageMicrosoftServerGatedCrypto
, oidExtKeyUsageMicrosoftServerGatedCrypto
},
436 {ExtKeyUsageNetscapeServerGatedCrypto
, oidExtKeyUsageNetscapeServerGatedCrypto
},
439 func extKeyUsageFromOID(oid asn1
.ObjectIdentifier
) (eku ExtKeyUsage
, ok
bool) {
440 for _
, pair
:= range extKeyUsageOIDs
{
441 if oid
.Equal(pair
.oid
) {
442 return pair
.extKeyUsage
, true
448 func oidFromExtKeyUsage(eku ExtKeyUsage
) (oid asn1
.ObjectIdentifier
, ok
bool) {
449 for _
, pair
:= range extKeyUsageOIDs
{
450 if eku
== pair
.extKeyUsage
{
451 return pair
.oid
, true
457 // A Certificate represents an X.509 certificate.
458 type Certificate
struct {
459 Raw
[]byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
460 RawTBSCertificate
[]byte // Certificate part of raw ASN.1 DER content.
461 RawSubjectPublicKeyInfo
[]byte // DER encoded SubjectPublicKeyInfo.
462 RawSubject
[]byte // DER encoded Subject
463 RawIssuer
[]byte // DER encoded Issuer
466 SignatureAlgorithm SignatureAlgorithm
468 PublicKeyAlgorithm PublicKeyAlgorithm
469 PublicKey
interface{}
472 SerialNumber
*big
.Int
475 NotBefore
, NotAfter time
.Time
// Validity bounds.
478 // Extensions contains raw X.509 extensions. When parsing certificates,
479 // this can be used to extract non-critical extensions that are not
480 // parsed by this package. When marshaling certificates, the Extensions
481 // field is ignored, see ExtraExtensions.
482 Extensions
[]pkix
.Extension
484 // ExtraExtensions contains extensions to be copied, raw, into any
485 // marshaled certificates. Values override any extensions that would
486 // otherwise be produced based on the other fields. The ExtraExtensions
487 // field is not populated when parsing certificates, see Extensions.
488 ExtraExtensions
[]pkix
.Extension
490 ExtKeyUsage
[]ExtKeyUsage
// Sequence of extended key usages.
491 UnknownExtKeyUsage
[]asn1
.ObjectIdentifier
// Encountered extended key usages unknown to this package.
493 BasicConstraintsValid
bool // if true then the next two fields are valid.
498 AuthorityKeyId
[]byte
500 // RFC 5280, 4.2.2.1 (Authority Information Access)
502 IssuingCertificateURL
[]string
504 // Subject Alternate Name values
506 EmailAddresses
[]string
510 PermittedDNSDomainsCritical
bool // if true then the name constraints are marked critical.
511 PermittedDNSDomains
[]string
513 // CRL Distribution Points
514 CRLDistributionPoints
[]string
516 PolicyIdentifiers
[]asn1
.ObjectIdentifier
519 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
520 // involves algorithms that are not currently implemented.
521 var ErrUnsupportedAlgorithm
= errors
.New("x509: cannot verify signature: algorithm unimplemented")
523 // ConstraintViolationError results when a requested usage is not permitted by
524 // a certificate. For example: checking a signature when the public key isn't a
525 // certificate signing key.
526 type ConstraintViolationError
struct{}
528 func (ConstraintViolationError
) Error() string {
529 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
532 func (c
*Certificate
) Equal(other
*Certificate
) bool {
533 return bytes
.Equal(c
.Raw
, other
.Raw
)
536 // Entrust have a broken root certificate (CN=Entrust.net Certification
537 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
538 // according to PKIX.
539 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
540 // from the Basic Constraints requirement.
541 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
543 // TODO(agl): remove this hack once their reissued root is sufficiently
545 var entrustBrokenSPKI
= []byte{
546 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
547 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
548 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
549 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
550 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
551 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
552 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
553 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
554 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
555 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
556 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
557 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
558 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
559 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
560 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
561 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
562 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
563 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
564 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
565 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
566 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
567 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
568 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
569 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
570 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
571 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
572 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
573 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
574 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
575 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
576 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
577 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
578 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
579 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
580 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
581 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
582 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
585 // CheckSignatureFrom verifies that the signature on c is a valid signature
587 func (c
*Certificate
) CheckSignatureFrom(parent
*Certificate
) (err error
) {
588 // RFC 5280, 4.2.1.9:
589 // "If the basic constraints extension is not present in a version 3
590 // certificate, or the extension is present but the cA boolean is not
591 // asserted, then the certified public key MUST NOT be used to verify
592 // certificate signatures."
593 // (except for Entrust, see comment above entrustBrokenSPKI)
594 if (parent
.Version
== 3 && !parent
.BasicConstraintsValid ||
595 parent
.BasicConstraintsValid
&& !parent
.IsCA
) &&
596 !bytes
.Equal(c
.RawSubjectPublicKeyInfo
, entrustBrokenSPKI
) {
597 return ConstraintViolationError
{}
600 if parent
.KeyUsage
!= 0 && parent
.KeyUsage
&KeyUsageCertSign
== 0 {
601 return ConstraintViolationError
{}
604 if parent
.PublicKeyAlgorithm
== UnknownPublicKeyAlgorithm
{
605 return ErrUnsupportedAlgorithm
608 // TODO(agl): don't ignore the path length constraint.
610 return parent
.CheckSignature(c
.SignatureAlgorithm
, c
.RawTBSCertificate
, c
.Signature
)
613 // CheckSignature verifies that signature is a valid signature over signed from
615 func (c
*Certificate
) CheckSignature(algo SignatureAlgorithm
, signed
, signature
[]byte) (err error
) {
616 var hashType crypto
.Hash
619 case SHA1WithRSA
, DSAWithSHA1
, ECDSAWithSHA1
:
620 hashType
= crypto
.SHA1
621 case SHA256WithRSA
, DSAWithSHA256
, ECDSAWithSHA256
:
622 hashType
= crypto
.SHA256
623 case SHA384WithRSA
, ECDSAWithSHA384
:
624 hashType
= crypto
.SHA384
625 case SHA512WithRSA
, ECDSAWithSHA512
:
626 hashType
= crypto
.SHA512
628 return ErrUnsupportedAlgorithm
631 if !hashType
.Available() {
632 return ErrUnsupportedAlgorithm
639 switch pub
:= c
.PublicKey
.(type) {
641 return rsa
.VerifyPKCS1v15(pub
, hashType
, digest
, signature
)
643 dsaSig
:= new(dsaSignature
)
644 if _
, err
:= asn1
.Unmarshal(signature
, dsaSig
); err
!= nil {
647 if dsaSig
.R
.Sign() <= 0 || dsaSig
.S
.Sign() <= 0 {
648 return errors
.New("x509: DSA signature contained zero or negative values")
650 if !dsa
.Verify(pub
, digest
, dsaSig
.R
, dsaSig
.S
) {
651 return errors
.New("x509: DSA verification failure")
654 case *ecdsa
.PublicKey
:
655 ecdsaSig
:= new(ecdsaSignature
)
656 if _
, err
:= asn1
.Unmarshal(signature
, ecdsaSig
); err
!= nil {
659 if ecdsaSig
.R
.Sign() <= 0 || ecdsaSig
.S
.Sign() <= 0 {
660 return errors
.New("x509: ECDSA signature contained zero or negative values")
662 if !ecdsa
.Verify(pub
, digest
, ecdsaSig
.R
, ecdsaSig
.S
) {
663 return errors
.New("x509: ECDSA verification failure")
667 return ErrUnsupportedAlgorithm
670 // CheckCRLSignature checks that the signature in crl is from c.
671 func (c
*Certificate
) CheckCRLSignature(crl
*pkix
.CertificateList
) (err error
) {
672 algo
:= getSignatureAlgorithmFromOID(crl
.SignatureAlgorithm
.Algorithm
)
673 return c
.CheckSignature(algo
, crl
.TBSCertList
.Raw
, crl
.SignatureValue
.RightAlign())
676 type UnhandledCriticalExtension
struct{}
678 func (h UnhandledCriticalExtension
) Error() string {
679 return "x509: unhandled critical extension"
682 type basicConstraints
struct {
683 IsCA
bool `asn1:"optional"`
684 MaxPathLen
int `asn1:"optional,default:-1"`
688 type policyInformation
struct {
689 Policy asn1
.ObjectIdentifier
690 // policyQualifiers omitted
693 // RFC 5280, 4.2.1.10
694 type nameConstraints
struct {
695 Permitted
[]generalSubtree
`asn1:"optional,tag:0"`
696 Excluded
[]generalSubtree
`asn1:"optional,tag:1"`
699 type generalSubtree
struct {
700 Name
string `asn1:"tag:2,optional,ia5"`
704 type authorityInfoAccess
struct {
705 Method asn1
.ObjectIdentifier
706 Location asn1
.RawValue
709 // RFC 5280, 4.2.1.14
710 type distributionPoint
struct {
711 DistributionPoint distributionPointName
`asn1:"optional,tag:0"`
712 Reason asn1
.BitString
`asn1:"optional,tag:1"`
713 CRLIssuer asn1
.RawValue
`asn1:"optional,tag:2"`
716 type distributionPointName
struct {
717 FullName asn1
.RawValue
`asn1:"optional,tag:0"`
718 RelativeName pkix
.RDNSequence
`asn1:"optional,tag:1"`
721 func parsePublicKey(algo PublicKeyAlgorithm
, keyData
*publicKeyInfo
) (interface{}, error
) {
722 asn1Data
:= keyData
.PublicKey
.RightAlign()
725 p
:= new(rsaPublicKey
)
726 _
, err
:= asn1
.Unmarshal(asn1Data
, p
)
732 return nil, errors
.New("x509: RSA modulus is not a positive number")
735 return nil, errors
.New("x509: RSA public exponent is not a positive number")
738 pub
:= &rsa
.PublicKey
{
745 _
, err
:= asn1
.Unmarshal(asn1Data
, &p
)
749 paramsData
:= keyData
.Algorithm
.Parameters
.FullBytes
750 params
:= new(dsaAlgorithmParameters
)
751 _
, err
= asn1
.Unmarshal(paramsData
, params
)
755 if p
.Sign() <= 0 || params
.P
.Sign() <= 0 || params
.Q
.Sign() <= 0 || params
.G
.Sign() <= 0 {
756 return nil, errors
.New("x509: zero or negative DSA parameter")
758 pub
:= &dsa
.PublicKey
{
759 Parameters
: dsa
.Parameters
{
768 paramsData
:= keyData
.Algorithm
.Parameters
.FullBytes
769 namedCurveOID
:= new(asn1
.ObjectIdentifier
)
770 _
, err
:= asn1
.Unmarshal(paramsData
, namedCurveOID
)
774 namedCurve
:= namedCurveFromOID(*namedCurveOID
)
775 if namedCurve
== nil {
776 return nil, errors
.New("x509: unsupported elliptic curve")
778 x
, y
:= elliptic
.Unmarshal(namedCurve
, asn1Data
)
780 return nil, errors
.New("x509: failed to unmarshal elliptic curve point")
782 pub
:= &ecdsa
.PublicKey
{
793 func parseCertificate(in
*certificate
) (*Certificate
, error
) {
794 out
:= new(Certificate
)
796 out
.RawTBSCertificate
= in
.TBSCertificate
.Raw
797 out
.RawSubjectPublicKeyInfo
= in
.TBSCertificate
.PublicKey
.Raw
798 out
.RawSubject
= in
.TBSCertificate
.Subject
.FullBytes
799 out
.RawIssuer
= in
.TBSCertificate
.Issuer
.FullBytes
801 out
.Signature
= in
.SignatureValue
.RightAlign()
802 out
.SignatureAlgorithm
=
803 getSignatureAlgorithmFromOID(in
.TBSCertificate
.SignatureAlgorithm
.Algorithm
)
805 out
.PublicKeyAlgorithm
=
806 getPublicKeyAlgorithmFromOID(in
.TBSCertificate
.PublicKey
.Algorithm
.Algorithm
)
808 out
.PublicKey
, err
= parsePublicKey(out
.PublicKeyAlgorithm
, &in
.TBSCertificate
.PublicKey
)
813 if in
.TBSCertificate
.SerialNumber
.Sign() < 0 {
814 return nil, errors
.New("x509: negative serial number")
817 out
.Version
= in
.TBSCertificate
.Version
+ 1
818 out
.SerialNumber
= in
.TBSCertificate
.SerialNumber
820 var issuer
, subject pkix
.RDNSequence
821 if _
, err
:= asn1
.Unmarshal(in
.TBSCertificate
.Subject
.FullBytes
, &subject
); err
!= nil {
824 if _
, err
:= asn1
.Unmarshal(in
.TBSCertificate
.Issuer
.FullBytes
, &issuer
); err
!= nil {
828 out
.Issuer
.FillFromRDNSequence(&issuer
)
829 out
.Subject
.FillFromRDNSequence(&subject
)
831 out
.NotBefore
= in
.TBSCertificate
.Validity
.NotBefore
832 out
.NotAfter
= in
.TBSCertificate
.Validity
.NotAfter
834 for _
, e
:= range in
.TBSCertificate
.Extensions
{
835 out
.Extensions
= append(out
.Extensions
, e
)
837 if len(e
.Id
) == 4 && e
.Id
[0] == 2 && e
.Id
[1] == 5 && e
.Id
[2] == 29 {
841 var usageBits asn1
.BitString
842 _
, err
:= asn1
.Unmarshal(e
.Value
, &usageBits
)
846 for i
:= 0; i
< 9; i
++ {
847 if usageBits
.At(i
) != 0 {
848 usage |
= 1 << uint(i
)
851 out
.KeyUsage
= KeyUsage(usage
)
856 var constraints basicConstraints
857 _
, err
:= asn1
.Unmarshal(e
.Value
, &constraints
)
860 out
.BasicConstraintsValid
= true
861 out
.IsCA
= constraints
.IsCA
862 out
.MaxPathLen
= constraints
.MaxPathLen
868 // SubjectAltName ::= GeneralNames
870 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
872 // GeneralName ::= CHOICE {
873 // otherName [0] OtherName,
874 // rfc822Name [1] IA5String,
875 // dNSName [2] IA5String,
876 // x400Address [3] ORAddress,
877 // directoryName [4] Name,
878 // ediPartyName [5] EDIPartyName,
879 // uniformResourceIdentifier [6] IA5String,
880 // iPAddress [7] OCTET STRING,
881 // registeredID [8] OBJECT IDENTIFIER }
882 var seq asn1
.RawValue
883 _
, err
:= asn1
.Unmarshal(e
.Value
, &seq
)
887 if !seq
.IsCompound || seq
.Tag
!= 16 || seq
.Class
!= 0 {
888 return nil, asn1
.StructuralError
{Msg
: "bad SAN sequence"}
896 rest
, err
= asn1
.Unmarshal(rest
, &v
)
902 out
.EmailAddresses
= append(out
.EmailAddresses
, string(v
.Bytes
))
905 out
.DNSNames
= append(out
.DNSNames
, string(v
.Bytes
))
908 switch len(v
.Bytes
) {
909 case net
.IPv4len
, net
.IPv6len
:
910 out
.IPAddresses
= append(out
.IPAddresses
, v
.Bytes
)
912 return nil, errors
.New("x509: certificate contained IP address of length " + strconv
.Itoa(len(v
.Bytes
)))
920 // If we didn't parse any of the names then we
921 // fall through to the critical check below.
924 // RFC 5280, 4.2.1.10
926 // NameConstraints ::= SEQUENCE {
927 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
928 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
930 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
932 // GeneralSubtree ::= SEQUENCE {
934 // minimum [0] BaseDistance DEFAULT 0,
935 // maximum [1] BaseDistance OPTIONAL }
937 // BaseDistance ::= INTEGER (0..MAX)
939 var constraints nameConstraints
940 _
, err
:= asn1
.Unmarshal(e
.Value
, &constraints
)
945 if len(constraints
.Excluded
) > 0 && e
.Critical
{
946 return out
, UnhandledCriticalExtension
{}
949 for _
, subtree
:= range constraints
.Permitted
{
950 if len(subtree
.Name
) == 0 {
952 return out
, UnhandledCriticalExtension
{}
956 out
.PermittedDNSDomains
= append(out
.PermittedDNSDomains
, subtree
.Name
)
961 // RFC 5280, 4.2.1.14
963 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
965 // DistributionPoint ::= SEQUENCE {
966 // distributionPoint [0] DistributionPointName OPTIONAL,
967 // reasons [1] ReasonFlags OPTIONAL,
968 // cRLIssuer [2] GeneralNames OPTIONAL }
970 // DistributionPointName ::= CHOICE {
971 // fullName [0] GeneralNames,
972 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
974 var cdp
[]distributionPoint
975 _
, err
:= asn1
.Unmarshal(e
.Value
, &cdp
)
980 for _
, dp
:= range cdp
{
982 _
, err
= asn1
.Unmarshal(dp
.DistributionPoint
.FullName
.Bytes
, &n
)
988 out
.CRLDistributionPoints
= append(out
.CRLDistributionPoints
, string(n
.Bytes
))
996 _
, err
= asn1
.Unmarshal(e
.Value
, &a
)
1000 out
.AuthorityKeyId
= a
.Id
1004 // RFC 5280, 4.2.1.12. Extended Key Usage
1006 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1008 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1010 // KeyPurposeId ::= OBJECT IDENTIFIER
1012 var keyUsage
[]asn1
.ObjectIdentifier
1013 _
, err
= asn1
.Unmarshal(e
.Value
, &keyUsage
)
1018 for _
, u
:= range keyUsage
{
1019 if extKeyUsage
, ok
:= extKeyUsageFromOID(u
); ok
{
1020 out
.ExtKeyUsage
= append(out
.ExtKeyUsage
, extKeyUsage
)
1022 out
.UnknownExtKeyUsage
= append(out
.UnknownExtKeyUsage
, u
)
1029 // RFC 5280, 4.2.1.2
1031 _
, err
= asn1
.Unmarshal(e
.Value
, &keyid
)
1035 out
.SubjectKeyId
= keyid
1039 // RFC 5280 4.2.1.4: Certificate Policies
1040 var policies
[]policyInformation
1041 if _
, err
= asn1
.Unmarshal(e
.Value
, &policies
); err
!= nil {
1044 out
.PolicyIdentifiers
= make([]asn1
.ObjectIdentifier
, len(policies
))
1045 for i
, policy
:= range policies
{
1046 out
.PolicyIdentifiers
[i
] = policy
.Policy
1049 } else if e
.Id
.Equal(oidExtensionAuthorityInfoAccess
) {
1050 // RFC 5280 4.2.2.1: Authority Information Access
1051 var aia
[]authorityInfoAccess
1052 if _
, err
= asn1
.Unmarshal(e
.Value
, &aia
); err
!= nil {
1056 for _
, v
:= range aia
{
1057 // GeneralName: uniformResourceIdentifier [6] IA5String
1058 if v
.Location
.Tag
!= 6 {
1061 if v
.Method
.Equal(oidAuthorityInfoAccessOcsp
) {
1062 out
.OCSPServer
= append(out
.OCSPServer
, string(v
.Location
.Bytes
))
1063 } else if v
.Method
.Equal(oidAuthorityInfoAccessIssuers
) {
1064 out
.IssuingCertificateURL
= append(out
.IssuingCertificateURL
, string(v
.Location
.Bytes
))
1070 return out
, UnhandledCriticalExtension
{}
1077 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1078 func ParseCertificate(asn1Data
[]byte) (*Certificate
, error
) {
1079 var cert certificate
1080 rest
, err
:= asn1
.Unmarshal(asn1Data
, &cert
)
1085 return nil, asn1
.SyntaxError
{Msg
: "trailing data"}
1088 return parseCertificate(&cert
)
1091 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1092 // data. The certificates must be concatenated with no intermediate padding.
1093 func ParseCertificates(asn1Data
[]byte) ([]*Certificate
, error
) {
1094 var v
[]*certificate
1096 for len(asn1Data
) > 0 {
1097 cert
:= new(certificate
)
1099 asn1Data
, err
= asn1
.Unmarshal(asn1Data
, cert
)
1106 ret
:= make([]*Certificate
, len(v
))
1107 for i
, ci
:= range v
{
1108 cert
, err
:= parseCertificate(ci
)
1118 func reverseBitsInAByte(in
byte) byte {
1120 b2
:= b1
>>2&0x33 | b1
<<2&0xcc
1121 b3
:= b2
>>1&0x55 | b2
<<1&0xaa
1126 oidExtensionSubjectKeyId
= []int{2, 5, 29, 14}
1127 oidExtensionKeyUsage
= []int{2, 5, 29, 15}
1128 oidExtensionExtendedKeyUsage
= []int{2, 5, 29, 37}
1129 oidExtensionAuthorityKeyId
= []int{2, 5, 29, 35}
1130 oidExtensionBasicConstraints
= []int{2, 5, 29, 19}
1131 oidExtensionSubjectAltName
= []int{2, 5, 29, 17}
1132 oidExtensionCertificatePolicies
= []int{2, 5, 29, 32}
1133 oidExtensionNameConstraints
= []int{2, 5, 29, 30}
1134 oidExtensionCRLDistributionPoints
= []int{2, 5, 29, 31}
1135 oidExtensionAuthorityInfoAccess
= []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1139 oidAuthorityInfoAccessOcsp
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 48, 1}
1140 oidAuthorityInfoAccessIssuers
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 48, 2}
1143 // oidNotInExtensions returns whether an extension with the given oid exists in
1145 func oidInExtensions(oid asn1
.ObjectIdentifier
, extensions
[]pkix
.Extension
) bool {
1146 for _
, e
:= range extensions
{
1147 if e
.Id
.Equal(oid
) {
1154 func buildExtensions(template
*Certificate
) (ret
[]pkix
.Extension
, err error
) {
1155 ret
= make([]pkix
.Extension
, 10 /* maximum number of elements. */)
1158 if template
.KeyUsage
!= 0 &&
1159 !oidInExtensions(oidExtensionKeyUsage
, template
.ExtraExtensions
) {
1160 ret
[n
].Id
= oidExtensionKeyUsage
1161 ret
[n
].Critical
= true
1164 a
[0] = reverseBitsInAByte(byte(template
.KeyUsage
))
1165 a
[1] = reverseBitsInAByte(byte(template
.KeyUsage
>> 8))
1172 ret
[n
].Value
, err
= asn1
.Marshal(asn1
.BitString
{Bytes
: a
[0:l
], BitLength
: l
* 8})
1179 if (len(template
.ExtKeyUsage
) > 0 ||
len(template
.UnknownExtKeyUsage
) > 0) &&
1180 !oidInExtensions(oidExtensionExtendedKeyUsage
, template
.ExtraExtensions
) {
1181 ret
[n
].Id
= oidExtensionExtendedKeyUsage
1183 var oids
[]asn1
.ObjectIdentifier
1184 for _
, u
:= range template
.ExtKeyUsage
{
1185 if oid
, ok
:= oidFromExtKeyUsage(u
); ok
{
1186 oids
= append(oids
, oid
)
1188 panic("internal error")
1192 oids
= append(oids
, template
.UnknownExtKeyUsage
...)
1194 ret
[n
].Value
, err
= asn1
.Marshal(oids
)
1201 if template
.BasicConstraintsValid
&& !oidInExtensions(oidExtensionBasicConstraints
, template
.ExtraExtensions
) {
1202 ret
[n
].Id
= oidExtensionBasicConstraints
1203 ret
[n
].Value
, err
= asn1
.Marshal(basicConstraints
{template
.IsCA
, template
.MaxPathLen
})
1204 ret
[n
].Critical
= true
1211 if len(template
.SubjectKeyId
) > 0 && !oidInExtensions(oidExtensionSubjectKeyId
, template
.ExtraExtensions
) {
1212 ret
[n
].Id
= oidExtensionSubjectKeyId
1213 ret
[n
].Value
, err
= asn1
.Marshal(template
.SubjectKeyId
)
1220 if len(template
.AuthorityKeyId
) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId
, template
.ExtraExtensions
) {
1221 ret
[n
].Id
= oidExtensionAuthorityKeyId
1222 ret
[n
].Value
, err
= asn1
.Marshal(authKeyId
{template
.AuthorityKeyId
})
1229 if (len(template
.OCSPServer
) > 0 ||
len(template
.IssuingCertificateURL
) > 0) &&
1230 !oidInExtensions(oidExtensionAuthorityInfoAccess
, template
.ExtraExtensions
) {
1231 ret
[n
].Id
= oidExtensionAuthorityInfoAccess
1232 var aiaValues
[]authorityInfoAccess
1233 for _
, name
:= range template
.OCSPServer
{
1234 aiaValues
= append(aiaValues
, authorityInfoAccess
{
1235 Method
: oidAuthorityInfoAccessOcsp
,
1236 Location
: asn1
.RawValue
{Tag
: 6, Class
: 2, Bytes
: []byte(name
)},
1239 for _
, name
:= range template
.IssuingCertificateURL
{
1240 aiaValues
= append(aiaValues
, authorityInfoAccess
{
1241 Method
: oidAuthorityInfoAccessIssuers
,
1242 Location
: asn1
.RawValue
{Tag
: 6, Class
: 2, Bytes
: []byte(name
)},
1245 ret
[n
].Value
, err
= asn1
.Marshal(aiaValues
)
1252 if (len(template
.DNSNames
) > 0 ||
len(template
.EmailAddresses
) > 0 ||
len(template
.IPAddresses
) > 0) &&
1253 !oidInExtensions(oidExtensionSubjectAltName
, template
.ExtraExtensions
) {
1254 ret
[n
].Id
= oidExtensionSubjectAltName
1255 var rawValues
[]asn1
.RawValue
1256 for _
, name
:= range template
.DNSNames
{
1257 rawValues
= append(rawValues
, asn1
.RawValue
{Tag
: 2, Class
: 2, Bytes
: []byte(name
)})
1259 for _
, email
:= range template
.EmailAddresses
{
1260 rawValues
= append(rawValues
, asn1
.RawValue
{Tag
: 1, Class
: 2, Bytes
: []byte(email
)})
1262 for _
, rawIP
:= range template
.IPAddresses
{
1263 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1268 rawValues
= append(rawValues
, asn1
.RawValue
{Tag
: 7, Class
: 2, Bytes
: ip
})
1270 ret
[n
].Value
, err
= asn1
.Marshal(rawValues
)
1277 if len(template
.PolicyIdentifiers
) > 0 &&
1278 !oidInExtensions(oidExtensionCertificatePolicies
, template
.ExtraExtensions
) {
1279 ret
[n
].Id
= oidExtensionCertificatePolicies
1280 policies
:= make([]policyInformation
, len(template
.PolicyIdentifiers
))
1281 for i
, policy
:= range template
.PolicyIdentifiers
{
1282 policies
[i
].Policy
= policy
1284 ret
[n
].Value
, err
= asn1
.Marshal(policies
)
1291 if len(template
.PermittedDNSDomains
) > 0 &&
1292 !oidInExtensions(oidExtensionNameConstraints
, template
.ExtraExtensions
) {
1293 ret
[n
].Id
= oidExtensionNameConstraints
1294 ret
[n
].Critical
= template
.PermittedDNSDomainsCritical
1296 var out nameConstraints
1297 out
.Permitted
= make([]generalSubtree
, len(template
.PermittedDNSDomains
))
1298 for i
, permitted
:= range template
.PermittedDNSDomains
{
1299 out
.Permitted
[i
] = generalSubtree
{Name
: permitted
}
1301 ret
[n
].Value
, err
= asn1
.Marshal(out
)
1308 if len(template
.CRLDistributionPoints
) > 0 &&
1309 !oidInExtensions(oidExtensionCRLDistributionPoints
, template
.ExtraExtensions
) {
1310 ret
[n
].Id
= oidExtensionCRLDistributionPoints
1312 var crlDp
[]distributionPoint
1313 for _
, name
:= range template
.CRLDistributionPoints
{
1314 rawFullName
, _
:= asn1
.Marshal(asn1
.RawValue
{Tag
: 6, Class
: 2, Bytes
: []byte(name
)})
1316 dp
:= distributionPoint
{
1317 DistributionPoint
: distributionPointName
{
1318 FullName
: asn1
.RawValue
{Tag
: 0, Class
: 2, Bytes
: rawFullName
},
1321 crlDp
= append(crlDp
, dp
)
1324 ret
[n
].Value
, err
= asn1
.Marshal(crlDp
)
1331 // Adding another extension here? Remember to update the maximum number
1332 // of elements in the make() at the top of the function.
1334 return append(ret
[:n
], template
.ExtraExtensions
...), nil
1337 func subjectBytes(cert
*Certificate
) ([]byte, error
) {
1338 if len(cert
.RawSubject
) > 0 {
1339 return cert
.RawSubject
, nil
1342 return asn1
.Marshal(cert
.Subject
.ToRDNSequence())
1345 // CreateCertificate creates a new certificate based on a template. The
1346 // following members of template are used: SerialNumber, Subject, NotBefore,
1347 // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
1348 // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
1349 // PermittedDNSDomains, SignatureAlgorithm.
1351 // The certificate is signed by parent. If parent is equal to template then the
1352 // certificate is self-signed. The parameter pub is the public key of the
1353 // signee and priv is the private key of the signer.
1355 // The returned slice is the certificate in DER encoding.
1357 // The only supported key types are RSA and ECDSA (*rsa.PublicKey or
1358 // *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PrivateKey for priv).
1359 func CreateCertificate(rand io
.Reader
, template
, parent
*Certificate
, pub
interface{}, priv
interface{}) (cert
[]byte, err error
) {
1360 var publicKeyBytes
[]byte
1361 var publicKeyAlgorithm pkix
.AlgorithmIdentifier
1363 if publicKeyBytes
, publicKeyAlgorithm
, err
= marshalPublicKey(pub
); err
!= nil {
1367 var signatureAlgorithm pkix
.AlgorithmIdentifier
1368 var hashFunc crypto
.Hash
1369 var privType PublicKeyAlgorithm
1371 switch priv
:= priv
.(type) {
1372 case *rsa
.PrivateKey
:
1374 signatureAlgorithm
.Algorithm
= oidSignatureSHA256WithRSA
1375 hashFunc
= crypto
.SHA256
1376 case *ecdsa
.PrivateKey
:
1380 case elliptic
.P224(), elliptic
.P256():
1381 hashFunc
= crypto
.SHA256
1382 signatureAlgorithm
.Algorithm
= oidSignatureECDSAWithSHA256
1383 case elliptic
.P384():
1384 hashFunc
= crypto
.SHA384
1385 signatureAlgorithm
.Algorithm
= oidSignatureECDSAWithSHA384
1386 case elliptic
.P521():
1387 hashFunc
= crypto
.SHA512
1388 signatureAlgorithm
.Algorithm
= oidSignatureECDSAWithSHA512
1390 return nil, errors
.New("x509: unknown elliptic curve")
1393 return nil, errors
.New("x509: only RSA and ECDSA private keys supported")
1396 if template
.SignatureAlgorithm
!= 0 {
1398 for _
, details
:= range signatureAlgorithmDetails
{
1399 if details
.algo
== template
.SignatureAlgorithm
{
1400 if details
.pubKeyAlgo
!= privType
{
1401 return nil, errors
.New("x509: requested SignatureAlgorithm does not match private key type")
1403 signatureAlgorithm
.Algorithm
, hashFunc
= details
.oid
, details
.hash
1405 return nil, errors
.New("x509: cannot sign with hash function requested")
1412 return nil, errors
.New("x509: unknown SignatureAlgorithm")
1420 if len(parent
.SubjectKeyId
) > 0 {
1421 template
.AuthorityKeyId
= parent
.SubjectKeyId
1424 extensions
, err
:= buildExtensions(template
)
1429 asn1Issuer
, err
:= subjectBytes(parent
)
1434 asn1Subject
, err
:= subjectBytes(template
)
1439 encodedPublicKey
:= asn1
.BitString
{BitLength
: len(publicKeyBytes
) * 8, Bytes
: publicKeyBytes
}
1440 c
:= tbsCertificate
{
1442 SerialNumber
: template
.SerialNumber
,
1443 SignatureAlgorithm
: signatureAlgorithm
,
1444 Issuer
: asn1
.RawValue
{FullBytes
: asn1Issuer
},
1445 Validity
: validity
{template
.NotBefore
.UTC(), template
.NotAfter
.UTC()},
1446 Subject
: asn1
.RawValue
{FullBytes
: asn1Subject
},
1447 PublicKey
: publicKeyInfo
{nil, publicKeyAlgorithm
, encodedPublicKey
},
1448 Extensions
: extensions
,
1451 tbsCertContents
, err
:= asn1
.Marshal(c
)
1456 c
.Raw
= tbsCertContents
1459 h
.Write(tbsCertContents
)
1460 digest
:= h
.Sum(nil)
1462 var signature
[]byte
1464 switch priv
:= priv
.(type) {
1465 case *rsa
.PrivateKey
:
1466 signature
, err
= rsa
.SignPKCS1v15(rand
, priv
, hashFunc
, digest
)
1467 case *ecdsa
.PrivateKey
:
1469 if r
, s
, err
= ecdsa
.Sign(rand
, priv
, digest
); err
== nil {
1470 signature
, err
= asn1
.Marshal(ecdsaSignature
{r
, s
})
1473 panic("internal error")
1480 cert
, err
= asn1
.Marshal(certificate
{
1484 asn1
.BitString
{Bytes
: signature
, BitLength
: len(signature
) * 8},
1489 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1491 var pemCRLPrefix
= []byte("-----BEGIN X509 CRL")
1493 // pemType is the type of a PEM encoded CRL.
1494 var pemType
= "X509 CRL"
1496 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1497 // encoded CRLs will appear where they should be DER encoded, so this function
1498 // will transparently handle PEM encoding as long as there isn't any leading
1500 func ParseCRL(crlBytes
[]byte) (certList
*pkix
.CertificateList
, err error
) {
1501 if bytes
.HasPrefix(crlBytes
, pemCRLPrefix
) {
1502 block
, _
:= pem
.Decode(crlBytes
)
1503 if block
!= nil && block
.Type
== pemType
{
1504 crlBytes
= block
.Bytes
1507 return ParseDERCRL(crlBytes
)
1510 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1511 func ParseDERCRL(derBytes
[]byte) (certList
*pkix
.CertificateList
, err error
) {
1512 certList
= new(pkix
.CertificateList
)
1513 _
, err
= asn1
.Unmarshal(derBytes
, certList
)
1520 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1521 // contains the given list of revoked certificates.
1523 // The only supported key type is RSA (*rsa.PrivateKey for priv).
1524 func (c
*Certificate
) CreateCRL(rand io
.Reader
, priv
interface{}, revokedCerts
[]pkix
.RevokedCertificate
, now
, expiry time
.Time
) (crlBytes
[]byte, err error
) {
1525 rsaPriv
, ok
:= priv
.(*rsa
.PrivateKey
)
1527 return nil, errors
.New("x509: non-RSA private keys not supported")
1529 tbsCertList
:= pkix
.TBSCertificateList
{
1531 Signature
: pkix
.AlgorithmIdentifier
{
1532 Algorithm
: oidSignatureSHA1WithRSA
,
1534 Issuer
: c
.Subject
.ToRDNSequence(),
1535 ThisUpdate
: now
.UTC(),
1536 NextUpdate
: expiry
.UTC(),
1537 RevokedCertificates
: revokedCerts
,
1540 tbsCertListContents
, err
:= asn1
.Marshal(tbsCertList
)
1546 h
.Write(tbsCertListContents
)
1547 digest
:= h
.Sum(nil)
1549 signature
, err
:= rsa
.SignPKCS1v15(rand
, rsaPriv
, crypto
.SHA1
, digest
)
1554 return asn1
.Marshal(pkix
.CertificateList
{
1555 TBSCertList
: tbsCertList
,
1556 SignatureAlgorithm
: pkix
.AlgorithmIdentifier
{
1557 Algorithm
: oidSignatureSHA1WithRSA
,
1559 SignatureValue
: asn1
.BitString
{Bytes
: signature
, BitLength
: len(signature
) * 8},