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.
22 // pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key.
23 type pkcs1PrivateKey struct {
30 // We ignore these values, if present, because rsa will calculate them.
31 Dp asn1.RawValue "optional"
32 Dq asn1.RawValue "optional"
33 Qinv asn1.RawValue "optional"
35 AdditionalPrimes []pkcs1AddtionalRSAPrime "optional"
38 type pkcs1AddtionalRSAPrime struct {
41 // We ignore these values because rsa will calculate them.
46 // rawValueIsInteger returns true iff the given ASN.1 RawValue is an INTEGER type.
47 func rawValueIsInteger(raw *asn1.RawValue) bool {
48 return raw.Class == 0 && raw.Tag == 2 && raw.IsCompound == false
51 // ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form.
52 func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err os.Error) {
53 var priv pkcs1PrivateKey
54 rest, err := asn1.Unmarshal(der, &priv)
56 err = asn1.SyntaxError{"trailing data"}
64 return nil, os.ErrorString("x509: unsupported private key version")
67 if !rawValueIsInteger(&priv.N) ||
68 !rawValueIsInteger(&priv.D) ||
69 !rawValueIsInteger(&priv.P) ||
70 !rawValueIsInteger(&priv.Q) {
71 err = asn1.StructuralError{"tags don't match"}
75 key = new(rsa.PrivateKey)
76 key.PublicKey = rsa.PublicKey{
78 N: new(big.Int).SetBytes(priv.N.Bytes),
81 key.D = new(big.Int).SetBytes(priv.D.Bytes)
82 key.Primes = make([]*big.Int, 2+len(priv.AdditionalPrimes))
83 key.Primes[0] = new(big.Int).SetBytes(priv.P.Bytes)
84 key.Primes[1] = new(big.Int).SetBytes(priv.Q.Bytes)
85 for i, a := range priv.AdditionalPrimes {
86 if !rawValueIsInteger(&a.Prime) {
87 return nil, asn1.StructuralError{"tags don't match"}
89 key.Primes[i+2] = new(big.Int).SetBytes(a.Prime.Bytes)
90 // We ignore the other two values because rsa will calculate
103 // rawValueForBig returns an asn1.RawValue which represents the given integer.
104 func rawValueForBig(n *big.Int) asn1.RawValue {
106 if n.Sign() >= 0 && len(b) > 0 && b[0]&0x80 != 0 {
107 // This positive number would be interpreted as a negative
108 // number in ASN.1 because the MSB is set.
109 padded := make([]byte, len(b)+1)
113 return asn1.RawValue{Tag: 2, Bytes: b}
116 // MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form.
117 func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte {
121 if len(key.Primes) > 2 {
125 priv := pkcs1PrivateKey{
127 N: rawValueForBig(key.N),
129 D: rawValueForBig(key.D),
130 P: rawValueForBig(key.Primes[0]),
131 Q: rawValueForBig(key.Primes[1]),
132 Dp: rawValueForBig(key.Precomputed.Dp),
133 Dq: rawValueForBig(key.Precomputed.Dq),
134 Qinv: rawValueForBig(key.Precomputed.Qinv),
137 priv.AdditionalPrimes = make([]pkcs1AddtionalRSAPrime, len(key.Precomputed.CRTValues))
138 for i, values := range key.Precomputed.CRTValues {
139 priv.AdditionalPrimes[i].Prime = rawValueForBig(key.Primes[2+i])
140 priv.AdditionalPrimes[i].Exp = rawValueForBig(values.Exp)
141 priv.AdditionalPrimes[i].Coeff = rawValueForBig(values.Coeff)
144 b, _ := asn1.Marshal(priv)
148 // These structures reflect the ASN.1 structure of X.509 certificates.:
150 type certificate struct {
152 TBSCertificate tbsCertificate
153 SignatureAlgorithm algorithmIdentifier
154 SignatureValue asn1.BitString
157 type tbsCertificate struct {
159 Version int "optional,explicit,default:1,tag:0"
160 SerialNumber asn1.RawValue
161 SignatureAlgorithm algorithmIdentifier
165 PublicKey publicKeyInfo
166 UniqueId asn1.BitString "optional,tag:1"
167 SubjectUniqueId asn1.BitString "optional,tag:2"
168 Extensions []extension "optional,explicit,tag:3"
171 type algorithmIdentifier struct {
172 Algorithm asn1.ObjectIdentifier
175 type rdnSequence []relativeDistinguishedNameSET
177 type relativeDistinguishedNameSET []attributeTypeAndValue
179 type attributeTypeAndValue struct {
180 Type asn1.ObjectIdentifier
184 type validity struct {
185 NotBefore, NotAfter *time.Time
188 type publicKeyInfo struct {
190 Algorithm algorithmIdentifier
191 PublicKey asn1.BitString
194 type extension struct {
195 Id asn1.ObjectIdentifier
196 Critical bool "optional"
201 type authKeyId struct {
202 Id []byte "optional,tag:0"
205 type SignatureAlgorithm int
208 UnknownSignatureAlgorithm SignatureAlgorithm = iota
217 type PublicKeyAlgorithm int
220 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
224 // Name represents an X.509 distinguished name. This only includes the common
225 // elements of a DN. Additional elements in the name are ignored.
227 Country, Organization, OrganizationalUnit []string
228 Locality, Province []string
229 StreetAddress, PostalCode []string
230 SerialNumber, CommonName string
233 func (n *Name) fillFromRDNSequence(rdns *rdnSequence) {
234 for _, rdn := range *rdns {
239 value, ok := atv.Value.(string)
245 if len(t) == 4 && t[0] == 2 && t[1] == 5 && t[2] == 4 {
250 n.SerialNumber = value
252 n.Country = append(n.Country, value)
254 n.Locality = append(n.Locality, value)
256 n.Province = append(n.Province, value)
258 n.StreetAddress = append(n.StreetAddress, value)
260 n.Organization = append(n.Organization, value)
262 n.OrganizationalUnit = append(n.OrganizationalUnit, value)
264 n.PostalCode = append(n.PostalCode, value)
271 oidCountry = []int{2, 5, 4, 6}
272 oidOrganization = []int{2, 5, 4, 10}
273 oidOrganizationalUnit = []int{2, 5, 4, 11}
274 oidCommonName = []int{2, 5, 4, 3}
275 oidSerialNumber = []int{2, 5, 4, 5}
276 oidLocatity = []int{2, 5, 4, 7}
277 oidProvince = []int{2, 5, 4, 8}
278 oidStreetAddress = []int{2, 5, 4, 9}
279 oidPostalCode = []int{2, 5, 4, 17}
282 // appendRDNs appends a relativeDistinguishedNameSET to the given rdnSequence
283 // and returns the new value. The relativeDistinguishedNameSET contains an
284 // attributeTypeAndValue for each of the given values. See RFC 5280, A.1, and
285 // search for AttributeTypeAndValue.
286 func appendRDNs(in rdnSequence, values []string, oid asn1.ObjectIdentifier) rdnSequence {
287 if len(values) == 0 {
291 s := make([]attributeTypeAndValue, len(values))
292 for i, value := range values {
300 func (n Name) toRDNSequence() (ret rdnSequence) {
301 ret = appendRDNs(ret, n.Country, oidCountry)
302 ret = appendRDNs(ret, n.Organization, oidOrganization)
303 ret = appendRDNs(ret, n.OrganizationalUnit, oidOrganizationalUnit)
304 ret = appendRDNs(ret, n.Locality, oidLocatity)
305 ret = appendRDNs(ret, n.Province, oidProvince)
306 ret = appendRDNs(ret, n.StreetAddress, oidStreetAddress)
307 ret = appendRDNs(ret, n.PostalCode, oidPostalCode)
308 if len(n.CommonName) > 0 {
309 ret = appendRDNs(ret, []string{n.CommonName}, oidCommonName)
311 if len(n.SerialNumber) > 0 {
312 ret = appendRDNs(ret, []string{n.SerialNumber}, oidSerialNumber)
318 func getSignatureAlgorithmFromOID(oid []int) SignatureAlgorithm {
319 if len(oid) == 7 && oid[0] == 1 && oid[1] == 2 && oid[2] == 840 &&
320 oid[3] == 113549 && oid[4] == 1 && oid[5] == 1 {
337 return UnknownSignatureAlgorithm
340 func getPublicKeyAlgorithmFromOID(oid []int) PublicKeyAlgorithm {
341 if len(oid) == 7 && oid[0] == 1 && oid[1] == 2 && oid[2] == 840 &&
342 oid[3] == 113549 && oid[4] == 1 && oid[5] == 1 {
349 return UnknownPublicKeyAlgorithm
352 // KeyUsage represents the set of actions that are valid for a given key. It's
353 // a bitmap of the KeyUsage* constants.
357 KeyUsageDigitalSignature KeyUsage = 1 << iota
358 KeyUsageContentCommitment
359 KeyUsageKeyEncipherment
360 KeyUsageDataEncipherment
368 // RFC 5280, 4.2.1.12 Extended Key Usage
370 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
372 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
374 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
375 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
376 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
377 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
378 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
379 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
381 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
382 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
383 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
384 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
385 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
386 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
387 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
390 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
391 // Each of the ExtKeyUsage* constants define a unique action.
395 ExtKeyUsageAny ExtKeyUsage = iota
396 ExtKeyUsageServerAuth
397 ExtKeyUsageClientAuth
398 ExtKeyUsageCodeSigning
399 ExtKeyUsageEmailProtection
400 ExtKeyUsageTimeStamping
401 ExtKeyUsageOCSPSigning
404 // A Certificate represents an X.509 certificate.
405 type Certificate struct {
406 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
407 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
408 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
411 SignatureAlgorithm SignatureAlgorithm
413 PublicKeyAlgorithm PublicKeyAlgorithm
414 PublicKey interface{}
420 NotBefore, NotAfter *time.Time // Validity bounds.
423 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
424 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
426 BasicConstraintsValid bool // if true then the next two fields are valid.
431 AuthorityKeyId []byte
433 // Subject Alternate Name values
435 EmailAddresses []string
438 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
439 PermittedDNSDomains []string
441 PolicyIdentifiers []asn1.ObjectIdentifier
444 // UnsupportedAlgorithmError results from attempting to perform an operation
445 // that involves algorithms that are not currently implemented.
446 type UnsupportedAlgorithmError struct{}
448 func (UnsupportedAlgorithmError) String() string {
449 return "cannot verify signature: algorithm unimplemented"
452 // ConstraintViolationError results when a requested usage is not permitted by
453 // a certificate. For example: checking a signature when the public key isn't a
454 // certificate signing key.
455 type ConstraintViolationError struct{}
457 func (ConstraintViolationError) String() string {
458 return "invalid signature: parent certificate cannot sign this kind of certificate"
461 func (c *Certificate) Equal(other *Certificate) bool {
462 return bytes.Equal(c.Raw, other.Raw)
465 // CheckSignatureFrom verifies that the signature on c is a valid signature
467 func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err os.Error) {
468 // RFC 5280, 4.2.1.9:
469 // "If the basic constraints extension is not present in a version 3
470 // certificate, or the extension is present but the cA boolean is not
471 // asserted, then the certified public key MUST NOT be used to verify
472 // certificate signatures."
473 if parent.Version == 3 && !parent.BasicConstraintsValid ||
474 parent.BasicConstraintsValid && !parent.IsCA {
475 return ConstraintViolationError{}
478 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
479 return ConstraintViolationError{}
482 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
483 return UnsupportedAlgorithmError{}
486 // TODO(agl): don't ignore the path length constraint.
489 var hashType crypto.Hash
491 switch c.SignatureAlgorithm {
494 hashType = crypto.SHA1
496 return UnsupportedAlgorithmError{}
499 pub, ok := parent.PublicKey.(*rsa.PublicKey)
501 return UnsupportedAlgorithmError{}
504 h.Write(c.RawTBSCertificate)
507 return rsa.VerifyPKCS1v15(pub, hashType, digest, c.Signature)
510 type UnhandledCriticalExtension struct{}
512 func (h UnhandledCriticalExtension) String() string {
513 return "unhandled critical extension"
516 type basicConstraints struct {
518 MaxPathLen int "optional"
521 type rsaPublicKey struct {
527 type policyInformation struct {
528 Policy asn1.ObjectIdentifier
529 // policyQualifiers omitted
532 // RFC 5280, 4.2.1.10
533 type nameConstraints struct {
534 Permitted []generalSubtree "optional,tag:0"
535 Excluded []generalSubtree "optional,tag:1"
538 type generalSubtree struct {
539 Name string "tag:2,optional,ia5"
540 Min int "optional,tag:0"
541 Max int "optional,tag:1"
544 func parsePublicKey(algo PublicKeyAlgorithm, asn1Data []byte) (interface{}, os.Error) {
547 p := new(rsaPublicKey)
548 _, err := asn1.Unmarshal(asn1Data, p)
553 if !rawValueIsInteger(&p.N) {
554 return nil, asn1.StructuralError{"tags don't match"}
557 pub := &rsa.PublicKey{
559 N: new(big.Int).SetBytes(p.N.Bytes),
569 func parseCertificate(in *certificate) (*Certificate, os.Error) {
570 out := new(Certificate)
572 out.RawTBSCertificate = in.TBSCertificate.Raw
573 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
575 out.Signature = in.SignatureValue.RightAlign()
576 out.SignatureAlgorithm =
577 getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
579 out.PublicKeyAlgorithm =
580 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
582 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, in.TBSCertificate.PublicKey.PublicKey.RightAlign())
587 out.Version = in.TBSCertificate.Version + 1
588 out.SerialNumber = in.TBSCertificate.SerialNumber.Bytes
589 out.Issuer.fillFromRDNSequence(&in.TBSCertificate.Issuer)
590 out.Subject.fillFromRDNSequence(&in.TBSCertificate.Subject)
591 out.NotBefore = in.TBSCertificate.Validity.NotBefore
592 out.NotAfter = in.TBSCertificate.Validity.NotAfter
594 for _, e := range in.TBSCertificate.Extensions {
595 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
599 var usageBits asn1.BitString
600 _, err := asn1.Unmarshal(e.Value, &usageBits)
604 for i := 0; i < 9; i++ {
605 if usageBits.At(i) != 0 {
606 usage |= 1 << uint(i)
609 out.KeyUsage = KeyUsage(usage)
614 var constriants basicConstraints
615 _, err := asn1.Unmarshal(e.Value, &constriants)
618 out.BasicConstraintsValid = true
619 out.IsCA = constriants.IsCA
620 out.MaxPathLen = constriants.MaxPathLen
626 // SubjectAltName ::= GeneralNames
628 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
630 // GeneralName ::= CHOICE {
631 // otherName [0] OtherName,
632 // rfc822Name [1] IA5String,
633 // dNSName [2] IA5String,
634 // x400Address [3] ORAddress,
635 // directoryName [4] Name,
636 // ediPartyName [5] EDIPartyName,
637 // uniformResourceIdentifier [6] IA5String,
638 // iPAddress [7] OCTET STRING,
639 // registeredID [8] OBJECT IDENTIFIER }
640 var seq asn1.RawValue
641 _, err := asn1.Unmarshal(e.Value, &seq)
645 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
646 return nil, asn1.StructuralError{"bad SAN sequence"}
654 rest, err = asn1.Unmarshal(rest, &v)
660 out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes))
663 out.DNSNames = append(out.DNSNames, string(v.Bytes))
671 // If we didn't parse any of the names then we
672 // fall through to the critical check below.
675 // RFC 5280, 4.2.1.10
677 // NameConstraints ::= SEQUENCE {
678 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
679 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
681 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
683 // GeneralSubtree ::= SEQUENCE {
685 // minimum [0] BaseDistance DEFAULT 0,
686 // maximum [1] BaseDistance OPTIONAL }
688 // BaseDistance ::= INTEGER (0..MAX)
690 var constraints nameConstraints
691 _, err := asn1.Unmarshal(e.Value, &constraints)
696 if len(constraints.Excluded) > 0 && e.Critical {
697 return out, UnhandledCriticalExtension{}
700 for _, subtree := range constraints.Permitted {
701 if subtree.Min > 0 || subtree.Max > 0 || len(subtree.Name) == 0 {
703 return out, UnhandledCriticalExtension{}
707 out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
714 _, err = asn1.Unmarshal(e.Value, &a)
718 out.AuthorityKeyId = a.Id
722 // RFC 5280, 4.2.1.12. Extended Key Usage
724 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
726 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
728 // KeyPurposeId ::= OBJECT IDENTIFIER
730 var keyUsage []asn1.ObjectIdentifier
731 _, err = asn1.Unmarshal(e.Value, &keyUsage)
736 for _, u := range keyUsage {
738 case u.Equal(oidExtKeyUsageAny):
739 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageAny)
740 case u.Equal(oidExtKeyUsageServerAuth):
741 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageServerAuth)
742 case u.Equal(oidExtKeyUsageClientAuth):
743 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageClientAuth)
744 case u.Equal(oidExtKeyUsageCodeSigning):
745 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageCodeSigning)
746 case u.Equal(oidExtKeyUsageEmailProtection):
747 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageEmailProtection)
748 case u.Equal(oidExtKeyUsageTimeStamping):
749 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageTimeStamping)
750 case u.Equal(oidExtKeyUsageOCSPSigning):
751 out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageOCSPSigning)
753 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
762 _, err = asn1.Unmarshal(e.Value, &keyid)
766 out.SubjectKeyId = keyid
770 // RFC 5280 4.2.1.4: Certificate Policies
771 var policies []policyInformation
772 if _, err = asn1.Unmarshal(e.Value, &policies); err != nil {
775 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
776 for i, policy := range policies {
777 out.PolicyIdentifiers[i] = policy.Policy
783 return out, UnhandledCriticalExtension{}
790 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
791 func ParseCertificate(asn1Data []byte) (*Certificate, os.Error) {
793 rest, err := asn1.Unmarshal(asn1Data, &cert)
798 return nil, asn1.SyntaxError{"trailing data"}
801 return parseCertificate(&cert)
804 // ParseCertificates parses one or more certificates from the given ASN.1 DER
805 // data. The certificates must be concatenated with no intermediate padding.
806 func ParseCertificates(asn1Data []byte) ([]*Certificate, os.Error) {
807 v := new(vector.Vector)
809 for len(asn1Data) > 0 {
810 cert := new(certificate)
812 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
819 ret := make([]*Certificate, v.Len())
820 for i := 0; i < v.Len(); i++ {
821 cert, err := parseCertificate(v.At(i).(*certificate))
831 func reverseBitsInAByte(in byte) byte {
833 b2 := b1>>2&0x33 | b1<<2&0xcc
834 b3 := b2>>1&0x55 | b2<<1&0xaa
839 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
840 oidExtensionKeyUsage = []int{2, 5, 29, 15}
841 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
842 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
843 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
844 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
845 oidExtensionNameConstraints = []int{2, 5, 29, 30}
848 func buildExtensions(template *Certificate) (ret []extension, err os.Error) {
849 ret = make([]extension, 7 /* maximum number of elements. */ )
852 if template.KeyUsage != 0 {
853 ret[n].Id = oidExtensionKeyUsage
854 ret[n].Critical = true
857 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
858 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
865 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
872 if template.BasicConstraintsValid {
873 ret[n].Id = oidExtensionBasicConstraints
874 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
875 ret[n].Critical = true
882 if len(template.SubjectKeyId) > 0 {
883 ret[n].Id = oidExtensionSubjectKeyId
884 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
891 if len(template.AuthorityKeyId) > 0 {
892 ret[n].Id = oidExtensionAuthorityKeyId
893 ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
900 if len(template.DNSNames) > 0 {
901 ret[n].Id = oidExtensionSubjectAltName
902 rawValues := make([]asn1.RawValue, len(template.DNSNames))
903 for i, name := range template.DNSNames {
904 rawValues[i] = asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}
906 ret[n].Value, err = asn1.Marshal(rawValues)
913 if len(template.PolicyIdentifiers) > 0 {
914 ret[n].Id = oidExtensionCertificatePolicies
915 policies := make([]policyInformation, len(template.PolicyIdentifiers))
916 for i, policy := range template.PolicyIdentifiers {
917 policies[i].Policy = policy
919 ret[n].Value, err = asn1.Marshal(policies)
926 if len(template.PermittedDNSDomains) > 0 {
927 ret[n].Id = oidExtensionNameConstraints
928 ret[n].Critical = template.PermittedDNSDomainsCritical
930 var out nameConstraints
931 out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
932 for i, permitted := range template.PermittedDNSDomains {
933 out.Permitted[i] = generalSubtree{Name: permitted}
935 ret[n].Value, err = asn1.Marshal(out)
942 // Adding another extension here? Remember to update the maximum number
943 // of elements in the make() at the top of the function.
949 oidSHA1WithRSA = []int{1, 2, 840, 113549, 1, 1, 5}
950 oidRSA = []int{1, 2, 840, 113549, 1, 1, 1}
953 // CreateSelfSignedCertificate creates a new certificate based on
954 // a template. The following members of template are used: SerialNumber,
955 // Subject, NotBefore, NotAfter, KeyUsage, BasicConstraintsValid, IsCA,
956 // MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
957 // PermittedDNSDomains.
959 // The certificate is signed by parent. If parent is equal to template then the
960 // certificate is self-signed. The parameter pub is the public key of the
961 // signee and priv is the private key of the signer.
963 // The returned slice is the certificate in DER encoding.
964 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub *rsa.PublicKey, priv *rsa.PrivateKey) (cert []byte, err os.Error) {
965 asn1PublicKey, err := asn1.Marshal(rsaPublicKey{
966 N: asn1.RawValue{Tag: 2, Bytes: pub.N.Bytes()},
973 if len(parent.SubjectKeyId) > 0 {
974 template.AuthorityKeyId = parent.SubjectKeyId
977 extensions, err := buildExtensions(template)
982 encodedPublicKey := asn1.BitString{BitLength: len(asn1PublicKey) * 8, Bytes: asn1PublicKey}
985 SerialNumber: asn1.RawValue{Bytes: template.SerialNumber, Tag: 2},
986 SignatureAlgorithm: algorithmIdentifier{oidSHA1WithRSA},
987 Issuer: parent.Subject.toRDNSequence(),
988 Validity: validity{template.NotBefore, template.NotAfter},
989 Subject: template.Subject.toRDNSequence(),
990 PublicKey: publicKeyInfo{nil, algorithmIdentifier{oidRSA}, encodedPublicKey},
991 Extensions: extensions,
994 tbsCertContents, err := asn1.Marshal(c)
999 c.Raw = tbsCertContents
1002 h.Write(tbsCertContents)
1005 signature, err := rsa.SignPKCS1v15(rand, priv, crypto.SHA1, digest)
1010 cert, err = asn1.Marshal(certificate{
1013 algorithmIdentifier{oidSHA1WithRSA},
1014 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},