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.
23 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
25 type pkixPublicKey struct {
26 Algo pkix.AlgorithmIdentifier
27 BitString asn1.BitString
30 // ParsePKIXPublicKey parses a DER encoded public key. These values are
31 // typically found in PEM blocks with "BEGIN PUBLIC KEY".
32 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
34 if _, err = asn1.Unmarshal(derBytes, &pki); err != nil {
37 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
38 if algo == UnknownPublicKeyAlgorithm {
39 return nil, errors.New("ParsePKIXPublicKey: unknown public key algorithm")
41 return parsePublicKey(algo, &pki)
44 // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
45 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
48 switch pub := pub.(type) {
50 pubBytes, _ = asn1.Marshal(rsaPublicKey{
55 return nil, errors.New("MarshalPKIXPublicKey: unknown public key type")
58 pkix := pkixPublicKey{
59 Algo: pkix.AlgorithmIdentifier{
60 Algorithm: []int{1, 2, 840, 113549, 1, 1, 1},
61 // This is a NULL parameters value which is technically
62 // superfluous, but most other code includes it and, by
63 // doing this, we match their public key hashes.
64 Parameters: asn1.RawValue{
68 BitString: asn1.BitString{
70 BitLength: 8 * len(pubBytes),
74 ret, _ := asn1.Marshal(pkix)
78 // These structures reflect the ASN.1 structure of X.509 certificates.:
80 type certificate struct {
82 TBSCertificate tbsCertificate
83 SignatureAlgorithm pkix.AlgorithmIdentifier
84 SignatureValue asn1.BitString
87 type tbsCertificate struct {
89 Version int `asn1:"optional,explicit,default:1,tag:0"`
91 SignatureAlgorithm pkix.AlgorithmIdentifier
95 PublicKey publicKeyInfo
96 UniqueId asn1.BitString `asn1:"optional,tag:1"`
97 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
98 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
101 type dsaAlgorithmParameters struct {
105 type dsaSignature struct {
109 type validity struct {
110 NotBefore, NotAfter time.Time
113 type publicKeyInfo struct {
115 Algorithm pkix.AlgorithmIdentifier
116 PublicKey asn1.BitString
120 type authKeyId struct {
121 Id []byte `asn1:"optional,tag:0"`
124 type SignatureAlgorithm int
127 UnknownSignatureAlgorithm SignatureAlgorithm = iota
138 type PublicKeyAlgorithm int
141 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
146 // OIDs for signature algorithms
148 // pkcs-1 OBJECT IDENTIFIER ::= {
149 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
152 // RFC 3279 2.2.1 RSA Signature Algorithms
154 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
156 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
158 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
160 // dsaWithSha1 OBJECT IDENTIFIER ::= {
161 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
164 // RFC 4055 5 PKCS #1 Version 1.5
166 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
168 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
170 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
173 // RFC 5758 3.1 DSA Signature Algorithms
175 // dsaWithSha256 OBJECT IDENTIFIER ::= {
176 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
177 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
180 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
181 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
182 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
183 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
184 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
185 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
186 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
187 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2}
190 func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm {
192 case oid.Equal(oidSignatureMD2WithRSA):
194 case oid.Equal(oidSignatureMD5WithRSA):
196 case oid.Equal(oidSignatureSHA1WithRSA):
198 case oid.Equal(oidSignatureSHA256WithRSA):
200 case oid.Equal(oidSignatureSHA384WithRSA):
202 case oid.Equal(oidSignatureSHA512WithRSA):
204 case oid.Equal(oidSignatureDSAWithSHA1):
206 case oid.Equal(oidSignatureDSAWithSHA256):
209 return UnknownSignatureAlgorithm
212 // RFC 3279, 2.3 Public Key Algorithms
214 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
215 // rsadsi(113549) pkcs(1) 1 }
217 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
219 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
220 // x9-57(10040) x9cm(4) 1 }
222 oidPublicKeyRsa = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
223 oidPublicKeyDsa = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
226 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
228 case oid.Equal(oidPublicKeyRsa):
230 case oid.Equal(oidPublicKeyDsa):
233 return UnknownPublicKeyAlgorithm
236 // KeyUsage represents the set of actions that are valid for a given key. It's
237 // a bitmap of the KeyUsage* constants.
241 KeyUsageDigitalSignature KeyUsage = 1 << iota
242 KeyUsageContentCommitment
243 KeyUsageKeyEncipherment
244 KeyUsageDataEncipherment
252 // RFC 5280, 4.2.1.12 Extended Key Usage
254 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
256 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
258 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
259 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
260 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
261 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
262 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
263 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
265 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
266 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
267 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
268 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
269 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
270 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
271 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
274 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
275 // Each of the ExtKeyUsage* constants define a unique action.
279 ExtKeyUsageAny ExtKeyUsage = iota
280 ExtKeyUsageServerAuth
281 ExtKeyUsageClientAuth
282 ExtKeyUsageCodeSigning
283 ExtKeyUsageEmailProtection
284 ExtKeyUsageTimeStamping
285 ExtKeyUsageOCSPSigning
288 // A Certificate represents an X.509 certificate.
289 type Certificate struct {
290 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
291 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
292 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
293 RawSubject []byte // DER encoded Subject
294 RawIssuer []byte // DER encoded Issuer
297 SignatureAlgorithm SignatureAlgorithm
299 PublicKeyAlgorithm PublicKeyAlgorithm
300 PublicKey interface{}
303 SerialNumber *big.Int
306 NotBefore, NotAfter time.Time // Validity bounds.
309 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
310 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
312 BasicConstraintsValid bool // if true then the next two fields are valid.
317 AuthorityKeyId []byte
319 // Subject Alternate Name values
321 EmailAddresses []string
324 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
325 PermittedDNSDomains []string
327 PolicyIdentifiers []asn1.ObjectIdentifier
330 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
331 // involves algorithms that are not currently implemented.
332 var ErrUnsupportedAlgorithm = errors.New("crypto/x509: cannot verify signature: algorithm unimplemented")
334 // ConstraintViolationError results when a requested usage is not permitted by
335 // a certificate. For example: checking a signature when the public key isn't a
336 // certificate signing key.
337 type ConstraintViolationError struct{}
339 func (ConstraintViolationError) Error() string {
340 return "crypto/x509: invalid signature: parent certificate cannot sign this kind of certificate"
343 func (c *Certificate) Equal(other *Certificate) bool {
344 return bytes.Equal(c.Raw, other.Raw)
347 // Entrust have a broken root certificate (CN=Entrust.net Certification
348 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
349 // according to PKIX.
350 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
351 // from the Basic Constraints requirement.
352 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
354 // TODO(agl): remove this hack once their reissued root is sufficiently
356 var entrustBrokenSPKI = []byte{
357 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
358 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
359 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
360 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
361 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
362 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
363 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
364 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
365 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
366 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
367 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
368 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
369 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
370 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
371 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
372 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
373 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
374 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
375 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
376 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
377 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
378 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
379 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
380 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
381 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
382 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
383 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
384 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
385 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
386 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
387 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
388 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
389 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
390 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
391 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
392 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
393 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
396 // CheckSignatureFrom verifies that the signature on c is a valid signature
398 func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) {
399 // RFC 5280, 4.2.1.9:
400 // "If the basic constraints extension is not present in a version 3
401 // certificate, or the extension is present but the cA boolean is not
402 // asserted, then the certified public key MUST NOT be used to verify
403 // certificate signatures."
404 // (except for Entrust, see comment above entrustBrokenSPKI)
405 if (parent.Version == 3 && !parent.BasicConstraintsValid ||
406 parent.BasicConstraintsValid && !parent.IsCA) &&
407 !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
408 return ConstraintViolationError{}
411 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
412 return ConstraintViolationError{}
415 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
416 return ErrUnsupportedAlgorithm
419 // TODO(agl): don't ignore the path length constraint.
421 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
424 // CheckSignature verifies that signature is a valid signature over signed from
426 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) {
427 var hashType crypto.Hash
430 case SHA1WithRSA, DSAWithSHA1:
431 hashType = crypto.SHA1
432 case SHA256WithRSA, DSAWithSHA256:
433 hashType = crypto.SHA256
435 hashType = crypto.SHA384
437 hashType = crypto.SHA512
439 return ErrUnsupportedAlgorithm
442 if !hashType.Available() {
443 return ErrUnsupportedAlgorithm
450 switch pub := c.PublicKey.(type) {
452 return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
454 dsaSig := new(dsaSignature)
455 if _, err := asn1.Unmarshal(signature, dsaSig); err != nil {
458 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
459 return errors.New("DSA signature contained zero or negative values")
461 if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
462 return errors.New("DSA verification failure")
466 return ErrUnsupportedAlgorithm
469 // CheckCRLSignature checks that the signature in crl is from c.
470 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) {
471 algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm)
472 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
475 type UnhandledCriticalExtension struct{}
477 func (h UnhandledCriticalExtension) Error() string {
478 return "unhandled critical extension"
481 type basicConstraints struct {
482 IsCA bool `asn1:"optional"`
483 MaxPathLen int `asn1:"optional,default:-1"`
487 type policyInformation struct {
488 Policy asn1.ObjectIdentifier
489 // policyQualifiers omitted
492 // RFC 5280, 4.2.1.10
493 type nameConstraints struct {
494 Permitted []generalSubtree `asn1:"optional,tag:0"`
495 Excluded []generalSubtree `asn1:"optional,tag:1"`
498 type generalSubtree struct {
499 Name string `asn1:"tag:2,optional,ia5"`
500 Min int `asn1:"optional,tag:0"`
501 Max int `asn1:"optional,tag:1"`
504 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
505 asn1Data := keyData.PublicKey.RightAlign()
508 p := new(rsaPublicKey)
509 _, err := asn1.Unmarshal(asn1Data, p)
514 pub := &rsa.PublicKey{
521 _, err := asn1.Unmarshal(asn1Data, &p)
525 paramsData := keyData.Algorithm.Parameters.FullBytes
526 params := new(dsaAlgorithmParameters)
527 _, err = asn1.Unmarshal(paramsData, params)
531 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
532 return nil, errors.New("zero or negative DSA parameter")
534 pub := &dsa.PublicKey{
535 Parameters: dsa.Parameters{
549 func parseCertificate(in *certificate) (*Certificate, error) {
550 out := new(Certificate)
552 out.RawTBSCertificate = in.TBSCertificate.Raw
553 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
554 out.RawSubject = in.TBSCertificate.Subject.FullBytes
555 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
557 out.Signature = in.SignatureValue.RightAlign()
558 out.SignatureAlgorithm =
559 getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
561 out.PublicKeyAlgorithm =
562 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
564 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
569 if in.TBSCertificate.SerialNumber.Sign() < 0 {
570 return nil, errors.New("negative serial number")
573 out.Version = in.TBSCertificate.Version + 1
574 out.SerialNumber = in.TBSCertificate.SerialNumber
576 var issuer, subject pkix.RDNSequence
577 if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
580 if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
584 out.Issuer.FillFromRDNSequence(&issuer)
585 out.Subject.FillFromRDNSequence(&subject)
587 out.NotBefore = in.TBSCertificate.Validity.NotBefore
588 out.NotAfter = in.TBSCertificate.Validity.NotAfter
590 for _, e := range in.TBSCertificate.Extensions {
591 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
595 var usageBits asn1.BitString
596 _, err := asn1.Unmarshal(e.Value, &usageBits)
600 for i := 0; i < 9; i++ {
601 if usageBits.At(i) != 0 {
602 usage |= 1 << uint(i)
605 out.KeyUsage = KeyUsage(usage)
610 var constraints basicConstraints
611 _, err := asn1.Unmarshal(e.Value, &constraints)
614 out.BasicConstraintsValid = true
615 out.IsCA = constraints.IsCA
616 out.MaxPathLen = constraints.MaxPathLen
622 // SubjectAltName ::= GeneralNames
624 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
626 // GeneralName ::= CHOICE {
627 // otherName [0] OtherName,
628 // rfc822Name [1] IA5String,
629 // dNSName [2] IA5String,
630 // x400Address [3] ORAddress,
631 // directoryName [4] Name,
632 // ediPartyName [5] EDIPartyName,
633 // uniformResourceIdentifier [6] IA5String,
634 // iPAddress [7] OCTET STRING,
635 // registeredID [8] OBJECT IDENTIFIER }
636 var seq asn1.RawValue
637 _, err := asn1.Unmarshal(e.Value, &seq)
641 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
642 return nil, asn1.StructuralError{Msg: "bad SAN sequence"}
650 rest, err = asn1.Unmarshal(rest, &v)
656 out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes))
659 out.DNSNames = append(out.DNSNames, string(v.Bytes))
667 // If we didn't parse any of the names then we
668 // fall through to the critical check below.
671 // RFC 5280, 4.2.1.10
673 // NameConstraints ::= SEQUENCE {
674 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
675 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
677 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
679 // GeneralSubtree ::= SEQUENCE {
681 // minimum [0] BaseDistance DEFAULT 0,
682 // maximum [1] BaseDistance OPTIONAL }
684 // BaseDistance ::= INTEGER (0..MAX)
686 var constraints nameConstraints
687 _, err := asn1.Unmarshal(e.Value, &constraints)
692 if len(constraints.Excluded) > 0 && e.Critical {
693 return out, UnhandledCriticalExtension{}
696 for _, subtree := range constraints.Permitted {
697 if subtree.Min > 0 || subtree.Max > 0 || len(subtree.Name) == 0 {
699 return out, UnhandledCriticalExtension{}
703 out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
710 _, err = asn1.Unmarshal(e.Value, &a)
714 out.AuthorityKeyId = a.Id
718 // RFC 5280, 4.2.1.12. Extended Key Usage
720 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
722 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
724 // KeyPurposeId ::= OBJECT IDENTIFIER
726 var keyUsage []asn1.ObjectIdentifier
727 _, err = asn1.Unmarshal(e.Value, &keyUsage)
732 for _, u := range keyUsage {
734 case u.Equal(oidExtKeyUsageAny):
735 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageAny)
736 case u.Equal(oidExtKeyUsageServerAuth):
737 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageServerAuth)
738 case u.Equal(oidExtKeyUsageClientAuth):
739 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageClientAuth)
740 case u.Equal(oidExtKeyUsageCodeSigning):
741 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageCodeSigning)
742 case u.Equal(oidExtKeyUsageEmailProtection):
743 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageEmailProtection)
744 case u.Equal(oidExtKeyUsageTimeStamping):
745 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageTimeStamping)
746 case u.Equal(oidExtKeyUsageOCSPSigning):
747 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageOCSPSigning)
749 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
758 _, err = asn1.Unmarshal(e.Value, &keyid)
762 out.SubjectKeyId = keyid
766 // RFC 5280 4.2.1.4: Certificate Policies
767 var policies []policyInformation
768 if _, err = asn1.Unmarshal(e.Value, &policies); err != nil {
771 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
772 for i, policy := range policies {
773 out.PolicyIdentifiers[i] = policy.Policy
779 return out, UnhandledCriticalExtension{}
786 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
787 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
789 rest, err := asn1.Unmarshal(asn1Data, &cert)
794 return nil, asn1.SyntaxError{Msg: "trailing data"}
797 return parseCertificate(&cert)
800 // ParseCertificates parses one or more certificates from the given ASN.1 DER
801 // data. The certificates must be concatenated with no intermediate padding.
802 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
805 for len(asn1Data) > 0 {
806 cert := new(certificate)
808 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
815 ret := make([]*Certificate, len(v))
816 for i, ci := range v {
817 cert, err := parseCertificate(ci)
827 func reverseBitsInAByte(in byte) byte {
829 b2 := b1>>2&0x33 | b1<<2&0xcc
830 b3 := b2>>1&0x55 | b2<<1&0xaa
835 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
836 oidExtensionKeyUsage = []int{2, 5, 29, 15}
837 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
838 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
839 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
840 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
841 oidExtensionNameConstraints = []int{2, 5, 29, 30}
844 func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
845 ret = make([]pkix.Extension, 7 /* maximum number of elements. */)
848 if template.KeyUsage != 0 {
849 ret[n].Id = oidExtensionKeyUsage
850 ret[n].Critical = true
853 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
854 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
861 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
868 if template.BasicConstraintsValid {
869 ret[n].Id = oidExtensionBasicConstraints
870 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
871 ret[n].Critical = true
878 if len(template.SubjectKeyId) > 0 {
879 ret[n].Id = oidExtensionSubjectKeyId
880 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
887 if len(template.AuthorityKeyId) > 0 {
888 ret[n].Id = oidExtensionAuthorityKeyId
889 ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
896 if len(template.DNSNames) > 0 {
897 ret[n].Id = oidExtensionSubjectAltName
898 rawValues := make([]asn1.RawValue, len(template.DNSNames))
899 for i, name := range template.DNSNames {
900 rawValues[i] = asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}
902 ret[n].Value, err = asn1.Marshal(rawValues)
909 if len(template.PolicyIdentifiers) > 0 {
910 ret[n].Id = oidExtensionCertificatePolicies
911 policies := make([]policyInformation, len(template.PolicyIdentifiers))
912 for i, policy := range template.PolicyIdentifiers {
913 policies[i].Policy = policy
915 ret[n].Value, err = asn1.Marshal(policies)
922 if len(template.PermittedDNSDomains) > 0 {
923 ret[n].Id = oidExtensionNameConstraints
924 ret[n].Critical = template.PermittedDNSDomainsCritical
926 var out nameConstraints
927 out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
928 for i, permitted := range template.PermittedDNSDomains {
929 out.Permitted[i] = generalSubtree{Name: permitted}
931 ret[n].Value, err = asn1.Marshal(out)
938 // Adding another extension here? Remember to update the maximum number
939 // of elements in the make() at the top of the function.
945 oidSHA1WithRSA = []int{1, 2, 840, 113549, 1, 1, 5}
946 oidRSA = []int{1, 2, 840, 113549, 1, 1, 1}
949 func subjectBytes(cert *Certificate) ([]byte, error) {
950 if len(cert.RawSubject) > 0 {
951 return cert.RawSubject, nil
954 return asn1.Marshal(cert.Subject.ToRDNSequence())
957 // CreateCertificate creates a new certificate based on a template. The
958 // following members of template are used: SerialNumber, Subject, NotBefore,
959 // NotAfter, KeyUsage, BasicConstraintsValid, IsCA, MaxPathLen, SubjectKeyId,
960 // DNSNames, PermittedDNSDomainsCritical, PermittedDNSDomains.
962 // The certificate is signed by parent. If parent is equal to template then the
963 // certificate is self-signed. The parameter pub is the public key of the
964 // signee and priv is the private key of the signer.
966 // The returned slice is the certificate in DER encoding.
968 // The only supported key type is RSA (*rsa.PublicKey for pub, *rsa.PrivateKey
970 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) {
971 rsaPub, ok := pub.(*rsa.PublicKey)
973 return nil, errors.New("x509: non-RSA public keys not supported")
976 rsaPriv, ok := priv.(*rsa.PrivateKey)
978 return nil, errors.New("x509: non-RSA private keys not supported")
981 asn1PublicKey, err := asn1.Marshal(rsaPublicKey{
989 if len(parent.SubjectKeyId) > 0 {
990 template.AuthorityKeyId = parent.SubjectKeyId
993 extensions, err := buildExtensions(template)
998 asn1Issuer, err := subjectBytes(parent)
1003 asn1Subject, err := subjectBytes(template)
1008 encodedPublicKey := asn1.BitString{BitLength: len(asn1PublicKey) * 8, Bytes: asn1PublicKey}
1009 c := tbsCertificate{
1011 SerialNumber: template.SerialNumber,
1012 SignatureAlgorithm: pkix.AlgorithmIdentifier{Algorithm: oidSHA1WithRSA},
1013 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1014 Validity: validity{template.NotBefore, template.NotAfter},
1015 Subject: asn1.RawValue{FullBytes: asn1Subject},
1016 PublicKey: publicKeyInfo{nil, pkix.AlgorithmIdentifier{Algorithm: oidRSA}, encodedPublicKey},
1017 Extensions: extensions,
1020 tbsCertContents, err := asn1.Marshal(c)
1025 c.Raw = tbsCertContents
1028 h.Write(tbsCertContents)
1029 digest := h.Sum(nil)
1031 signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
1036 cert, err = asn1.Marshal(certificate{
1039 pkix.AlgorithmIdentifier{Algorithm: oidSHA1WithRSA},
1040 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1045 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1047 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1049 // pemType is the type of a PEM encoded CRL.
1050 var pemType = "X509 CRL"
1052 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1053 // encoded CRLs will appear where they should be DER encoded, so this function
1054 // will transparently handle PEM encoding as long as there isn't any leading
1056 func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) {
1057 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1058 block, _ := pem.Decode(crlBytes)
1059 if block != nil && block.Type == pemType {
1060 crlBytes = block.Bytes
1063 return ParseDERCRL(crlBytes)
1066 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1067 func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) {
1068 certList = new(pkix.CertificateList)
1069 _, err = asn1.Unmarshal(derBytes, certList)
1076 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
1077 // contains the given list of revoked certificates.
1079 // The only supported key type is RSA (*rsa.PrivateKey for priv).
1080 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
1081 rsaPriv, ok := priv.(*rsa.PrivateKey)
1083 return nil, errors.New("x509: non-RSA private keys not supported")
1085 tbsCertList := pkix.TBSCertificateList{
1087 Signature: pkix.AlgorithmIdentifier{
1088 Algorithm: oidSignatureSHA1WithRSA,
1090 Issuer: c.Subject.ToRDNSequence(),
1093 RevokedCertificates: revokedCerts,
1096 tbsCertListContents, err := asn1.Marshal(tbsCertList)
1102 h.Write(tbsCertListContents)
1103 digest := h.Sum(nil)
1105 signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
1110 return asn1.Marshal(pkix.CertificateList{
1111 TBSCertList: tbsCertList,
1112 SignatureAlgorithm: pkix.AlgorithmIdentifier{
1113 Algorithm: oidSignatureSHA1WithRSA,
1115 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},