1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
5 // Package x509 parses X.509-encoded keys and certificates.
29 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
31 type pkixPublicKey
struct {
32 Algo pkix
.AlgorithmIdentifier
33 BitString asn1
.BitString
36 // ParsePKIXPublicKey parses a DER encoded public key. These values are
37 // typically found in PEM blocks with "BEGIN PUBLIC KEY".
38 func ParsePKIXPublicKey(derBytes
[]byte) (pub
interface{}, err error
) {
40 if _
, err
= asn1
.Unmarshal(derBytes
, &pki
); err
!= nil {
43 algo
:= getPublicKeyAlgorithmFromOID(pki
.Algorithm
.Algorithm
)
44 if algo
== UnknownPublicKeyAlgorithm
{
45 return nil, errors
.New("x509: unknown public key algorithm")
47 return parsePublicKey(algo
, &pki
)
50 func marshalPublicKey(pub
interface{}) (publicKeyBytes
[]byte, publicKeyAlgorithm pkix
.AlgorithmIdentifier
, err error
) {
51 switch pub
:= pub
.(type) {
53 publicKeyBytes
, err
= asn1
.Marshal(rsaPublicKey
{
57 publicKeyAlgorithm
.Algorithm
= oidPublicKeyRSA
58 // This is a NULL parameters value which is technically
59 // superfluous, but most other code includes it and, by
60 // doing this, we match their public key hashes.
61 publicKeyAlgorithm
.Parameters
= asn1
.RawValue
{
64 case *ecdsa
.PublicKey
:
65 publicKeyBytes
= elliptic
.Marshal(pub
.Curve
, pub
.X
, pub
.Y
)
66 oid
, ok
:= oidFromNamedCurve(pub
.Curve
)
68 return nil, pkix
.AlgorithmIdentifier
{}, errors
.New("x509: unsupported elliptic curve")
70 publicKeyAlgorithm
.Algorithm
= oidPublicKeyECDSA
72 paramBytes
, err
= asn1
.Marshal(oid
)
76 publicKeyAlgorithm
.Parameters
.FullBytes
= paramBytes
78 return nil, pkix
.AlgorithmIdentifier
{}, errors
.New("x509: only RSA and ECDSA public keys supported")
81 return publicKeyBytes
, publicKeyAlgorithm
, nil
84 // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
85 func MarshalPKIXPublicKey(pub
interface{}) ([]byte, error
) {
86 var publicKeyBytes
[]byte
87 var publicKeyAlgorithm pkix
.AlgorithmIdentifier
90 if publicKeyBytes
, publicKeyAlgorithm
, err
= marshalPublicKey(pub
); err
!= nil {
94 pkix
:= pkixPublicKey
{
95 Algo
: publicKeyAlgorithm
,
96 BitString
: asn1
.BitString
{
97 Bytes
: publicKeyBytes
,
98 BitLength
: 8 * len(publicKeyBytes
),
102 ret
, _
:= asn1
.Marshal(pkix
)
106 // These structures reflect the ASN.1 structure of X.509 certificates.:
108 type certificate
struct {
110 TBSCertificate tbsCertificate
111 SignatureAlgorithm pkix
.AlgorithmIdentifier
112 SignatureValue asn1
.BitString
115 type tbsCertificate
struct {
117 Version
int `asn1:"optional,explicit,default:1,tag:0"`
118 SerialNumber
*big
.Int
119 SignatureAlgorithm pkix
.AlgorithmIdentifier
122 Subject asn1
.RawValue
123 PublicKey publicKeyInfo
124 UniqueId asn1
.BitString
`asn1:"optional,tag:1"`
125 SubjectUniqueId asn1
.BitString
`asn1:"optional,tag:2"`
126 Extensions
[]pkix
.Extension
`asn1:"optional,explicit,tag:3"`
129 type dsaAlgorithmParameters
struct {
133 type dsaSignature
struct {
137 type ecdsaSignature dsaSignature
139 type validity
struct {
140 NotBefore
, NotAfter time
.Time
143 type publicKeyInfo
struct {
145 Algorithm pkix
.AlgorithmIdentifier
146 PublicKey asn1
.BitString
150 type authKeyId
struct {
151 Id
[]byte `asn1:"optional,tag:0"`
154 type SignatureAlgorithm
int
157 UnknownSignatureAlgorithm SignatureAlgorithm
= iota
172 type PublicKeyAlgorithm
int
175 UnknownPublicKeyAlgorithm PublicKeyAlgorithm
= iota
181 // OIDs for signature algorithms
183 // pkcs-1 OBJECT IDENTIFIER ::= {
184 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
187 // RFC 3279 2.2.1 RSA Signature Algorithms
189 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
191 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
193 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
195 // dsaWithSha1 OBJECT IDENTIFIER ::= {
196 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
198 // RFC 3279 2.2.3 ECDSA Signature Algorithm
200 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
201 // iso(1) member-body(2) us(840) ansi-x962(10045)
202 // signatures(4) ecdsa-with-SHA1(1)}
205 // RFC 4055 5 PKCS #1 Version 1.5
207 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
209 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
211 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
214 // RFC 5758 3.1 DSA Signature Algorithms
216 // dsaWithSha256 OBJECT IDENTIFIER ::= {
217 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
218 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
220 // RFC 5758 3.2 ECDSA Signature Algorithm
222 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
223 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
225 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
226 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
228 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
229 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
232 oidSignatureMD2WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 2}
233 oidSignatureMD5WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 4}
234 oidSignatureSHA1WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 5}
235 oidSignatureSHA256WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 11}
236 oidSignatureSHA384WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 12}
237 oidSignatureSHA512WithRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 13}
238 oidSignatureDSAWithSHA1
= asn1
.ObjectIdentifier
{1, 2, 840, 10040, 4, 3}
239 oidSignatureDSAWithSHA256
= asn1
.ObjectIdentifier
{2, 16, 840, 1, 101, 4, 3, 2}
240 oidSignatureECDSAWithSHA1
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 1}
241 oidSignatureECDSAWithSHA256
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 3, 2}
242 oidSignatureECDSAWithSHA384
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 3, 3}
243 oidSignatureECDSAWithSHA512
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 4, 3, 4}
246 var signatureAlgorithmDetails
= []struct {
247 algo SignatureAlgorithm
248 oid asn1
.ObjectIdentifier
249 pubKeyAlgo PublicKeyAlgorithm
252 {MD2WithRSA
, oidSignatureMD2WithRSA
, RSA
, crypto
.Hash(0) /* no value for MD2 */},
253 {MD5WithRSA
, oidSignatureMD5WithRSA
, RSA
, crypto
.MD5
},
254 {SHA1WithRSA
, oidSignatureSHA1WithRSA
, RSA
, crypto
.SHA1
},
255 {SHA256WithRSA
, oidSignatureSHA256WithRSA
, RSA
, crypto
.SHA256
},
256 {SHA384WithRSA
, oidSignatureSHA384WithRSA
, RSA
, crypto
.SHA384
},
257 {SHA512WithRSA
, oidSignatureSHA512WithRSA
, RSA
, crypto
.SHA512
},
258 {DSAWithSHA1
, oidSignatureDSAWithSHA1
, DSA
, crypto
.SHA1
},
259 {DSAWithSHA256
, oidSignatureDSAWithSHA256
, DSA
, crypto
.SHA256
},
260 {ECDSAWithSHA1
, oidSignatureECDSAWithSHA1
, ECDSA
, crypto
.SHA1
},
261 {ECDSAWithSHA256
, oidSignatureECDSAWithSHA256
, ECDSA
, crypto
.SHA256
},
262 {ECDSAWithSHA384
, oidSignatureECDSAWithSHA384
, ECDSA
, crypto
.SHA384
},
263 {ECDSAWithSHA512
, oidSignatureECDSAWithSHA512
, ECDSA
, crypto
.SHA512
},
266 func getSignatureAlgorithmFromOID(oid asn1
.ObjectIdentifier
) SignatureAlgorithm
{
267 for _
, details
:= range signatureAlgorithmDetails
{
268 if oid
.Equal(details
.oid
) {
272 return UnknownSignatureAlgorithm
275 // RFC 3279, 2.3 Public Key Algorithms
277 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
278 // rsadsi(113549) pkcs(1) 1 }
280 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
282 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
283 // x9-57(10040) x9cm(4) 1 }
285 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
287 // id-ecPublicKey OBJECT IDENTIFIER ::= {
288 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
290 oidPublicKeyRSA
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 1, 1}
291 oidPublicKeyDSA
= asn1
.ObjectIdentifier
{1, 2, 840, 10040, 4, 1}
292 oidPublicKeyECDSA
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 2, 1}
295 func getPublicKeyAlgorithmFromOID(oid asn1
.ObjectIdentifier
) PublicKeyAlgorithm
{
297 case oid
.Equal(oidPublicKeyRSA
):
299 case oid
.Equal(oidPublicKeyDSA
):
301 case oid
.Equal(oidPublicKeyECDSA
):
304 return UnknownPublicKeyAlgorithm
307 // RFC 5480, 2.1.1.1. Named Curve
309 // secp224r1 OBJECT IDENTIFIER ::= {
310 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
312 // secp256r1 OBJECT IDENTIFIER ::= {
313 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
316 // secp384r1 OBJECT IDENTIFIER ::= {
317 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
319 // secp521r1 OBJECT IDENTIFIER ::= {
320 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
322 // NB: secp256r1 is equivalent to prime256v1
324 oidNamedCurveP224
= asn1
.ObjectIdentifier
{1, 3, 132, 0, 33}
325 oidNamedCurveP256
= asn1
.ObjectIdentifier
{1, 2, 840, 10045, 3, 1, 7}
326 oidNamedCurveP384
= asn1
.ObjectIdentifier
{1, 3, 132, 0, 34}
327 oidNamedCurveP521
= asn1
.ObjectIdentifier
{1, 3, 132, 0, 35}
330 func namedCurveFromOID(oid asn1
.ObjectIdentifier
) elliptic
.Curve
{
332 case oid
.Equal(oidNamedCurveP224
):
333 return elliptic
.P224()
334 case oid
.Equal(oidNamedCurveP256
):
335 return elliptic
.P256()
336 case oid
.Equal(oidNamedCurveP384
):
337 return elliptic
.P384()
338 case oid
.Equal(oidNamedCurveP521
):
339 return elliptic
.P521()
344 func oidFromNamedCurve(curve elliptic
.Curve
) (asn1
.ObjectIdentifier
, bool) {
346 case elliptic
.P224():
347 return oidNamedCurveP224
, true
348 case elliptic
.P256():
349 return oidNamedCurveP256
, true
350 case elliptic
.P384():
351 return oidNamedCurveP384
, true
352 case elliptic
.P521():
353 return oidNamedCurveP521
, true
359 // KeyUsage represents the set of actions that are valid for a given key. It's
360 // a bitmap of the KeyUsage* constants.
364 KeyUsageDigitalSignature KeyUsage
= 1 << iota
365 KeyUsageContentCommitment
366 KeyUsageKeyEncipherment
367 KeyUsageDataEncipherment
375 // RFC 5280, 4.2.1.12 Extended Key Usage
377 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
379 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
381 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
382 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
383 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
384 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
385 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
386 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
388 oidExtKeyUsageAny
= asn1
.ObjectIdentifier
{2, 5, 29, 37, 0}
389 oidExtKeyUsageServerAuth
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 1}
390 oidExtKeyUsageClientAuth
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 2}
391 oidExtKeyUsageCodeSigning
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 3}
392 oidExtKeyUsageEmailProtection
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 4}
393 oidExtKeyUsageIPSECEndSystem
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 5}
394 oidExtKeyUsageIPSECTunnel
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 6}
395 oidExtKeyUsageIPSECUser
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 7}
396 oidExtKeyUsageTimeStamping
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 8}
397 oidExtKeyUsageOCSPSigning
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 3, 9}
398 oidExtKeyUsageMicrosoftServerGatedCrypto
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
399 oidExtKeyUsageNetscapeServerGatedCrypto
= asn1
.ObjectIdentifier
{2, 16, 840, 1, 113730, 4, 1}
402 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
403 // Each of the ExtKeyUsage* constants define a unique action.
407 ExtKeyUsageAny ExtKeyUsage
= iota
408 ExtKeyUsageServerAuth
409 ExtKeyUsageClientAuth
410 ExtKeyUsageCodeSigning
411 ExtKeyUsageEmailProtection
412 ExtKeyUsageIPSECEndSystem
413 ExtKeyUsageIPSECTunnel
415 ExtKeyUsageTimeStamping
416 ExtKeyUsageOCSPSigning
417 ExtKeyUsageMicrosoftServerGatedCrypto
418 ExtKeyUsageNetscapeServerGatedCrypto
421 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
422 var extKeyUsageOIDs
= []struct {
423 extKeyUsage ExtKeyUsage
424 oid asn1
.ObjectIdentifier
426 {ExtKeyUsageAny
, oidExtKeyUsageAny
},
427 {ExtKeyUsageServerAuth
, oidExtKeyUsageServerAuth
},
428 {ExtKeyUsageClientAuth
, oidExtKeyUsageClientAuth
},
429 {ExtKeyUsageCodeSigning
, oidExtKeyUsageCodeSigning
},
430 {ExtKeyUsageEmailProtection
, oidExtKeyUsageEmailProtection
},
431 {ExtKeyUsageIPSECEndSystem
, oidExtKeyUsageIPSECEndSystem
},
432 {ExtKeyUsageIPSECTunnel
, oidExtKeyUsageIPSECTunnel
},
433 {ExtKeyUsageIPSECUser
, oidExtKeyUsageIPSECUser
},
434 {ExtKeyUsageTimeStamping
, oidExtKeyUsageTimeStamping
},
435 {ExtKeyUsageOCSPSigning
, oidExtKeyUsageOCSPSigning
},
436 {ExtKeyUsageMicrosoftServerGatedCrypto
, oidExtKeyUsageMicrosoftServerGatedCrypto
},
437 {ExtKeyUsageNetscapeServerGatedCrypto
, oidExtKeyUsageNetscapeServerGatedCrypto
},
440 func extKeyUsageFromOID(oid asn1
.ObjectIdentifier
) (eku ExtKeyUsage
, ok
bool) {
441 for _
, pair
:= range extKeyUsageOIDs
{
442 if oid
.Equal(pair
.oid
) {
443 return pair
.extKeyUsage
, true
449 func oidFromExtKeyUsage(eku ExtKeyUsage
) (oid asn1
.ObjectIdentifier
, ok
bool) {
450 for _
, pair
:= range extKeyUsageOIDs
{
451 if eku
== pair
.extKeyUsage
{
452 return pair
.oid
, true
458 // A Certificate represents an X.509 certificate.
459 type Certificate
struct {
460 Raw
[]byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
461 RawTBSCertificate
[]byte // Certificate part of raw ASN.1 DER content.
462 RawSubjectPublicKeyInfo
[]byte // DER encoded SubjectPublicKeyInfo.
463 RawSubject
[]byte // DER encoded Subject
464 RawIssuer
[]byte // DER encoded Issuer
467 SignatureAlgorithm SignatureAlgorithm
469 PublicKeyAlgorithm PublicKeyAlgorithm
470 PublicKey
interface{}
473 SerialNumber
*big
.Int
476 NotBefore
, NotAfter time
.Time
// Validity bounds.
479 // Extensions contains raw X.509 extensions. When parsing certificates,
480 // this can be used to extract non-critical extensions that are not
481 // parsed by this package. When marshaling certificates, the Extensions
482 // field is ignored, see ExtraExtensions.
483 Extensions
[]pkix
.Extension
485 // ExtraExtensions contains extensions to be copied, raw, into any
486 // marshaled certificates. Values override any extensions that would
487 // otherwise be produced based on the other fields. The ExtraExtensions
488 // field is not populated when parsing certificates, see Extensions.
489 ExtraExtensions
[]pkix
.Extension
491 ExtKeyUsage
[]ExtKeyUsage
// Sequence of extended key usages.
492 UnknownExtKeyUsage
[]asn1
.ObjectIdentifier
// Encountered extended key usages unknown to this package.
494 BasicConstraintsValid
bool // if true then the next two fields are valid.
499 AuthorityKeyId
[]byte
501 // RFC 5280, 4.2.2.1 (Authority Information Access)
503 IssuingCertificateURL
[]string
505 // Subject Alternate Name values
507 EmailAddresses
[]string
511 PermittedDNSDomainsCritical
bool // if true then the name constraints are marked critical.
512 PermittedDNSDomains
[]string
514 // CRL Distribution Points
515 CRLDistributionPoints
[]string
517 PolicyIdentifiers
[]asn1
.ObjectIdentifier
520 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
521 // involves algorithms that are not currently implemented.
522 var ErrUnsupportedAlgorithm
= errors
.New("x509: cannot verify signature: algorithm unimplemented")
524 // ConstraintViolationError results when a requested usage is not permitted by
525 // a certificate. For example: checking a signature when the public key isn't a
526 // certificate signing key.
527 type ConstraintViolationError
struct{}
529 func (ConstraintViolationError
) Error() string {
530 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
533 func (c
*Certificate
) Equal(other
*Certificate
) bool {
534 return bytes
.Equal(c
.Raw
, other
.Raw
)
537 // Entrust have a broken root certificate (CN=Entrust.net Certification
538 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
539 // according to PKIX.
540 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
541 // from the Basic Constraints requirement.
542 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
544 // TODO(agl): remove this hack once their reissued root is sufficiently
546 var entrustBrokenSPKI
= []byte{
547 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
548 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
549 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
550 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
551 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
552 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
553 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
554 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
555 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
556 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
557 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
558 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
559 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
560 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
561 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
562 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
563 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
564 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
565 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
566 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
567 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
568 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
569 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
570 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
571 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
572 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
573 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
574 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
575 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
576 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
577 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
578 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
579 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
580 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
581 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
582 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
583 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
586 // CheckSignatureFrom verifies that the signature on c is a valid signature
588 func (c
*Certificate
) CheckSignatureFrom(parent
*Certificate
) (err error
) {
589 // RFC 5280, 4.2.1.9:
590 // "If the basic constraints extension is not present in a version 3
591 // certificate, or the extension is present but the cA boolean is not
592 // asserted, then the certified public key MUST NOT be used to verify
593 // certificate signatures."
594 // (except for Entrust, see comment above entrustBrokenSPKI)
595 if (parent
.Version
== 3 && !parent
.BasicConstraintsValid ||
596 parent
.BasicConstraintsValid
&& !parent
.IsCA
) &&
597 !bytes
.Equal(c
.RawSubjectPublicKeyInfo
, entrustBrokenSPKI
) {
598 return ConstraintViolationError
{}
601 if parent
.KeyUsage
!= 0 && parent
.KeyUsage
&KeyUsageCertSign
== 0 {
602 return ConstraintViolationError
{}
605 if parent
.PublicKeyAlgorithm
== UnknownPublicKeyAlgorithm
{
606 return ErrUnsupportedAlgorithm
609 // TODO(agl): don't ignore the path length constraint.
611 return parent
.CheckSignature(c
.SignatureAlgorithm
, c
.RawTBSCertificate
, c
.Signature
)
614 // CheckSignature verifies that signature is a valid signature over signed from
616 func (c
*Certificate
) CheckSignature(algo SignatureAlgorithm
, signed
, signature
[]byte) (err error
) {
617 var hashType crypto
.Hash
620 case SHA1WithRSA
, DSAWithSHA1
, ECDSAWithSHA1
:
621 hashType
= crypto
.SHA1
622 case SHA256WithRSA
, DSAWithSHA256
, ECDSAWithSHA256
:
623 hashType
= crypto
.SHA256
624 case SHA384WithRSA
, ECDSAWithSHA384
:
625 hashType
= crypto
.SHA384
626 case SHA512WithRSA
, ECDSAWithSHA512
:
627 hashType
= crypto
.SHA512
629 return ErrUnsupportedAlgorithm
632 if !hashType
.Available() {
633 return ErrUnsupportedAlgorithm
640 switch pub
:= c
.PublicKey
.(type) {
642 return rsa
.VerifyPKCS1v15(pub
, hashType
, digest
, signature
)
644 dsaSig
:= new(dsaSignature
)
645 if _
, err
:= asn1
.Unmarshal(signature
, dsaSig
); err
!= nil {
648 if dsaSig
.R
.Sign() <= 0 || dsaSig
.S
.Sign() <= 0 {
649 return errors
.New("x509: DSA signature contained zero or negative values")
651 if !dsa
.Verify(pub
, digest
, dsaSig
.R
, dsaSig
.S
) {
652 return errors
.New("x509: DSA verification failure")
655 case *ecdsa
.PublicKey
:
656 ecdsaSig
:= new(ecdsaSignature
)
657 if _
, err
:= asn1
.Unmarshal(signature
, ecdsaSig
); err
!= nil {
660 if ecdsaSig
.R
.Sign() <= 0 || ecdsaSig
.S
.Sign() <= 0 {
661 return errors
.New("x509: ECDSA signature contained zero or negative values")
663 if !ecdsa
.Verify(pub
, digest
, ecdsaSig
.R
, ecdsaSig
.S
) {
664 return errors
.New("x509: ECDSA verification failure")
668 return ErrUnsupportedAlgorithm
671 // CheckCRLSignature checks that the signature in crl is from c.
672 func (c
*Certificate
) CheckCRLSignature(crl
*pkix
.CertificateList
) (err error
) {
673 algo
:= getSignatureAlgorithmFromOID(crl
.SignatureAlgorithm
.Algorithm
)
674 return c
.CheckSignature(algo
, crl
.TBSCertList
.Raw
, crl
.SignatureValue
.RightAlign())
677 type UnhandledCriticalExtension
struct{}
679 func (h UnhandledCriticalExtension
) Error() string {
680 return "x509: unhandled critical extension"
683 type basicConstraints
struct {
684 IsCA
bool `asn1:"optional"`
685 MaxPathLen
int `asn1:"optional,default:-1"`
689 type policyInformation
struct {
690 Policy asn1
.ObjectIdentifier
691 // policyQualifiers omitted
694 // RFC 5280, 4.2.1.10
695 type nameConstraints
struct {
696 Permitted
[]generalSubtree
`asn1:"optional,tag:0"`
697 Excluded
[]generalSubtree
`asn1:"optional,tag:1"`
700 type generalSubtree
struct {
701 Name
string `asn1:"tag:2,optional,ia5"`
705 type authorityInfoAccess
struct {
706 Method asn1
.ObjectIdentifier
707 Location asn1
.RawValue
710 // RFC 5280, 4.2.1.14
711 type distributionPoint
struct {
712 DistributionPoint distributionPointName
`asn1:"optional,tag:0"`
713 Reason asn1
.BitString
`asn1:"optional,tag:1"`
714 CRLIssuer asn1
.RawValue
`asn1:"optional,tag:2"`
717 type distributionPointName
struct {
718 FullName asn1
.RawValue
`asn1:"optional,tag:0"`
719 RelativeName pkix
.RDNSequence
`asn1:"optional,tag:1"`
722 func parsePublicKey(algo PublicKeyAlgorithm
, keyData
*publicKeyInfo
) (interface{}, error
) {
723 asn1Data
:= keyData
.PublicKey
.RightAlign()
726 p
:= new(rsaPublicKey
)
727 _
, err
:= asn1
.Unmarshal(asn1Data
, p
)
733 return nil, errors
.New("x509: RSA modulus is not a positive number")
736 return nil, errors
.New("x509: RSA public exponent is not a positive number")
739 pub
:= &rsa
.PublicKey
{
746 _
, err
:= asn1
.Unmarshal(asn1Data
, &p
)
750 paramsData
:= keyData
.Algorithm
.Parameters
.FullBytes
751 params
:= new(dsaAlgorithmParameters
)
752 _
, err
= asn1
.Unmarshal(paramsData
, params
)
756 if p
.Sign() <= 0 || params
.P
.Sign() <= 0 || params
.Q
.Sign() <= 0 || params
.G
.Sign() <= 0 {
757 return nil, errors
.New("x509: zero or negative DSA parameter")
759 pub
:= &dsa
.PublicKey
{
760 Parameters
: dsa
.Parameters
{
769 paramsData
:= keyData
.Algorithm
.Parameters
.FullBytes
770 namedCurveOID
:= new(asn1
.ObjectIdentifier
)
771 _
, err
:= asn1
.Unmarshal(paramsData
, namedCurveOID
)
775 namedCurve
:= namedCurveFromOID(*namedCurveOID
)
776 if namedCurve
== nil {
777 return nil, errors
.New("x509: unsupported elliptic curve")
779 x
, y
:= elliptic
.Unmarshal(namedCurve
, asn1Data
)
781 return nil, errors
.New("x509: failed to unmarshal elliptic curve point")
783 pub
:= &ecdsa
.PublicKey
{
794 func parseSANExtension(value
[]byte) (dnsNames
, emailAddresses
[]string, ipAddresses
[]net
.IP
, err error
) {
797 // SubjectAltName ::= GeneralNames
799 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
801 // GeneralName ::= CHOICE {
802 // otherName [0] OtherName,
803 // rfc822Name [1] IA5String,
804 // dNSName [2] IA5String,
805 // x400Address [3] ORAddress,
806 // directoryName [4] Name,
807 // ediPartyName [5] EDIPartyName,
808 // uniformResourceIdentifier [6] IA5String,
809 // iPAddress [7] OCTET STRING,
810 // registeredID [8] OBJECT IDENTIFIER }
811 var seq asn1
.RawValue
812 if _
, err
= asn1
.Unmarshal(value
, &seq
); err
!= nil {
815 if !seq
.IsCompound || seq
.Tag
!= 16 || seq
.Class
!= 0 {
816 err
= asn1
.StructuralError
{Msg
: "bad SAN sequence"}
823 rest
, err
= asn1
.Unmarshal(rest
, &v
)
829 emailAddresses
= append(emailAddresses
, string(v
.Bytes
))
831 dnsNames
= append(dnsNames
, string(v
.Bytes
))
833 switch len(v
.Bytes
) {
834 case net
.IPv4len
, net
.IPv6len
:
835 ipAddresses
= append(ipAddresses
, v
.Bytes
)
837 err
= errors
.New("x509: certificate contained IP address of length " + strconv
.Itoa(len(v
.Bytes
)))
846 func parseCertificate(in
*certificate
) (*Certificate
, error
) {
847 out
:= new(Certificate
)
849 out
.RawTBSCertificate
= in
.TBSCertificate
.Raw
850 out
.RawSubjectPublicKeyInfo
= in
.TBSCertificate
.PublicKey
.Raw
851 out
.RawSubject
= in
.TBSCertificate
.Subject
.FullBytes
852 out
.RawIssuer
= in
.TBSCertificate
.Issuer
.FullBytes
854 out
.Signature
= in
.SignatureValue
.RightAlign()
855 out
.SignatureAlgorithm
=
856 getSignatureAlgorithmFromOID(in
.TBSCertificate
.SignatureAlgorithm
.Algorithm
)
858 out
.PublicKeyAlgorithm
=
859 getPublicKeyAlgorithmFromOID(in
.TBSCertificate
.PublicKey
.Algorithm
.Algorithm
)
861 out
.PublicKey
, err
= parsePublicKey(out
.PublicKeyAlgorithm
, &in
.TBSCertificate
.PublicKey
)
866 if in
.TBSCertificate
.SerialNumber
.Sign() < 0 {
867 return nil, errors
.New("x509: negative serial number")
870 out
.Version
= in
.TBSCertificate
.Version
+ 1
871 out
.SerialNumber
= in
.TBSCertificate
.SerialNumber
873 var issuer
, subject pkix
.RDNSequence
874 if _
, err
:= asn1
.Unmarshal(in
.TBSCertificate
.Subject
.FullBytes
, &subject
); err
!= nil {
877 if _
, err
:= asn1
.Unmarshal(in
.TBSCertificate
.Issuer
.FullBytes
, &issuer
); err
!= nil {
881 out
.Issuer
.FillFromRDNSequence(&issuer
)
882 out
.Subject
.FillFromRDNSequence(&subject
)
884 out
.NotBefore
= in
.TBSCertificate
.Validity
.NotBefore
885 out
.NotAfter
= in
.TBSCertificate
.Validity
.NotAfter
887 for _
, e
:= range in
.TBSCertificate
.Extensions
{
888 out
.Extensions
= append(out
.Extensions
, e
)
890 if len(e
.Id
) == 4 && e
.Id
[0] == 2 && e
.Id
[1] == 5 && e
.Id
[2] == 29 {
894 var usageBits asn1
.BitString
895 _
, err
:= asn1
.Unmarshal(e
.Value
, &usageBits
)
899 for i
:= 0; i
< 9; i
++ {
900 if usageBits
.At(i
) != 0 {
901 usage |
= 1 << uint(i
)
904 out
.KeyUsage
= KeyUsage(usage
)
909 var constraints basicConstraints
910 _
, err
:= asn1
.Unmarshal(e
.Value
, &constraints
)
913 out
.BasicConstraintsValid
= true
914 out
.IsCA
= constraints
.IsCA
915 out
.MaxPathLen
= constraints
.MaxPathLen
919 out
.DNSNames
, out
.EmailAddresses
, out
.IPAddresses
, err
= parseSANExtension(e
.Value
)
924 if len(out
.DNSNames
) > 0 ||
len(out
.EmailAddresses
) > 0 ||
len(out
.IPAddresses
) > 0 {
927 // If we didn't parse any of the names then we
928 // fall through to the critical check below.
931 // RFC 5280, 4.2.1.10
933 // NameConstraints ::= SEQUENCE {
934 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
935 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
937 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
939 // GeneralSubtree ::= SEQUENCE {
941 // minimum [0] BaseDistance DEFAULT 0,
942 // maximum [1] BaseDistance OPTIONAL }
944 // BaseDistance ::= INTEGER (0..MAX)
946 var constraints nameConstraints
947 _
, err
:= asn1
.Unmarshal(e
.Value
, &constraints
)
952 if len(constraints
.Excluded
) > 0 && e
.Critical
{
953 return out
, UnhandledCriticalExtension
{}
956 for _
, subtree
:= range constraints
.Permitted
{
957 if len(subtree
.Name
) == 0 {
959 return out
, UnhandledCriticalExtension
{}
963 out
.PermittedDNSDomains
= append(out
.PermittedDNSDomains
, subtree
.Name
)
968 // RFC 5280, 4.2.1.14
970 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
972 // DistributionPoint ::= SEQUENCE {
973 // distributionPoint [0] DistributionPointName OPTIONAL,
974 // reasons [1] ReasonFlags OPTIONAL,
975 // cRLIssuer [2] GeneralNames OPTIONAL }
977 // DistributionPointName ::= CHOICE {
978 // fullName [0] GeneralNames,
979 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
981 var cdp
[]distributionPoint
982 _
, err
:= asn1
.Unmarshal(e
.Value
, &cdp
)
987 for _
, dp
:= range cdp
{
989 _
, err
= asn1
.Unmarshal(dp
.DistributionPoint
.FullName
.Bytes
, &n
)
995 out
.CRLDistributionPoints
= append(out
.CRLDistributionPoints
, string(n
.Bytes
))
1001 // RFC 5280, 4.2.1.1
1003 _
, err
= asn1
.Unmarshal(e
.Value
, &a
)
1007 out
.AuthorityKeyId
= a
.Id
1011 // RFC 5280, 4.2.1.12. Extended Key Usage
1013 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1015 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1017 // KeyPurposeId ::= OBJECT IDENTIFIER
1019 var keyUsage
[]asn1
.ObjectIdentifier
1020 _
, err
= asn1
.Unmarshal(e
.Value
, &keyUsage
)
1025 for _
, u
:= range keyUsage
{
1026 if extKeyUsage
, ok
:= extKeyUsageFromOID(u
); ok
{
1027 out
.ExtKeyUsage
= append(out
.ExtKeyUsage
, extKeyUsage
)
1029 out
.UnknownExtKeyUsage
= append(out
.UnknownExtKeyUsage
, u
)
1036 // RFC 5280, 4.2.1.2
1038 _
, err
= asn1
.Unmarshal(e
.Value
, &keyid
)
1042 out
.SubjectKeyId
= keyid
1046 // RFC 5280 4.2.1.4: Certificate Policies
1047 var policies
[]policyInformation
1048 if _
, err
= asn1
.Unmarshal(e
.Value
, &policies
); err
!= nil {
1051 out
.PolicyIdentifiers
= make([]asn1
.ObjectIdentifier
, len(policies
))
1052 for i
, policy
:= range policies
{
1053 out
.PolicyIdentifiers
[i
] = policy
.Policy
1056 } else if e
.Id
.Equal(oidExtensionAuthorityInfoAccess
) {
1057 // RFC 5280 4.2.2.1: Authority Information Access
1058 var aia
[]authorityInfoAccess
1059 if _
, err
= asn1
.Unmarshal(e
.Value
, &aia
); err
!= nil {
1063 for _
, v
:= range aia
{
1064 // GeneralName: uniformResourceIdentifier [6] IA5String
1065 if v
.Location
.Tag
!= 6 {
1068 if v
.Method
.Equal(oidAuthorityInfoAccessOcsp
) {
1069 out
.OCSPServer
= append(out
.OCSPServer
, string(v
.Location
.Bytes
))
1070 } else if v
.Method
.Equal(oidAuthorityInfoAccessIssuers
) {
1071 out
.IssuingCertificateURL
= append(out
.IssuingCertificateURL
, string(v
.Location
.Bytes
))
1077 return out
, UnhandledCriticalExtension
{}
1084 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1085 func ParseCertificate(asn1Data
[]byte) (*Certificate
, error
) {
1086 var cert certificate
1087 rest
, err
:= asn1
.Unmarshal(asn1Data
, &cert
)
1092 return nil, asn1
.SyntaxError
{Msg
: "trailing data"}
1095 return parseCertificate(&cert
)
1098 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1099 // data. The certificates must be concatenated with no intermediate padding.
1100 func ParseCertificates(asn1Data
[]byte) ([]*Certificate
, error
) {
1101 var v
[]*certificate
1103 for len(asn1Data
) > 0 {
1104 cert
:= new(certificate
)
1106 asn1Data
, err
= asn1
.Unmarshal(asn1Data
, cert
)
1113 ret
:= make([]*Certificate
, len(v
))
1114 for i
, ci
:= range v
{
1115 cert
, err
:= parseCertificate(ci
)
1125 func reverseBitsInAByte(in
byte) byte {
1127 b2
:= b1
>>2&0x33 | b1
<<2&0xcc
1128 b3
:= b2
>>1&0x55 | b2
<<1&0xaa
1133 oidExtensionSubjectKeyId
= []int{2, 5, 29, 14}
1134 oidExtensionKeyUsage
= []int{2, 5, 29, 15}
1135 oidExtensionExtendedKeyUsage
= []int{2, 5, 29, 37}
1136 oidExtensionAuthorityKeyId
= []int{2, 5, 29, 35}
1137 oidExtensionBasicConstraints
= []int{2, 5, 29, 19}
1138 oidExtensionSubjectAltName
= []int{2, 5, 29, 17}
1139 oidExtensionCertificatePolicies
= []int{2, 5, 29, 32}
1140 oidExtensionNameConstraints
= []int{2, 5, 29, 30}
1141 oidExtensionCRLDistributionPoints
= []int{2, 5, 29, 31}
1142 oidExtensionAuthorityInfoAccess
= []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1146 oidAuthorityInfoAccessOcsp
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 48, 1}
1147 oidAuthorityInfoAccessIssuers
= asn1
.ObjectIdentifier
{1, 3, 6, 1, 5, 5, 7, 48, 2}
1150 // oidNotInExtensions returns whether an extension with the given oid exists in
1152 func oidInExtensions(oid asn1
.ObjectIdentifier
, extensions
[]pkix
.Extension
) bool {
1153 for _
, e
:= range extensions
{
1154 if e
.Id
.Equal(oid
) {
1161 // marshalSANs marshals a list of addresses into a the contents of an X.509
1162 // SubjectAlternativeName extension.
1163 func marshalSANs(dnsNames
, emailAddresses
[]string, ipAddresses
[]net
.IP
) (derBytes
[]byte, err error
) {
1164 var rawValues
[]asn1
.RawValue
1165 for _
, name
:= range dnsNames
{
1166 rawValues
= append(rawValues
, asn1
.RawValue
{Tag
: 2, Class
: 2, Bytes
: []byte(name
)})
1168 for _
, email
:= range emailAddresses
{
1169 rawValues
= append(rawValues
, asn1
.RawValue
{Tag
: 1, Class
: 2, Bytes
: []byte(email
)})
1171 for _
, rawIP
:= range ipAddresses
{
1172 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1177 rawValues
= append(rawValues
, asn1
.RawValue
{Tag
: 7, Class
: 2, Bytes
: ip
})
1179 return asn1
.Marshal(rawValues
)
1182 func buildExtensions(template
*Certificate
) (ret
[]pkix
.Extension
, err error
) {
1183 ret
= make([]pkix
.Extension
, 10 /* maximum number of elements. */)
1186 if template
.KeyUsage
!= 0 &&
1187 !oidInExtensions(oidExtensionKeyUsage
, template
.ExtraExtensions
) {
1188 ret
[n
].Id
= oidExtensionKeyUsage
1189 ret
[n
].Critical
= true
1192 a
[0] = reverseBitsInAByte(byte(template
.KeyUsage
))
1193 a
[1] = reverseBitsInAByte(byte(template
.KeyUsage
>> 8))
1200 ret
[n
].Value
, err
= asn1
.Marshal(asn1
.BitString
{Bytes
: a
[0:l
], BitLength
: l
* 8})
1207 if (len(template
.ExtKeyUsage
) > 0 ||
len(template
.UnknownExtKeyUsage
) > 0) &&
1208 !oidInExtensions(oidExtensionExtendedKeyUsage
, template
.ExtraExtensions
) {
1209 ret
[n
].Id
= oidExtensionExtendedKeyUsage
1211 var oids
[]asn1
.ObjectIdentifier
1212 for _
, u
:= range template
.ExtKeyUsage
{
1213 if oid
, ok
:= oidFromExtKeyUsage(u
); ok
{
1214 oids
= append(oids
, oid
)
1216 panic("internal error")
1220 oids
= append(oids
, template
.UnknownExtKeyUsage
...)
1222 ret
[n
].Value
, err
= asn1
.Marshal(oids
)
1229 if template
.BasicConstraintsValid
&& !oidInExtensions(oidExtensionBasicConstraints
, template
.ExtraExtensions
) {
1230 ret
[n
].Id
= oidExtensionBasicConstraints
1231 ret
[n
].Value
, err
= asn1
.Marshal(basicConstraints
{template
.IsCA
, template
.MaxPathLen
})
1232 ret
[n
].Critical
= true
1239 if len(template
.SubjectKeyId
) > 0 && !oidInExtensions(oidExtensionSubjectKeyId
, template
.ExtraExtensions
) {
1240 ret
[n
].Id
= oidExtensionSubjectKeyId
1241 ret
[n
].Value
, err
= asn1
.Marshal(template
.SubjectKeyId
)
1248 if len(template
.AuthorityKeyId
) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId
, template
.ExtraExtensions
) {
1249 ret
[n
].Id
= oidExtensionAuthorityKeyId
1250 ret
[n
].Value
, err
= asn1
.Marshal(authKeyId
{template
.AuthorityKeyId
})
1257 if (len(template
.OCSPServer
) > 0 ||
len(template
.IssuingCertificateURL
) > 0) &&
1258 !oidInExtensions(oidExtensionAuthorityInfoAccess
, template
.ExtraExtensions
) {
1259 ret
[n
].Id
= oidExtensionAuthorityInfoAccess
1260 var aiaValues
[]authorityInfoAccess
1261 for _
, name
:= range template
.OCSPServer
{
1262 aiaValues
= append(aiaValues
, authorityInfoAccess
{
1263 Method
: oidAuthorityInfoAccessOcsp
,
1264 Location
: asn1
.RawValue
{Tag
: 6, Class
: 2, Bytes
: []byte(name
)},
1267 for _
, name
:= range template
.IssuingCertificateURL
{
1268 aiaValues
= append(aiaValues
, authorityInfoAccess
{
1269 Method
: oidAuthorityInfoAccessIssuers
,
1270 Location
: asn1
.RawValue
{Tag
: 6, Class
: 2, Bytes
: []byte(name
)},
1273 ret
[n
].Value
, err
= asn1
.Marshal(aiaValues
)
1280 if (len(template
.DNSNames
) > 0 ||
len(template
.EmailAddresses
) > 0 ||
len(template
.IPAddresses
) > 0) &&
1281 !oidInExtensions(oidExtensionSubjectAltName
, template
.ExtraExtensions
) {
1282 ret
[n
].Id
= oidExtensionSubjectAltName
1283 ret
[n
].Value
, err
= marshalSANs(template
.DNSNames
, template
.EmailAddresses
, template
.IPAddresses
)
1290 if len(template
.PolicyIdentifiers
) > 0 &&
1291 !oidInExtensions(oidExtensionCertificatePolicies
, template
.ExtraExtensions
) {
1292 ret
[n
].Id
= oidExtensionCertificatePolicies
1293 policies
:= make([]policyInformation
, len(template
.PolicyIdentifiers
))
1294 for i
, policy
:= range template
.PolicyIdentifiers
{
1295 policies
[i
].Policy
= policy
1297 ret
[n
].Value
, err
= asn1
.Marshal(policies
)
1304 if len(template
.PermittedDNSDomains
) > 0 &&
1305 !oidInExtensions(oidExtensionNameConstraints
, template
.ExtraExtensions
) {
1306 ret
[n
].Id
= oidExtensionNameConstraints
1307 ret
[n
].Critical
= template
.PermittedDNSDomainsCritical
1309 var out nameConstraints
1310 out
.Permitted
= make([]generalSubtree
, len(template
.PermittedDNSDomains
))
1311 for i
, permitted
:= range template
.PermittedDNSDomains
{
1312 out
.Permitted
[i
] = generalSubtree
{Name
: permitted
}
1314 ret
[n
].Value
, err
= asn1
.Marshal(out
)
1321 if len(template
.CRLDistributionPoints
) > 0 &&
1322 !oidInExtensions(oidExtensionCRLDistributionPoints
, template
.ExtraExtensions
) {
1323 ret
[n
].Id
= oidExtensionCRLDistributionPoints
1325 var crlDp
[]distributionPoint
1326 for _
, name
:= range template
.CRLDistributionPoints
{
1327 rawFullName
, _
:= asn1
.Marshal(asn1
.RawValue
{Tag
: 6, Class
: 2, Bytes
: []byte(name
)})
1329 dp
:= distributionPoint
{
1330 DistributionPoint
: distributionPointName
{
1331 FullName
: asn1
.RawValue
{Tag
: 0, Class
: 2, Bytes
: rawFullName
},
1334 crlDp
= append(crlDp
, dp
)
1337 ret
[n
].Value
, err
= asn1
.Marshal(crlDp
)
1344 // Adding another extension here? Remember to update the maximum number
1345 // of elements in the make() at the top of the function.
1347 return append(ret
[:n
], template
.ExtraExtensions
...), nil
1350 func subjectBytes(cert
*Certificate
) ([]byte, error
) {
1351 if len(cert
.RawSubject
) > 0 {
1352 return cert
.RawSubject
, nil
1355 return asn1
.Marshal(cert
.Subject
.ToRDNSequence())
1358 // signingParamsForPrivateKey returns the parameters to use for signing with
1359 // priv. If requestedSigAlgo is not zero then it overrides the default
1360 // signature algorithm.
1361 func signingParamsForPrivateKey(priv
interface{}, requestedSigAlgo SignatureAlgorithm
) (hashFunc crypto
.Hash
, sigAlgo pkix
.AlgorithmIdentifier
, err error
) {
1362 var pubType PublicKeyAlgorithm
1364 switch priv
:= priv
.(type) {
1365 case *rsa
.PrivateKey
:
1367 sigAlgo
.Algorithm
= oidSignatureSHA256WithRSA
1368 hashFunc
= crypto
.SHA256
1370 case *ecdsa
.PrivateKey
:
1374 case elliptic
.P224(), elliptic
.P256():
1375 hashFunc
= crypto
.SHA256
1376 sigAlgo
.Algorithm
= oidSignatureECDSAWithSHA256
1377 case elliptic
.P384():
1378 hashFunc
= crypto
.SHA384
1379 sigAlgo
.Algorithm
= oidSignatureECDSAWithSHA384
1380 case elliptic
.P521():
1381 hashFunc
= crypto
.SHA512
1382 sigAlgo
.Algorithm
= oidSignatureECDSAWithSHA512
1384 err
= errors
.New("x509: unknown elliptic curve")
1388 err
= errors
.New("x509: only RSA and ECDSA private keys supported")
1395 if requestedSigAlgo
== 0 {
1400 for _
, details
:= range signatureAlgorithmDetails
{
1401 if details
.algo
== requestedSigAlgo
{
1402 if details
.pubKeyAlgo
!= pubType
{
1403 err
= errors
.New("x509: requested SignatureAlgorithm does not match private key type")
1406 sigAlgo
.Algorithm
, hashFunc
= details
.oid
, details
.hash
1408 err
= errors
.New("x509: cannot sign with hash function requested")
1417 err
= errors
.New("x509: unknown SignatureAlgorithm")
1423 // CreateCertificate creates a new certificate based on a template. The
1424 // following members of template are used: SerialNumber, Subject, NotBefore,
1425 // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
1426 // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
1427 // PermittedDNSDomains, SignatureAlgorithm.
1429 // The certificate is signed by parent. If parent is equal to template then the
1430 // certificate is self-signed. The parameter pub is the public key of the
1431 // signee and priv is the private key of the signer.
1433 // The returned slice is the certificate in DER encoding.
1435 // The only supported key types are RSA and ECDSA (*rsa.PublicKey or
1436 // *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PrivateKey for priv).
1437 func CreateCertificate(rand io
.Reader
, template
, parent
*Certificate
, pub
interface{}, priv
interface{}) (cert
[]byte, err error
) {
1438 hashFunc
, signatureAlgorithm
, err
:= signingParamsForPrivateKey(priv
, template
.SignatureAlgorithm
)
1443 publicKeyBytes
, publicKeyAlgorithm
, err
:= marshalPublicKey(pub
)
1452 if len(parent
.SubjectKeyId
) > 0 {
1453 template
.AuthorityKeyId
= parent
.SubjectKeyId
1456 extensions
, err
:= buildExtensions(template
)
1461 asn1Issuer
, err
:= subjectBytes(parent
)
1466 asn1Subject
, err
:= subjectBytes(template
)
1471 encodedPublicKey
:= asn1
.BitString
{BitLength
: len(publicKeyBytes
) * 8, Bytes
: publicKeyBytes
}
1472 c
:= tbsCertificate
{
1474 SerialNumber
: template
.SerialNumber
,
1475 SignatureAlgorithm
: signatureAlgorithm
,
1476 Issuer
: asn1
.RawValue
{FullBytes
: asn1Issuer
},
1477 Validity
: validity
{template
.NotBefore
.UTC(), template
.NotAfter
.UTC()},
1478 Subject
: asn1
.RawValue
{FullBytes
: asn1Subject
},
1479 PublicKey
: publicKeyInfo
{nil, publicKeyAlgorithm
, encodedPublicKey
},
1480 Extensions
: extensions
,
1483 tbsCertContents
, err
:= asn1
.Marshal(c
)
1488 c
.Raw
= tbsCertContents
1491 h
.Write(tbsCertContents
)
1492 digest
:= h
.Sum(nil)
1494 var signature
[]byte
1496 switch priv
:= priv
.(type) {
1497 case *rsa
.PrivateKey
:
1498 signature
, err
= rsa
.SignPKCS1v15(rand
, priv
, hashFunc
, digest
)
1499 case *ecdsa
.PrivateKey
:
1501 if r
, s
, err
= ecdsa
.Sign(rand
, priv
, digest
); err
== nil {
1502 signature
, err
= asn1
.Marshal(ecdsaSignature
{r
, s
})
1505 panic("internal error")
1512 cert
, err
= asn1
.Marshal(certificate
{
1516 asn1
.BitString
{Bytes
: signature
, BitLength
: len(signature
) * 8},
1521 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1523 var pemCRLPrefix
= []byte("-----BEGIN X509 CRL")
1525 // pemType is the type of a PEM encoded CRL.
1526 var pemType
= "X509 CRL"
1528 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1529 // encoded CRLs will appear where they should be DER encoded, so this function
1530 // will transparently handle PEM encoding as long as there isn't any leading
1532 func ParseCRL(crlBytes
[]byte) (certList
*pkix
.CertificateList
, err error
) {
1533 if bytes
.HasPrefix(crlBytes
, pemCRLPrefix
) {
1534 block
, _
:= pem
.Decode(crlBytes
)
1535 if block
!= nil && block
.Type
== pemType
{
1536 crlBytes
= block
.Bytes
1539 return ParseDERCRL(crlBytes
)
1542 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1543 func ParseDERCRL(derBytes
[]byte) (certList
*pkix
.CertificateList
, err error
) {
1544 certList
= new(pkix
.CertificateList
)
1545 _
, err
= asn1
.Unmarshal(derBytes
, certList
)
1552 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1553 // contains the given list of revoked certificates.
1555 // The only supported key type is RSA (*rsa.PrivateKey for priv).
1556 func (c
*Certificate
) CreateCRL(rand io
.Reader
, priv
interface{}, revokedCerts
[]pkix
.RevokedCertificate
, now
, expiry time
.Time
) (crlBytes
[]byte, err error
) {
1557 rsaPriv
, ok
:= priv
.(*rsa
.PrivateKey
)
1559 return nil, errors
.New("x509: non-RSA private keys not supported")
1561 tbsCertList
:= pkix
.TBSCertificateList
{
1563 Signature
: pkix
.AlgorithmIdentifier
{
1564 Algorithm
: oidSignatureSHA1WithRSA
,
1566 Issuer
: c
.Subject
.ToRDNSequence(),
1567 ThisUpdate
: now
.UTC(),
1568 NextUpdate
: expiry
.UTC(),
1569 RevokedCertificates
: revokedCerts
,
1572 tbsCertListContents
, err
:= asn1
.Marshal(tbsCertList
)
1578 h
.Write(tbsCertListContents
)
1579 digest
:= h
.Sum(nil)
1581 signature
, err
:= rsa
.SignPKCS1v15(rand
, rsaPriv
, crypto
.SHA1
, digest
)
1586 return asn1
.Marshal(pkix
.CertificateList
{
1587 TBSCertList
: tbsCertList
,
1588 SignatureAlgorithm
: pkix
.AlgorithmIdentifier
{
1589 Algorithm
: oidSignatureSHA1WithRSA
,
1591 SignatureValue
: asn1
.BitString
{Bytes
: signature
, BitLength
: len(signature
) * 8},
1595 // CertificateRequest represents a PKCS #10, certificate signature request.
1596 type CertificateRequest
struct {
1597 Raw
[]byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
1598 RawTBSCertificateRequest
[]byte // Certificate request info part of raw ASN.1 DER content.
1599 RawSubjectPublicKeyInfo
[]byte // DER encoded SubjectPublicKeyInfo.
1600 RawSubject
[]byte // DER encoded Subject.
1604 SignatureAlgorithm SignatureAlgorithm
1606 PublicKeyAlgorithm PublicKeyAlgorithm
1607 PublicKey
interface{}
1611 // Attributes is a collection of attributes providing
1612 // additional information about the subject of the certificate.
1613 // See RFC 2986 section 4.1.
1614 Attributes
[]pkix
.AttributeTypeAndValueSET
1616 // Extensions contains raw X.509 extensions. When parsing CSRs, this
1617 // can be used to extract extensions that are not parsed by this
1619 Extensions
[]pkix
.Extension
1621 // ExtraExtensions contains extensions to be copied, raw, into any
1622 // marshaled CSR. Values override any extensions that would otherwise
1623 // be produced based on the other fields but are overridden by any
1624 // extensions specified in Attributes.
1626 // The ExtraExtensions field is not populated when parsing CSRs, see
1628 ExtraExtensions
[]pkix
.Extension
1630 // Subject Alternate Name values.
1632 EmailAddresses
[]string
1633 IPAddresses
[]net
.IP
1636 // These structures reflect the ASN.1 structure of X.509 certificate
1637 // signature requests (see RFC 2986):
1639 type tbsCertificateRequest
struct {
1642 Subject asn1
.RawValue
1643 PublicKey publicKeyInfo
1644 Attributes
[]pkix
.AttributeTypeAndValueSET
`asn1:"tag:0"`
1647 type certificateRequest
struct {
1649 TBSCSR tbsCertificateRequest
1650 SignatureAlgorithm pkix
.AlgorithmIdentifier
1651 SignatureValue asn1
.BitString
1654 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
1655 // extensions in a CSR.
1656 var oidExtensionRequest
= asn1
.ObjectIdentifier
{1, 2, 840, 113549, 1, 9, 14}
1658 // CreateCertificateRequest creates a new certificate based on a template. The
1659 // following members of template are used: Subject, Attributes,
1660 // SignatureAlgorithm, Extension, DNSNames, EmailAddresses, and IPAddresses.
1661 // The private key is the private key of the signer.
1663 // The returned slice is the certificate request in DER encoding.
1665 // The only supported key types are RSA (*rsa.PrivateKey) and ECDSA
1666 // (*ecdsa.PrivateKey).
1667 func CreateCertificateRequest(rand io
.Reader
, template
*CertificateRequest
, priv
interface{}) (csr
[]byte, err error
) {
1668 hashFunc
, sigAlgo
, err
:= signingParamsForPrivateKey(priv
, template
.SignatureAlgorithm
)
1673 var publicKeyBytes
[]byte
1674 var publicKeyAlgorithm pkix
.AlgorithmIdentifier
1676 switch priv
:= priv
.(type) {
1677 case *rsa
.PrivateKey
:
1678 publicKeyBytes
, publicKeyAlgorithm
, err
= marshalPublicKey(&priv
.PublicKey
)
1679 case *ecdsa
.PrivateKey
:
1680 publicKeyBytes
, publicKeyAlgorithm
, err
= marshalPublicKey(&priv
.PublicKey
)
1682 panic("internal error")
1689 var extensions
[]pkix
.Extension
1691 if (len(template
.DNSNames
) > 0 ||
len(template
.EmailAddresses
) > 0 ||
len(template
.IPAddresses
) > 0) &&
1692 !oidInExtensions(oidExtensionSubjectAltName
, template
.ExtraExtensions
) {
1693 sanBytes
, err
:= marshalSANs(template
.DNSNames
, template
.EmailAddresses
, template
.IPAddresses
)
1698 extensions
= append(extensions
, pkix
.Extension
{
1699 Id
: oidExtensionSubjectAltName
,
1704 extensions
= append(extensions
, template
.ExtraExtensions
...)
1706 var attributes
[]pkix
.AttributeTypeAndValueSET
1707 attributes
= append(attributes
, template
.Attributes
...)
1709 if len(extensions
) > 0 {
1710 // specifiedExtensions contains all the extensions that we
1711 // found specified via template.Attributes.
1712 specifiedExtensions
:= make(map[string]bool)
1714 for _
, atvSet
:= range template
.Attributes
{
1715 if !atvSet
.Type
.Equal(oidExtensionRequest
) {
1719 for _
, atvs
:= range atvSet
.Value
{
1720 for _
, atv
:= range atvs
{
1721 specifiedExtensions
[atv
.Type
.String()] = true
1726 atvs
:= make([]pkix
.AttributeTypeAndValue
, 0, len(extensions
))
1727 for _
, e
:= range extensions
{
1728 if specifiedExtensions
[e
.Id
.String()] {
1729 // Attributes already contained a value for
1730 // this extension and it takes priority.
1734 atvs
= append(atvs
, pkix
.AttributeTypeAndValue
{
1735 // There is no place for the critical flag in a CSR.
1741 // Append the extensions to an existing attribute if possible.
1743 for _
, atvSet
:= range attributes
{
1744 if !atvSet
.Type
.Equal(oidExtensionRequest
) ||
len(atvSet
.Value
) == 0 {
1748 atvSet
.Value
[0] = append(atvSet
.Value
[0], atvs
...)
1753 // Otherwise, add a new attribute for the extensions.
1755 attributes
= append(attributes
, pkix
.AttributeTypeAndValueSET
{
1756 Type
: oidExtensionRequest
,
1757 Value
: [][]pkix
.AttributeTypeAndValue
{
1764 asn1Subject
:= template
.RawSubject
1765 if len(asn1Subject
) == 0 {
1766 asn1Subject
, err
= asn1
.Marshal(template
.Subject
.ToRDNSequence())
1772 tbsCSR
:= tbsCertificateRequest
{
1773 Version
: 0, // PKCS #10, RFC 2986
1774 Subject
: asn1
.RawValue
{FullBytes
: asn1Subject
},
1775 PublicKey
: publicKeyInfo
{
1776 Algorithm
: publicKeyAlgorithm
,
1777 PublicKey
: asn1
.BitString
{
1778 Bytes
: publicKeyBytes
,
1779 BitLength
: len(publicKeyBytes
) * 8,
1782 Attributes
: attributes
,
1785 tbsCSRContents
, err
:= asn1
.Marshal(tbsCSR
)
1789 tbsCSR
.Raw
= tbsCSRContents
1792 h
.Write(tbsCSRContents
)
1793 digest
:= h
.Sum(nil)
1795 var signature
[]byte
1796 switch priv
:= priv
.(type) {
1797 case *rsa
.PrivateKey
:
1798 signature
, err
= rsa
.SignPKCS1v15(rand
, priv
, hashFunc
, digest
)
1799 case *ecdsa
.PrivateKey
:
1801 if r
, s
, err
= ecdsa
.Sign(rand
, priv
, digest
); err
== nil {
1802 signature
, err
= asn1
.Marshal(ecdsaSignature
{r
, s
})
1805 panic("internal error")
1812 return asn1
.Marshal(certificateRequest
{
1814 SignatureAlgorithm
: sigAlgo
,
1815 SignatureValue
: asn1
.BitString
{
1817 BitLength
: len(signature
) * 8,
1822 // ParseCertificateRequest parses a single certificate request from the
1823 // given ASN.1 DER data.
1824 func ParseCertificateRequest(asn1Data
[]byte) (*CertificateRequest
, error
) {
1825 var csr certificateRequest
1827 rest
, err
:= asn1
.Unmarshal(asn1Data
, &csr
)
1830 } else if len(rest
) != 0 {
1831 return nil, asn1
.SyntaxError
{Msg
: "trailing data"}
1834 return parseCertificateRequest(&csr
)
1837 func parseCertificateRequest(in
*certificateRequest
) (*CertificateRequest
, error
) {
1838 out
:= &CertificateRequest
{
1840 RawTBSCertificateRequest
: in
.TBSCSR
.Raw
,
1841 RawSubjectPublicKeyInfo
: in
.TBSCSR
.PublicKey
.Raw
,
1842 RawSubject
: in
.TBSCSR
.Subject
.FullBytes
,
1844 Signature
: in
.SignatureValue
.RightAlign(),
1845 SignatureAlgorithm
: getSignatureAlgorithmFromOID(in
.SignatureAlgorithm
.Algorithm
),
1847 PublicKeyAlgorithm
: getPublicKeyAlgorithmFromOID(in
.TBSCSR
.PublicKey
.Algorithm
.Algorithm
),
1849 Version
: in
.TBSCSR
.Version
,
1850 Attributes
: in
.TBSCSR
.Attributes
,
1854 out
.PublicKey
, err
= parsePublicKey(out
.PublicKeyAlgorithm
, &in
.TBSCSR
.PublicKey
)
1859 var subject pkix
.RDNSequence
1860 if _
, err
:= asn1
.Unmarshal(in
.TBSCSR
.Subject
.FullBytes
, &subject
); err
!= nil {
1864 out
.Subject
.FillFromRDNSequence(&subject
)
1866 var extensions
[]pkix
.AttributeTypeAndValue
1868 for _
, atvSet
:= range in
.TBSCSR
.Attributes
{
1869 if !atvSet
.Type
.Equal(oidExtensionRequest
) {
1873 for _
, atvs
:= range atvSet
.Value
{
1874 extensions
= append(extensions
, atvs
...)
1878 out
.Extensions
= make([]pkix
.Extension
, 0, len(extensions
))
1880 for _
, e
:= range extensions
{
1881 value
, ok
:= e
.Value
.([]byte)
1883 return nil, errors
.New("x509: extension attribute contained non-OCTET STRING data")
1886 out
.Extensions
= append(out
.Extensions
, pkix
.Extension
{
1891 if len(e
.Type
) == 4 && e
.Type
[0] == 2 && e
.Type
[1] == 5 && e
.Type
[2] == 29 {
1894 out
.DNSNames
, out
.EmailAddresses
, out
.IPAddresses
, err
= parseSANExtension(value
)