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.
27 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
29 type pkixPublicKey struct {
30 Algo pkix.AlgorithmIdentifier
31 BitString asn1.BitString
34 // ParsePKIXPublicKey parses a DER encoded public key. These values are
35 // typically found in PEM blocks with "BEGIN PUBLIC KEY".
36 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
38 if _, err = asn1.Unmarshal(derBytes, &pki); err != nil {
41 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
42 if algo == UnknownPublicKeyAlgorithm {
43 return nil, errors.New("ParsePKIXPublicKey: unknown public key algorithm")
45 return parsePublicKey(algo, &pki)
48 // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
49 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
52 switch pub := pub.(type) {
54 pubBytes, _ = asn1.Marshal(rsaPublicKey{
59 return nil, errors.New("MarshalPKIXPublicKey: unknown public key type")
62 pkix := pkixPublicKey{
63 Algo: pkix.AlgorithmIdentifier{
64 Algorithm: []int{1, 2, 840, 113549, 1, 1, 1},
65 // This is a NULL parameters value which is technically
66 // superfluous, but most other code includes it and, by
67 // doing this, we match their public key hashes.
68 Parameters: asn1.RawValue{
72 BitString: asn1.BitString{
74 BitLength: 8 * len(pubBytes),
78 ret, _ := asn1.Marshal(pkix)
82 // These structures reflect the ASN.1 structure of X.509 certificates.:
84 type certificate struct {
86 TBSCertificate tbsCertificate
87 SignatureAlgorithm pkix.AlgorithmIdentifier
88 SignatureValue asn1.BitString
91 type tbsCertificate struct {
93 Version int `asn1:"optional,explicit,default:1,tag:0"`
95 SignatureAlgorithm pkix.AlgorithmIdentifier
99 PublicKey publicKeyInfo
100 UniqueId asn1.BitString `asn1:"optional,tag:1"`
101 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
102 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
105 type dsaAlgorithmParameters struct {
109 type dsaSignature struct {
113 type ecdsaSignature dsaSignature
115 type validity struct {
116 NotBefore, NotAfter time.Time
119 type publicKeyInfo struct {
121 Algorithm pkix.AlgorithmIdentifier
122 PublicKey asn1.BitString
126 type authKeyId struct {
127 Id []byte `asn1:"optional,tag:0"`
130 type SignatureAlgorithm int
133 UnknownSignatureAlgorithm SignatureAlgorithm = iota
148 type PublicKeyAlgorithm int
151 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
157 // OIDs for signature algorithms
159 // pkcs-1 OBJECT IDENTIFIER ::= {
160 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
163 // RFC 3279 2.2.1 RSA Signature Algorithms
165 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
167 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
169 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
171 // dsaWithSha1 OBJECT IDENTIFIER ::= {
172 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
174 // RFC 3279 2.2.3 ECDSA Signature Algorithm
176 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
177 // iso(1) member-body(2) us(840) ansi-x962(10045)
178 // signatures(4) ecdsa-with-SHA1(1)}
181 // RFC 4055 5 PKCS #1 Version 1.5
183 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
185 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
187 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
190 // RFC 5758 3.1 DSA Signature Algorithms
192 // dsaWithSha256 OBJECT IDENTIFIER ::= {
193 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
194 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
196 // RFC 5758 3.2 ECDSA Signature Algorithm
198 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
199 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
201 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
202 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
204 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
205 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
208 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
209 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
210 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
211 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
212 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
213 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
214 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
215 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2}
216 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
217 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
218 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
219 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
222 func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm {
224 case oid.Equal(oidSignatureMD2WithRSA):
226 case oid.Equal(oidSignatureMD5WithRSA):
228 case oid.Equal(oidSignatureSHA1WithRSA):
230 case oid.Equal(oidSignatureSHA256WithRSA):
232 case oid.Equal(oidSignatureSHA384WithRSA):
234 case oid.Equal(oidSignatureSHA512WithRSA):
236 case oid.Equal(oidSignatureDSAWithSHA1):
238 case oid.Equal(oidSignatureDSAWithSHA256):
240 case oid.Equal(oidSignatureECDSAWithSHA1):
242 case oid.Equal(oidSignatureECDSAWithSHA256):
243 return ECDSAWithSHA256
244 case oid.Equal(oidSignatureECDSAWithSHA384):
245 return ECDSAWithSHA384
246 case oid.Equal(oidSignatureECDSAWithSHA512):
247 return ECDSAWithSHA512
249 return UnknownSignatureAlgorithm
252 // RFC 3279, 2.3 Public Key Algorithms
254 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
255 // rsadsi(113549) pkcs(1) 1 }
257 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
259 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
260 // x9-57(10040) x9cm(4) 1 }
262 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
264 // id-ecPublicKey OBJECT IDENTIFIER ::= {
265 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
267 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
268 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
269 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
272 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
274 case oid.Equal(oidPublicKeyRSA):
276 case oid.Equal(oidPublicKeyDSA):
278 case oid.Equal(oidPublicKeyECDSA):
281 return UnknownPublicKeyAlgorithm
284 // RFC 5480, 2.1.1.1. Named Curve
286 // secp224r1 OBJECT IDENTIFIER ::= {
287 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
289 // secp256r1 OBJECT IDENTIFIER ::= {
290 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
293 // secp384r1 OBJECT IDENTIFIER ::= {
294 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
296 // secp521r1 OBJECT IDENTIFIER ::= {
297 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
299 // NB: secp256r1 is equivalent to prime256v1
301 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
302 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
303 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
304 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
307 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
309 case oid.Equal(oidNamedCurveP224):
310 return elliptic.P224()
311 case oid.Equal(oidNamedCurveP256):
312 return elliptic.P256()
313 case oid.Equal(oidNamedCurveP384):
314 return elliptic.P384()
315 case oid.Equal(oidNamedCurveP521):
316 return elliptic.P521()
321 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
323 case elliptic.P224():
324 return oidNamedCurveP224, true
325 case elliptic.P256():
326 return oidNamedCurveP256, true
327 case elliptic.P384():
328 return oidNamedCurveP384, true
329 case elliptic.P521():
330 return oidNamedCurveP521, true
336 // KeyUsage represents the set of actions that are valid for a given key. It's
337 // a bitmap of the KeyUsage* constants.
341 KeyUsageDigitalSignature KeyUsage = 1 << iota
342 KeyUsageContentCommitment
343 KeyUsageKeyEncipherment
344 KeyUsageDataEncipherment
352 // RFC 5280, 4.2.1.12 Extended Key Usage
354 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
356 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
358 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
359 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
360 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
361 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
362 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
363 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
365 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
366 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
367 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
368 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
369 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
370 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
371 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
372 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
373 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
374 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
375 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
376 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
379 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
380 // Each of the ExtKeyUsage* constants define a unique action.
384 ExtKeyUsageAny ExtKeyUsage = iota
385 ExtKeyUsageServerAuth
386 ExtKeyUsageClientAuth
387 ExtKeyUsageCodeSigning
388 ExtKeyUsageEmailProtection
389 ExtKeyUsageIPSECEndSystem
390 ExtKeyUsageIPSECTunnel
392 ExtKeyUsageTimeStamping
393 ExtKeyUsageOCSPSigning
394 ExtKeyUsageMicrosoftServerGatedCrypto
395 ExtKeyUsageNetscapeServerGatedCrypto
398 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
399 var extKeyUsageOIDs = []struct {
400 extKeyUsage ExtKeyUsage
401 oid asn1.ObjectIdentifier
403 {ExtKeyUsageAny, oidExtKeyUsageAny},
404 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
405 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
406 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
407 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
408 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
409 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
410 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
411 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
412 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
413 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
414 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
417 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
418 for _, pair := range extKeyUsageOIDs {
419 if oid.Equal(pair.oid) {
420 return pair.extKeyUsage, true
426 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
427 for _, pair := range extKeyUsageOIDs {
428 if eku == pair.extKeyUsage {
429 return pair.oid, true
435 // A Certificate represents an X.509 certificate.
436 type Certificate struct {
437 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
438 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
439 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
440 RawSubject []byte // DER encoded Subject
441 RawIssuer []byte // DER encoded Issuer
444 SignatureAlgorithm SignatureAlgorithm
446 PublicKeyAlgorithm PublicKeyAlgorithm
447 PublicKey interface{}
450 SerialNumber *big.Int
453 NotBefore, NotAfter time.Time // Validity bounds.
456 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
457 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
459 BasicConstraintsValid bool // if true then the next two fields are valid.
464 AuthorityKeyId []byte
466 // Subject Alternate Name values
468 EmailAddresses []string
472 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
473 PermittedDNSDomains []string
475 PolicyIdentifiers []asn1.ObjectIdentifier
478 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
479 // involves algorithms that are not currently implemented.
480 var ErrUnsupportedAlgorithm = errors.New("crypto/x509: cannot verify signature: algorithm unimplemented")
482 // ConstraintViolationError results when a requested usage is not permitted by
483 // a certificate. For example: checking a signature when the public key isn't a
484 // certificate signing key.
485 type ConstraintViolationError struct{}
487 func (ConstraintViolationError) Error() string {
488 return "crypto/x509: invalid signature: parent certificate cannot sign this kind of certificate"
491 func (c *Certificate) Equal(other *Certificate) bool {
492 return bytes.Equal(c.Raw, other.Raw)
495 // Entrust have a broken root certificate (CN=Entrust.net Certification
496 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
497 // according to PKIX.
498 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
499 // from the Basic Constraints requirement.
500 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
502 // TODO(agl): remove this hack once their reissued root is sufficiently
504 var entrustBrokenSPKI = []byte{
505 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
506 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
507 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
508 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
509 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
510 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
511 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
512 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
513 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
514 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
515 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
516 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
517 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
518 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
519 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
520 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
521 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
522 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
523 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
524 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
525 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
526 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
527 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
528 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
529 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
530 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
531 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
532 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
533 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
534 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
535 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
536 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
537 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
538 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
539 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
540 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
541 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
544 // CheckSignatureFrom verifies that the signature on c is a valid signature
546 func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) {
547 // RFC 5280, 4.2.1.9:
548 // "If the basic constraints extension is not present in a version 3
549 // certificate, or the extension is present but the cA boolean is not
550 // asserted, then the certified public key MUST NOT be used to verify
551 // certificate signatures."
552 // (except for Entrust, see comment above entrustBrokenSPKI)
553 if (parent.Version == 3 && !parent.BasicConstraintsValid ||
554 parent.BasicConstraintsValid && !parent.IsCA) &&
555 !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
556 return ConstraintViolationError{}
559 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
560 return ConstraintViolationError{}
563 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
564 return ErrUnsupportedAlgorithm
567 // TODO(agl): don't ignore the path length constraint.
569 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
572 // CheckSignature verifies that signature is a valid signature over signed from
574 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) {
575 var hashType crypto.Hash
578 case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1:
579 hashType = crypto.SHA1
580 case SHA256WithRSA, DSAWithSHA256, ECDSAWithSHA256:
581 hashType = crypto.SHA256
582 case SHA384WithRSA, ECDSAWithSHA384:
583 hashType = crypto.SHA384
584 case SHA512WithRSA, ECDSAWithSHA512:
585 hashType = crypto.SHA512
587 return ErrUnsupportedAlgorithm
590 if !hashType.Available() {
591 return ErrUnsupportedAlgorithm
598 switch pub := c.PublicKey.(type) {
600 return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
602 dsaSig := new(dsaSignature)
603 if _, err := asn1.Unmarshal(signature, dsaSig); err != nil {
606 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
607 return errors.New("DSA signature contained zero or negative values")
609 if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
610 return errors.New("DSA verification failure")
613 case *ecdsa.PublicKey:
614 ecdsaSig := new(ecdsaSignature)
615 if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
618 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
619 return errors.New("crypto/x509: ECDSA signature contained zero or negative values")
621 if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
622 return errors.New("crypto/x509: ECDSA verification failure")
626 return ErrUnsupportedAlgorithm
629 // CheckCRLSignature checks that the signature in crl is from c.
630 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) {
631 algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm)
632 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
635 type UnhandledCriticalExtension struct{}
637 func (h UnhandledCriticalExtension) Error() string {
638 return "unhandled critical extension"
641 type basicConstraints struct {
642 IsCA bool `asn1:"optional"`
643 MaxPathLen int `asn1:"optional,default:-1"`
647 type policyInformation struct {
648 Policy asn1.ObjectIdentifier
649 // policyQualifiers omitted
652 // RFC 5280, 4.2.1.10
653 type nameConstraints struct {
654 Permitted []generalSubtree `asn1:"optional,tag:0"`
655 Excluded []generalSubtree `asn1:"optional,tag:1"`
658 type generalSubtree struct {
659 Name string `asn1:"tag:2,optional,ia5"`
662 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
663 asn1Data := keyData.PublicKey.RightAlign()
666 p := new(rsaPublicKey)
667 _, err := asn1.Unmarshal(asn1Data, p)
673 return nil, errors.New("x509: RSA modulus is not a positive number")
676 return nil, errors.New("x509: RSA public exponent is not a positive number")
679 pub := &rsa.PublicKey{
686 _, err := asn1.Unmarshal(asn1Data, &p)
690 paramsData := keyData.Algorithm.Parameters.FullBytes
691 params := new(dsaAlgorithmParameters)
692 _, err = asn1.Unmarshal(paramsData, params)
696 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
697 return nil, errors.New("zero or negative DSA parameter")
699 pub := &dsa.PublicKey{
700 Parameters: dsa.Parameters{
709 paramsData := keyData.Algorithm.Parameters.FullBytes
710 namedCurveOID := new(asn1.ObjectIdentifier)
711 _, err := asn1.Unmarshal(paramsData, namedCurveOID)
715 namedCurve := namedCurveFromOID(*namedCurveOID)
716 if namedCurve == nil {
717 return nil, errors.New("crypto/x509: unsupported elliptic curve")
719 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
721 return nil, errors.New("crypto/x509: failed to unmarshal elliptic curve point")
723 pub := &ecdsa.PublicKey{
734 func parseCertificate(in *certificate) (*Certificate, error) {
735 out := new(Certificate)
737 out.RawTBSCertificate = in.TBSCertificate.Raw
738 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
739 out.RawSubject = in.TBSCertificate.Subject.FullBytes
740 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
742 out.Signature = in.SignatureValue.RightAlign()
743 out.SignatureAlgorithm =
744 getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
746 out.PublicKeyAlgorithm =
747 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
749 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
754 if in.TBSCertificate.SerialNumber.Sign() < 0 {
755 return nil, errors.New("negative serial number")
758 out.Version = in.TBSCertificate.Version + 1
759 out.SerialNumber = in.TBSCertificate.SerialNumber
761 var issuer, subject pkix.RDNSequence
762 if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
765 if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
769 out.Issuer.FillFromRDNSequence(&issuer)
770 out.Subject.FillFromRDNSequence(&subject)
772 out.NotBefore = in.TBSCertificate.Validity.NotBefore
773 out.NotAfter = in.TBSCertificate.Validity.NotAfter
775 for _, e := range in.TBSCertificate.Extensions {
776 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
780 var usageBits asn1.BitString
781 _, err := asn1.Unmarshal(e.Value, &usageBits)
785 for i := 0; i < 9; i++ {
786 if usageBits.At(i) != 0 {
787 usage |= 1 << uint(i)
790 out.KeyUsage = KeyUsage(usage)
795 var constraints basicConstraints
796 _, err := asn1.Unmarshal(e.Value, &constraints)
799 out.BasicConstraintsValid = true
800 out.IsCA = constraints.IsCA
801 out.MaxPathLen = constraints.MaxPathLen
807 // SubjectAltName ::= GeneralNames
809 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
811 // GeneralName ::= CHOICE {
812 // otherName [0] OtherName,
813 // rfc822Name [1] IA5String,
814 // dNSName [2] IA5String,
815 // x400Address [3] ORAddress,
816 // directoryName [4] Name,
817 // ediPartyName [5] EDIPartyName,
818 // uniformResourceIdentifier [6] IA5String,
819 // iPAddress [7] OCTET STRING,
820 // registeredID [8] OBJECT IDENTIFIER }
821 var seq asn1.RawValue
822 _, err := asn1.Unmarshal(e.Value, &seq)
826 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
827 return nil, asn1.StructuralError{Msg: "bad SAN sequence"}
835 rest, err = asn1.Unmarshal(rest, &v)
841 out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes))
844 out.DNSNames = append(out.DNSNames, string(v.Bytes))
847 switch len(v.Bytes) {
848 case net.IPv4len, net.IPv6len:
849 out.IPAddresses = append(out.IPAddresses, v.Bytes)
851 return nil, errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes)))
859 // If we didn't parse any of the names then we
860 // fall through to the critical check below.
863 // RFC 5280, 4.2.1.10
865 // NameConstraints ::= SEQUENCE {
866 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
867 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
869 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
871 // GeneralSubtree ::= SEQUENCE {
873 // minimum [0] BaseDistance DEFAULT 0,
874 // maximum [1] BaseDistance OPTIONAL }
876 // BaseDistance ::= INTEGER (0..MAX)
878 var constraints nameConstraints
879 _, err := asn1.Unmarshal(e.Value, &constraints)
884 if len(constraints.Excluded) > 0 && e.Critical {
885 return out, UnhandledCriticalExtension{}
888 for _, subtree := range constraints.Permitted {
889 if len(subtree.Name) == 0 {
891 return out, UnhandledCriticalExtension{}
895 out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
902 _, err = asn1.Unmarshal(e.Value, &a)
906 out.AuthorityKeyId = a.Id
910 // RFC 5280, 4.2.1.12. Extended Key Usage
912 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
914 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
916 // KeyPurposeId ::= OBJECT IDENTIFIER
918 var keyUsage []asn1.ObjectIdentifier
919 _, err = asn1.Unmarshal(e.Value, &keyUsage)
924 for _, u := range keyUsage {
925 if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
926 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
928 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
937 _, err = asn1.Unmarshal(e.Value, &keyid)
941 out.SubjectKeyId = keyid
945 // RFC 5280 4.2.1.4: Certificate Policies
946 var policies []policyInformation
947 if _, err = asn1.Unmarshal(e.Value, &policies); err != nil {
950 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
951 for i, policy := range policies {
952 out.PolicyIdentifiers[i] = policy.Policy
958 return out, UnhandledCriticalExtension{}
965 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
966 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
968 rest, err := asn1.Unmarshal(asn1Data, &cert)
973 return nil, asn1.SyntaxError{Msg: "trailing data"}
976 return parseCertificate(&cert)
979 // ParseCertificates parses one or more certificates from the given ASN.1 DER
980 // data. The certificates must be concatenated with no intermediate padding.
981 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
984 for len(asn1Data) > 0 {
985 cert := new(certificate)
987 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
994 ret := make([]*Certificate, len(v))
995 for i, ci := range v {
996 cert, err := parseCertificate(ci)
1006 func reverseBitsInAByte(in byte) byte {
1008 b2 := b1>>2&0x33 | b1<<2&0xcc
1009 b3 := b2>>1&0x55 | b2<<1&0xaa
1014 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1015 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1016 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1017 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1018 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1019 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1020 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1021 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1024 func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
1025 ret = make([]pkix.Extension, 8 /* maximum number of elements. */)
1028 if template.KeyUsage != 0 {
1029 ret[n].Id = oidExtensionKeyUsage
1030 ret[n].Critical = true
1033 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1034 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1041 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
1048 if len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0 {
1049 ret[n].Id = oidExtensionExtendedKeyUsage
1051 var oids []asn1.ObjectIdentifier
1052 for _, u := range template.ExtKeyUsage {
1053 if oid, ok := oidFromExtKeyUsage(u); ok {
1054 oids = append(oids, oid)
1056 panic("internal error")
1060 oids = append(oids, template.UnknownExtKeyUsage...)
1062 ret[n].Value, err = asn1.Marshal(oids)
1069 if template.BasicConstraintsValid {
1070 ret[n].Id = oidExtensionBasicConstraints
1071 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
1072 ret[n].Critical = true
1079 if len(template.SubjectKeyId) > 0 {
1080 ret[n].Id = oidExtensionSubjectKeyId
1081 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
1088 if len(template.AuthorityKeyId) > 0 {
1089 ret[n].Id = oidExtensionAuthorityKeyId
1090 ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
1097 if len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 {
1098 ret[n].Id = oidExtensionSubjectAltName
1099 var rawValues []asn1.RawValue
1100 for _, name := range template.DNSNames {
1101 rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
1103 for _, email := range template.EmailAddresses {
1104 rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
1106 for _, rawIP := range template.IPAddresses {
1107 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1112 rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
1114 ret[n].Value, err = asn1.Marshal(rawValues)
1121 if len(template.PolicyIdentifiers) > 0 {
1122 ret[n].Id = oidExtensionCertificatePolicies
1123 policies := make([]policyInformation, len(template.PolicyIdentifiers))
1124 for i, policy := range template.PolicyIdentifiers {
1125 policies[i].Policy = policy
1127 ret[n].Value, err = asn1.Marshal(policies)
1134 if len(template.PermittedDNSDomains) > 0 {
1135 ret[n].Id = oidExtensionNameConstraints
1136 ret[n].Critical = template.PermittedDNSDomainsCritical
1138 var out nameConstraints
1139 out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
1140 for i, permitted := range template.PermittedDNSDomains {
1141 out.Permitted[i] = generalSubtree{Name: permitted}
1143 ret[n].Value, err = asn1.Marshal(out)
1150 // Adding another extension here? Remember to update the maximum number
1151 // of elements in the make() at the top of the function.
1153 return ret[0:n], nil
1156 func subjectBytes(cert *Certificate) ([]byte, error) {
1157 if len(cert.RawSubject) > 0 {
1158 return cert.RawSubject, nil
1161 return asn1.Marshal(cert.Subject.ToRDNSequence())
1164 // CreateCertificate creates a new certificate based on a template. The
1165 // following members of template are used: SerialNumber, Subject, NotBefore,
1166 // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
1167 // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
1168 // PermittedDNSDomains.
1170 // The certificate is signed by parent. If parent is equal to template then the
1171 // certificate is self-signed. The parameter pub is the public key of the
1172 // signee and priv is the private key of the signer.
1174 // The returned slice is the certificate in DER encoding.
1176 // The only supported key types are RSA and ECDSA (*rsa.PublicKey or
1177 // *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PublicKey for priv).
1178 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) {
1179 var publicKeyBytes []byte
1180 var publicKeyAlgorithm pkix.AlgorithmIdentifier
1182 switch pub := pub.(type) {
1183 case *rsa.PublicKey:
1184 publicKeyBytes, err = asn1.Marshal(rsaPublicKey{
1188 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
1189 case *ecdsa.PublicKey:
1190 oid, ok := oidFromNamedCurve(pub.Curve)
1192 return nil, errors.New("x509: unknown elliptic curve")
1194 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
1195 var paramBytes []byte
1196 paramBytes, err = asn1.Marshal(oid)
1200 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
1201 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
1203 return nil, errors.New("x509: only RSA and ECDSA public keys supported")
1206 var signatureAlgorithm pkix.AlgorithmIdentifier
1207 var hashFunc crypto.Hash
1209 switch priv := priv.(type) {
1210 case *rsa.PrivateKey:
1211 signatureAlgorithm.Algorithm = oidSignatureSHA1WithRSA
1212 hashFunc = crypto.SHA1
1213 case *ecdsa.PrivateKey:
1215 case elliptic.P224(), elliptic.P256():
1216 hashFunc = crypto.SHA256
1217 signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA256
1218 case elliptic.P384():
1219 hashFunc = crypto.SHA384
1220 signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA384
1221 case elliptic.P521():
1222 hashFunc = crypto.SHA512
1223 signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA512
1225 return nil, errors.New("x509: unknown elliptic curve")
1228 return nil, errors.New("x509: only RSA and ECDSA private keys supported")
1235 if len(parent.SubjectKeyId) > 0 {
1236 template.AuthorityKeyId = parent.SubjectKeyId
1239 extensions, err := buildExtensions(template)
1244 asn1Issuer, err := subjectBytes(parent)
1249 asn1Subject, err := subjectBytes(template)
1254 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1255 c := tbsCertificate{
1257 SerialNumber: template.SerialNumber,
1258 SignatureAlgorithm: signatureAlgorithm,
1259 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1260 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1261 Subject: asn1.RawValue{FullBytes: asn1Subject},
1262 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1263 Extensions: extensions,
1266 tbsCertContents, err := asn1.Marshal(c)
1271 c.Raw = tbsCertContents
1274 h.Write(tbsCertContents)
1275 digest := h.Sum(nil)
1277 var signature []byte
1279 switch priv := priv.(type) {
1280 case *rsa.PrivateKey:
1281 signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest)
1282 case *ecdsa.PrivateKey:
1284 if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil {
1285 signature, err = asn1.Marshal(ecdsaSignature{r, s})
1288 panic("internal error")
1295 cert, err = asn1.Marshal(certificate{
1299 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1304 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1306 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1308 // pemType is the type of a PEM encoded CRL.
1309 var pemType = "X509 CRL"
1311 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1312 // encoded CRLs will appear where they should be DER encoded, so this function
1313 // will transparently handle PEM encoding as long as there isn't any leading
1315 func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) {
1316 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1317 block, _ := pem.Decode(crlBytes)
1318 if block != nil && block.Type == pemType {
1319 crlBytes = block.Bytes
1322 return ParseDERCRL(crlBytes)
1325 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1326 func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) {
1327 certList = new(pkix.CertificateList)
1328 _, err = asn1.Unmarshal(derBytes, certList)
1335 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1336 // contains the given list of revoked certificates.
1338 // The only supported key type is RSA (*rsa.PrivateKey for priv).
1339 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1340 rsaPriv, ok := priv.(*rsa.PrivateKey)
1342 return nil, errors.New("x509: non-RSA private keys not supported")
1344 tbsCertList := pkix.TBSCertificateList{
1346 Signature: pkix.AlgorithmIdentifier{
1347 Algorithm: oidSignatureSHA1WithRSA,
1349 Issuer: c.Subject.ToRDNSequence(),
1350 ThisUpdate: now.UTC(),
1351 NextUpdate: expiry.UTC(),
1352 RevokedCertificates: revokedCerts,
1355 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1361 h.Write(tbsCertListContents)
1362 digest := h.Sum(nil)
1364 signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
1369 return asn1.Marshal(pkix.CertificateList{
1370 TBSCertList: tbsCertList,
1371 SignatureAlgorithm: pkix.AlgorithmIdentifier{
1372 Algorithm: oidSignatureSHA1WithRSA,
1374 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},