1 // crypto/x509 add sm2 support
30 "golang.org/x/crypto/ripemd160"
31 "golang.org/x/crypto/sha3"
33 "github.com/vapor/crypto/sm3"
36 // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
38 type pkixPublicKey struct {
39 Algo pkix.AlgorithmIdentifier
40 BitString asn1.BitString
43 // ParsePKIXPublicKey parses a DER encoded public key. These values are
44 // typically found in PEM blocks with "BEGIN PUBLIC KEY".
46 // Supported key types include RSA, DSA, and ECDSA. Unknown key
47 // types result in an error.
49 // On success, pub will be of type *rsa.PublicKey, *dsa.PublicKey,
50 // or *ecdsa.PublicKey.
51 func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
54 if rest, err := asn1.Unmarshal(derBytes, &pki); err != nil {
56 } else if len(rest) != 0 {
57 return nil, errors.New("x509: trailing data after ASN.1 of public-key")
59 algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
60 if algo == UnknownPublicKeyAlgorithm {
61 return nil, errors.New("x509: unknown public key algorithm")
63 return parsePublicKey(algo, &pki)
66 func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) {
67 switch pub := pub.(type) {
69 publicKeyBytes, err = asn1.Marshal(rsaPublicKey{
74 return nil, pkix.AlgorithmIdentifier{}, err
76 publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
77 // This is a NULL parameters value which is required by
78 // https://tools.ietf.org/html/rfc3279#section-2.3.1.
79 publicKeyAlgorithm.Parameters = asn1.RawValue{
82 case *ecdsa.PublicKey:
83 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
84 oid, ok := oidFromNamedCurve(pub.Curve)
86 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve")
88 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
90 paramBytes, err = asn1.Marshal(oid)
94 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
96 publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
97 oid, ok := oidFromNamedCurve(pub.Curve)
99 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported SM2 curve")
101 publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
102 var paramBytes []byte
103 paramBytes, err = asn1.Marshal(oid)
107 publicKeyAlgorithm.Parameters.FullBytes = paramBytes
109 return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA(SM2) public keys supported")
112 return publicKeyBytes, publicKeyAlgorithm, nil
115 // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
116 func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
117 var publicKeyBytes []byte
118 var publicKeyAlgorithm pkix.AlgorithmIdentifier
121 if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil {
125 pkix := pkixPublicKey{
126 Algo: publicKeyAlgorithm,
127 BitString: asn1.BitString{
128 Bytes: publicKeyBytes,
129 BitLength: 8 * len(publicKeyBytes),
133 ret, _ := asn1.Marshal(pkix)
137 // These structures reflect the ASN.1 structure of X.509 certificates.:
139 type certificate struct {
141 TBSCertificate tbsCertificate
142 SignatureAlgorithm pkix.AlgorithmIdentifier
143 SignatureValue asn1.BitString
146 type tbsCertificate struct {
148 Version int `asn1:"optional,explicit,default:0,tag:0"`
149 SerialNumber *big.Int
150 SignatureAlgorithm pkix.AlgorithmIdentifier
153 Subject asn1.RawValue
154 PublicKey publicKeyInfo
155 UniqueId asn1.BitString `asn1:"optional,tag:1"`
156 SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"`
157 Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"`
160 type dsaAlgorithmParameters struct {
164 type dsaSignature struct {
168 type ecdsaSignature dsaSignature
170 type validity struct {
171 NotBefore, NotAfter time.Time
174 type publicKeyInfo struct {
176 Algorithm pkix.AlgorithmIdentifier
177 PublicKey asn1.BitString
181 type authKeyId struct {
182 Id []byte `asn1:"optional,tag:0"`
185 type SignatureAlgorithm int
190 RegisterHash(MD4, nil)
191 RegisterHash(MD5, md5.New)
192 RegisterHash(SHA1, sha1.New)
193 RegisterHash(SHA224, sha256.New224)
194 RegisterHash(SHA256, sha256.New)
195 RegisterHash(SHA384, sha512.New384)
196 RegisterHash(SHA512, sha512.New)
197 RegisterHash(MD5SHA1, nil)
198 RegisterHash(RIPEMD160, ripemd160.New)
199 RegisterHash(SHA3_224, sha3.New224)
200 RegisterHash(SHA3_256, sha3.New256)
201 RegisterHash(SHA3_384, sha3.New384)
202 RegisterHash(SHA3_512, sha3.New512)
203 RegisterHash(SHA512_224, sha512.New512_224)
204 RegisterHash(SHA512_256, sha512.New512_256)
205 RegisterHash(SM3, sm3.New)
208 // HashFunc simply returns the value of h so that Hash implements SignerOpts.
209 func (h Hash) HashFunc() crypto.Hash {
210 return crypto.Hash(h)
214 MD4 Hash = 1 + iota // import golang.org/x/crypto/md4
215 MD5 // import crypto/md5
216 SHA1 // import crypto/sha1
217 SHA224 // import crypto/sha256
218 SHA256 // import crypto/sha256
219 SHA384 // import crypto/sha512
220 SHA512 // import crypto/sha512
221 MD5SHA1 // no implementation; MD5+SHA1 used for TLS RSA
222 RIPEMD160 // import golang.org/x/crypto/ripemd160
223 SHA3_224 // import golang.org/x/crypto/sha3
224 SHA3_256 // import golang.org/x/crypto/sha3
225 SHA3_384 // import golang.org/x/crypto/sha3
226 SHA3_512 // import golang.org/x/crypto/sha3
227 SHA512_224 // import crypto/sha512
228 SHA512_256 // import crypto/sha512
233 var digestSizes = []uint8{
252 // Size returns the length, in bytes, of a digest resulting from the given hash
253 // function. It doesn't require that the hash function in question be linked
255 func (h Hash) Size() int {
256 if h > 0 && h < maxHash {
257 return int(digestSizes[h])
259 panic("crypto: Size of unknown hash function")
262 var hashes = make([]func() hash.Hash, maxHash)
264 // New returns a new hash.Hash calculating the given hash function. New panics
265 // if the hash function is not linked into the binary.
266 func (h Hash) New() hash.Hash {
267 if h > 0 && h < maxHash {
273 panic("crypto: requested hash function #" + strconv.Itoa(int(h)) + " is unavailable")
276 // Available reports whether the given hash function is linked into the binary.
277 func (h Hash) Available() bool {
278 return h < maxHash && hashes[h] != nil
281 // RegisterHash registers a function that returns a new instance of the given
282 // hash function. This is intended to be called from the init function in
283 // packages that implement hash functions.
284 func RegisterHash(h Hash, f func() hash.Hash) {
286 panic("crypto: RegisterHash of unknown hash function")
292 UnknownSignatureAlgorithm SignatureAlgorithm = iota
295 // SM3WithRSA reserve
314 func (algo SignatureAlgorithm) isRSAPSS() bool {
316 case SHA256WithRSAPSS, SHA384WithRSAPSS, SHA512WithRSAPSS:
323 var algoName = [...]string{
324 MD2WithRSA: "MD2-RSA",
325 MD5WithRSA: "MD5-RSA",
326 SHA1WithRSA: "SHA1-RSA",
327 // SM3WithRSA: "SM3-RSA", reserve
328 SHA256WithRSA: "SHA256-RSA",
329 SHA384WithRSA: "SHA384-RSA",
330 SHA512WithRSA: "SHA512-RSA",
331 SHA256WithRSAPSS: "SHA256-RSAPSS",
332 SHA384WithRSAPSS: "SHA384-RSAPSS",
333 SHA512WithRSAPSS: "SHA512-RSAPSS",
334 DSAWithSHA1: "DSA-SHA1",
335 DSAWithSHA256: "DSA-SHA256",
336 ECDSAWithSHA1: "ECDSA-SHA1",
337 ECDSAWithSHA256: "ECDSA-SHA256",
338 ECDSAWithSHA384: "ECDSA-SHA384",
339 ECDSAWithSHA512: "ECDSA-SHA512",
340 SM2WithSM3: "SM2-SM3",
341 SM2WithSHA1: "SM2-SHA1",
342 SM2WithSHA256: "SM2-SHA256",
345 func (algo SignatureAlgorithm) String() string {
346 if 0 < algo && int(algo) < len(algoName) {
347 return algoName[algo]
349 return strconv.Itoa(int(algo))
352 type PublicKeyAlgorithm int
355 UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
361 // OIDs for signature algorithms
363 // pkcs-1 OBJECT IDENTIFIER ::= {
364 // iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
367 // RFC 3279 2.2.1 RSA Signature Algorithms
369 // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
371 // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
373 // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
375 // dsaWithSha1 OBJECT IDENTIFIER ::= {
376 // iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
378 // RFC 3279 2.2.3 ECDSA Signature Algorithm
380 // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
381 // iso(1) member-body(2) us(840) ansi-x962(10045)
382 // signatures(4) ecdsa-with-SHA1(1)}
385 // RFC 4055 5 PKCS #1 Version 1.5
387 // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
389 // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
391 // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
394 // RFC 5758 3.1 DSA Signature Algorithms
396 // dsaWithSha256 OBJECT IDENTIFIER ::= {
397 // joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
398 // csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
400 // RFC 5758 3.2 ECDSA Signature Algorithm
402 // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
403 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
405 // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
406 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
408 // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
409 // us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
412 oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
413 oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
414 oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
415 oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
416 oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
417 oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
418 oidSignatureRSAPSS = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 10}
419 oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
420 oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 3, 2}
421 oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
422 oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
423 oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
424 oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
425 oidSignatureSM2WithSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 501}
426 oidSignatureSM2WithSHA1 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 502}
427 oidSignatureSM2WithSHA256 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 503}
428 // oidSignatureSM3WithRSA = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 504}
430 oidSM3 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 401, 1}
431 oidSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 1}
432 oidSHA384 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 2}
433 oidSHA512 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 3, 4, 2, 3}
435 oidMGF1 = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 8}
437 // oidISOSignatureSHA1WithRSA means the same as oidSignatureSHA1WithRSA
438 // but it's specified by ISO. Microsoft's makecert.exe has been known
439 // to produce certificates with this OID.
440 oidISOSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 3, 14, 3, 2, 29}
443 var signatureAlgorithmDetails = []struct {
444 algo SignatureAlgorithm
445 oid asn1.ObjectIdentifier
446 pubKeyAlgo PublicKeyAlgorithm
449 {MD2WithRSA, oidSignatureMD2WithRSA, RSA, Hash(0) /* no value for MD2 */},
450 {MD5WithRSA, oidSignatureMD5WithRSA, RSA, MD5},
451 {SHA1WithRSA, oidSignatureSHA1WithRSA, RSA, SHA1},
452 {SHA1WithRSA, oidISOSignatureSHA1WithRSA, RSA, SHA1},
453 {SHA256WithRSA, oidSignatureSHA256WithRSA, RSA, SHA256},
454 {SHA384WithRSA, oidSignatureSHA384WithRSA, RSA, SHA384},
455 {SHA512WithRSA, oidSignatureSHA512WithRSA, RSA, SHA512},
456 {SHA256WithRSAPSS, oidSignatureRSAPSS, RSA, SHA256},
457 {SHA384WithRSAPSS, oidSignatureRSAPSS, RSA, SHA384},
458 {SHA512WithRSAPSS, oidSignatureRSAPSS, RSA, SHA512},
459 {DSAWithSHA1, oidSignatureDSAWithSHA1, DSA, SHA1},
460 {DSAWithSHA256, oidSignatureDSAWithSHA256, DSA, SHA256},
461 {ECDSAWithSHA1, oidSignatureECDSAWithSHA1, ECDSA, SHA1},
462 {ECDSAWithSHA256, oidSignatureECDSAWithSHA256, ECDSA, SHA256},
463 {ECDSAWithSHA384, oidSignatureECDSAWithSHA384, ECDSA, SHA384},
464 {ECDSAWithSHA512, oidSignatureECDSAWithSHA512, ECDSA, SHA512},
465 {SM2WithSM3, oidSignatureSM2WithSM3, ECDSA, SM3},
466 {SM2WithSHA1, oidSignatureSM2WithSHA1, ECDSA, SHA1},
467 {SM2WithSHA256, oidSignatureSM2WithSHA256, ECDSA, SHA256},
468 // {SM3WithRSA, oidSignatureSM3WithRSA, RSA, SM3},
471 // pssParameters reflects the parameters in an AlgorithmIdentifier that
472 // specifies RSA PSS. See https://tools.ietf.org/html/rfc3447#appendix-A.2.3
473 type pssParameters struct {
474 // The following three fields are not marked as
475 // optional because the default values specify SHA-1,
476 // which is no longer suitable for use in signatures.
477 Hash pkix.AlgorithmIdentifier `asn1:"explicit,tag:0"`
478 MGF pkix.AlgorithmIdentifier `asn1:"explicit,tag:1"`
479 SaltLength int `asn1:"explicit,tag:2"`
480 TrailerField int `asn1:"optional,explicit,tag:3,default:1"`
483 // rsaPSSParameters returns an asn1.RawValue suitable for use as the Parameters
484 // in an AlgorithmIdentifier that specifies RSA PSS.
485 func rsaPSSParameters(hashFunc Hash) asn1.RawValue {
486 var hashOID asn1.ObjectIdentifier
497 params := pssParameters{
498 Hash: pkix.AlgorithmIdentifier{
500 Parameters: asn1.RawValue{
501 Tag: 5, /* ASN.1 NULL */
504 MGF: pkix.AlgorithmIdentifier{
507 SaltLength: hashFunc.Size(),
511 mgf1Params := pkix.AlgorithmIdentifier{
513 Parameters: asn1.RawValue{
514 Tag: 5, /* ASN.1 NULL */
519 params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
524 serialized, err := asn1.Marshal(params)
529 return asn1.RawValue{FullBytes: serialized}
532 func getSignatureAlgorithmFromAI(ai pkix.AlgorithmIdentifier) SignatureAlgorithm {
533 if !ai.Algorithm.Equal(oidSignatureRSAPSS) {
534 for _, details := range signatureAlgorithmDetails {
535 if ai.Algorithm.Equal(details.oid) {
539 return UnknownSignatureAlgorithm
542 // RSA PSS is special because it encodes important parameters
543 // in the Parameters.
545 var params pssParameters
546 if _, err := asn1.Unmarshal(ai.Parameters.FullBytes, ¶ms); err != nil {
547 return UnknownSignatureAlgorithm
550 var mgf1HashFunc pkix.AlgorithmIdentifier
551 if _, err := asn1.Unmarshal(params.MGF.Parameters.FullBytes, &mgf1HashFunc); err != nil {
552 return UnknownSignatureAlgorithm
555 // PSS is greatly overburdened with options. This code forces
556 // them into three buckets by requiring that the MGF1 hash
557 // function always match the message hash function (as
559 // https://tools.ietf.org/html/rfc3447#section-8.1), that the
560 // salt length matches the hash length, and that the trailer
561 // field has the default value.
562 asn1NULL := []byte{0x05, 0x00}
563 if !bytes.Equal(params.Hash.Parameters.FullBytes, asn1NULL) ||
564 !params.MGF.Algorithm.Equal(oidMGF1) ||
565 !mgf1HashFunc.Algorithm.Equal(params.Hash.Algorithm) ||
566 !bytes.Equal(mgf1HashFunc.Parameters.FullBytes, asn1NULL) ||
567 params.TrailerField != 1 {
568 return UnknownSignatureAlgorithm
572 case params.Hash.Algorithm.Equal(oidSHA256) && params.SaltLength == 32:
573 return SHA256WithRSAPSS
574 case params.Hash.Algorithm.Equal(oidSHA384) && params.SaltLength == 48:
575 return SHA384WithRSAPSS
576 case params.Hash.Algorithm.Equal(oidSHA512) && params.SaltLength == 64:
577 return SHA512WithRSAPSS
580 return UnknownSignatureAlgorithm
583 // RFC 3279, 2.3 Public Key Algorithms
585 // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
586 // rsadsi(113549) pkcs(1) 1 }
588 // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
590 // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
591 // x9-57(10040) x9cm(4) 1 }
593 // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
595 // id-ecPublicKey OBJECT IDENTIFIER ::= {
596 // iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
598 oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
599 oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
600 oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
603 func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
605 case oid.Equal(oidPublicKeyRSA):
607 case oid.Equal(oidPublicKeyDSA):
609 case oid.Equal(oidPublicKeyECDSA):
612 return UnknownPublicKeyAlgorithm
615 // RFC 5480, 2.1.1.1. Named Curve
617 // secp224r1 OBJECT IDENTIFIER ::= {
618 // iso(1) identified-organization(3) certicom(132) curve(0) 33 }
620 // secp256r1 OBJECT IDENTIFIER ::= {
621 // iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
624 // secp384r1 OBJECT IDENTIFIER ::= {
625 // iso(1) identified-organization(3) certicom(132) curve(0) 34 }
627 // secp521r1 OBJECT IDENTIFIER ::= {
628 // iso(1) identified-organization(3) certicom(132) curve(0) 35 }
630 // NB: secp256r1 is equivalent to prime256v1
632 oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
633 oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
634 oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
635 oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
636 oidNamedCurveP256SM2 = asn1.ObjectIdentifier{1, 2, 156, 10197, 1, 301} // I get the SM2 ID through parsing the pem file generated by gmssl
639 func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
641 case oid.Equal(oidNamedCurveP224):
642 return elliptic.P224()
643 case oid.Equal(oidNamedCurveP256):
644 return elliptic.P256()
645 case oid.Equal(oidNamedCurveP384):
646 return elliptic.P384()
647 case oid.Equal(oidNamedCurveP521):
648 return elliptic.P521()
649 case oid.Equal(oidNamedCurveP256SM2):
655 func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
657 case elliptic.P224():
658 return oidNamedCurveP224, true
659 case elliptic.P256():
660 return oidNamedCurveP256, true
661 case elliptic.P384():
662 return oidNamedCurveP384, true
663 case elliptic.P521():
664 return oidNamedCurveP521, true
666 return oidNamedCurveP256SM2, true
671 // KeyUsage represents the set of actions that are valid for a given key. It's
672 // a bitmap of the KeyUsage* constants.
676 KeyUsageDigitalSignature KeyUsage = 1 << iota
677 KeyUsageContentCommitment
678 KeyUsageKeyEncipherment
679 KeyUsageDataEncipherment
687 // RFC 5280, 4.2.1.12 Extended Key Usage
689 // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
691 // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
693 // id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 }
694 // id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 }
695 // id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 }
696 // id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 }
697 // id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 }
698 // id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 }
700 oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
701 oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
702 oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
703 oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
704 oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
705 oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
706 oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
707 oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
708 oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
709 oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
710 oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
711 oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
714 // ExtKeyUsage represents an extended set of actions that are valid for a given key.
715 // Each of the ExtKeyUsage* constants define a unique action.
719 ExtKeyUsageAny ExtKeyUsage = iota
720 ExtKeyUsageServerAuth
721 ExtKeyUsageClientAuth
722 ExtKeyUsageCodeSigning
723 ExtKeyUsageEmailProtection
724 ExtKeyUsageIPSECEndSystem
725 ExtKeyUsageIPSECTunnel
727 ExtKeyUsageTimeStamping
728 ExtKeyUsageOCSPSigning
729 ExtKeyUsageMicrosoftServerGatedCrypto
730 ExtKeyUsageNetscapeServerGatedCrypto
733 // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
734 var extKeyUsageOIDs = []struct {
735 extKeyUsage ExtKeyUsage
736 oid asn1.ObjectIdentifier
738 {ExtKeyUsageAny, oidExtKeyUsageAny},
739 {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
740 {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
741 {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
742 {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
743 {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
744 {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
745 {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
746 {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
747 {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
748 {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
749 {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
752 func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
753 for _, pair := range extKeyUsageOIDs {
754 if oid.Equal(pair.oid) {
755 return pair.extKeyUsage, true
761 func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
762 for _, pair := range extKeyUsageOIDs {
763 if eku == pair.extKeyUsage {
764 return pair.oid, true
770 // A Certificate represents an X.509 certificate.
771 type Certificate struct {
772 Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
773 RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content.
774 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
775 RawSubject []byte // DER encoded Subject
776 RawIssuer []byte // DER encoded Issuer
779 SignatureAlgorithm SignatureAlgorithm
781 PublicKeyAlgorithm PublicKeyAlgorithm
782 PublicKey interface{}
785 SerialNumber *big.Int
788 NotBefore, NotAfter time.Time // Validity bounds.
791 // Extensions contains raw X.509 extensions. When parsing certificates,
792 // this can be used to extract non-critical extensions that are not
793 // parsed by this package. When marshaling certificates, the Extensions
794 // field is ignored, see ExtraExtensions.
795 Extensions []pkix.Extension
797 // ExtraExtensions contains extensions to be copied, raw, into any
798 // marshaled certificates. Values override any extensions that would
799 // otherwise be produced based on the other fields. The ExtraExtensions
800 // field is not populated when parsing certificates, see Extensions.
801 ExtraExtensions []pkix.Extension
803 // UnhandledCriticalExtensions contains a list of extension IDs that
804 // were not (fully) processed when parsing. Verify will fail if this
805 // slice is non-empty, unless verification is delegated to an OS
806 // library which understands all the critical extensions.
808 // Users can access these extensions using Extensions and can remove
809 // elements from this slice if they believe that they have been
811 UnhandledCriticalExtensions []asn1.ObjectIdentifier
813 ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages.
814 UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
816 BasicConstraintsValid bool // if true then the next two fields are valid.
819 // MaxPathLenZero indicates that BasicConstraintsValid==true and
820 // MaxPathLen==0 should be interpreted as an actual maximum path length
821 // of zero. Otherwise, that combination is interpreted as MaxPathLen
826 AuthorityKeyId []byte
828 // RFC 5280, 4.2.2.1 (Authority Information Access)
830 IssuingCertificateURL []string
832 // Subject Alternate Name values
834 EmailAddresses []string
838 PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
839 PermittedDNSDomains []string
841 // CRL Distribution Points
842 CRLDistributionPoints []string
844 PolicyIdentifiers []asn1.ObjectIdentifier
847 // ErrUnsupportedAlgorithm results from attempting to perform an operation that
848 // involves algorithms that are not currently implemented.
849 var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented")
851 // An InsecureAlgorithmError
852 type InsecureAlgorithmError SignatureAlgorithm
854 func (e InsecureAlgorithmError) Error() string {
855 return fmt.Sprintf("x509: cannot verify signature: insecure algorithm %v", SignatureAlgorithm(e))
858 // ConstraintViolationError results when a requested usage is not permitted by
859 // a certificate. For example: checking a signature when the public key isn't a
860 // certificate signing key.
861 type ConstraintViolationError struct{}
863 func (ConstraintViolationError) Error() string {
864 return "x509: invalid signature: parent certificate cannot sign this kind of certificate"
867 func (c *Certificate) Equal(other *Certificate) bool {
868 return bytes.Equal(c.Raw, other.Raw)
871 // Entrust have a broken root certificate (CN=Entrust.net Certification
872 // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
873 // according to PKIX.
874 // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
875 // from the Basic Constraints requirement.
876 // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
878 // TODO(agl): remove this hack once their reissued root is sufficiently
880 var entrustBrokenSPKI = []byte{
881 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
882 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
883 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
884 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
885 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
886 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
887 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
888 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
889 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
890 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
891 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
892 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
893 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
894 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
895 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
896 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
897 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
898 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
899 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
900 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
901 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
902 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
903 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
904 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
905 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
906 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
907 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
908 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
909 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
910 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
911 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
912 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
913 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
914 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
915 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
916 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
917 0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
920 // CheckSignatureFrom verifies that the signature on c is a valid signature
922 func (c *Certificate) CheckSignatureFrom(parent *Certificate) error {
923 // RFC 5280, 4.2.1.9:
924 // "If the basic constraints extension is not present in a version 3
925 // certificate, or the extension is present but the cA boolean is not
926 // asserted, then the certified public key MUST NOT be used to verify
927 // certificate signatures."
928 // (except for Entrust, see comment above entrustBrokenSPKI)
929 if (parent.Version == 3 && !parent.BasicConstraintsValid ||
930 parent.BasicConstraintsValid && !parent.IsCA) &&
931 !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
932 return ConstraintViolationError{}
935 if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
936 return ConstraintViolationError{}
939 if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
940 return ErrUnsupportedAlgorithm
943 // TODO(agl): don't ignore the path length constraint.
945 return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
948 // CheckSignature verifies that signature is a valid signature over signed from
950 func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) error {
951 return checkSignature(algo, signed, signature, c.PublicKey)
954 // CheckSignature verifies that signature is a valid signature over signed from
955 // a crypto.PublicKey.
956 func checkSignature(algo SignatureAlgorithm, signed, signature []byte, publicKey crypto.PublicKey) (err error) {
960 case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1, SM2WithSHA1:
962 case SHA256WithRSA, SHA256WithRSAPSS, DSAWithSHA256, ECDSAWithSHA256, SM2WithSHA256:
964 case SHA384WithRSA, SHA384WithRSAPSS, ECDSAWithSHA384:
966 case SHA512WithRSA, SHA512WithRSAPSS, ECDSAWithSHA512:
968 case MD2WithRSA, MD5WithRSA:
969 return InsecureAlgorithmError(algo)
970 case SM2WithSM3: // SM3WithRSA reserve
973 return ErrUnsupportedAlgorithm
976 if !hashType.Available() {
977 return ErrUnsupportedAlgorithm
984 switch pub := publicKey.(type) {
987 return rsa.VerifyPSS(pub, crypto.Hash(hashType), digest, signature, &rsa.PSSOptions{SaltLength: rsa.PSSSaltLengthEqualsHash})
989 return rsa.VerifyPKCS1v15(pub, crypto.Hash(hashType), digest, signature)
992 dsaSig := new(dsaSignature)
993 if rest, err := asn1.Unmarshal(signature, dsaSig); err != nil {
995 } else if len(rest) != 0 {
996 return errors.New("x509: trailing data after DSA signature")
998 if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
999 return errors.New("x509: DSA signature contained zero or negative values")
1001 if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
1002 return errors.New("x509: DSA verification failure")
1005 case *ecdsa.PublicKey:
1006 ecdsaSig := new(ecdsaSignature)
1007 if rest, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
1009 } else if len(rest) != 0 {
1010 return errors.New("x509: trailing data after ECDSA signature")
1012 if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
1013 return errors.New("x509: ECDSA signature contained zero or negative values")
1017 if !Verify(&PublicKey{
1021 }, digest, ecdsaSig.R, ecdsaSig.S) {
1022 return errors.New("x509: SM2 verification failure")
1025 if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
1026 return errors.New("x509: ECDSA verification failure")
1031 return ErrUnsupportedAlgorithm
1034 // CheckCRLSignature checks that the signature in crl is from c.
1035 func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) error {
1036 algo := getSignatureAlgorithmFromAI(crl.SignatureAlgorithm)
1037 return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
1040 type UnhandledCriticalExtension struct{}
1042 func (h UnhandledCriticalExtension) Error() string {
1043 return "x509: unhandled critical extension"
1046 type basicConstraints struct {
1047 IsCA bool `asn1:"optional"`
1048 MaxPathLen int `asn1:"optional,default:-1"`
1052 type policyInformation struct {
1053 Policy asn1.ObjectIdentifier
1054 // policyQualifiers omitted
1057 // RFC 5280, 4.2.1.10
1058 type nameConstraints struct {
1059 Permitted []generalSubtree `asn1:"optional,tag:0"`
1060 Excluded []generalSubtree `asn1:"optional,tag:1"`
1063 type generalSubtree struct {
1064 Name string `asn1:"tag:2,optional,ia5"`
1067 // RFC 5280, 4.2.2.1
1068 type authorityInfoAccess struct {
1069 Method asn1.ObjectIdentifier
1070 Location asn1.RawValue
1073 // RFC 5280, 4.2.1.14
1074 type distributionPoint struct {
1075 DistributionPoint distributionPointName `asn1:"optional,tag:0"`
1076 Reason asn1.BitString `asn1:"optional,tag:1"`
1077 CRLIssuer asn1.RawValue `asn1:"optional,tag:2"`
1080 type distributionPointName struct {
1081 FullName asn1.RawValue `asn1:"optional,tag:0"`
1082 RelativeName pkix.RDNSequence `asn1:"optional,tag:1"`
1085 // asn1Null is the ASN.1 encoding of a NULL value.
1086 var asn1Null = []byte{5, 0}
1088 func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
1089 asn1Data := keyData.PublicKey.RightAlign()
1092 // RSA public keys must have a NULL in the parameters
1093 // (https://tools.ietf.org/html/rfc3279#section-2.3.1).
1094 if !bytes.Equal(keyData.Algorithm.Parameters.FullBytes, asn1Null) {
1095 return nil, errors.New("x509: RSA key missing NULL parameters")
1098 p := new(rsaPublicKey)
1099 rest, err := asn1.Unmarshal(asn1Data, p)
1104 return nil, errors.New("x509: trailing data after RSA public key")
1107 if p.N.Sign() <= 0 {
1108 return nil, errors.New("x509: RSA modulus is not a positive number")
1111 return nil, errors.New("x509: RSA public exponent is not a positive number")
1114 pub := &rsa.PublicKey{
1121 rest, err := asn1.Unmarshal(asn1Data, &p)
1126 return nil, errors.New("x509: trailing data after DSA public key")
1128 paramsData := keyData.Algorithm.Parameters.FullBytes
1129 params := new(dsaAlgorithmParameters)
1130 rest, err = asn1.Unmarshal(paramsData, params)
1135 return nil, errors.New("x509: trailing data after DSA parameters")
1137 if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
1138 return nil, errors.New("x509: zero or negative DSA parameter")
1140 pub := &dsa.PublicKey{
1141 Parameters: dsa.Parameters{
1150 paramsData := keyData.Algorithm.Parameters.FullBytes
1151 namedCurveOID := new(asn1.ObjectIdentifier)
1152 rest, err := asn1.Unmarshal(paramsData, namedCurveOID)
1157 return nil, errors.New("x509: trailing data after ECDSA parameters")
1159 namedCurve := namedCurveFromOID(*namedCurveOID)
1160 if namedCurve == nil {
1161 return nil, errors.New("x509: unsupported elliptic curve")
1163 x, y := elliptic.Unmarshal(namedCurve, asn1Data)
1165 return nil, errors.New("x509: failed to unmarshal elliptic curve point")
1167 pub := &ecdsa.PublicKey{
1178 func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, err error) {
1179 // RFC 5280, 4.2.1.6
1181 // SubjectAltName ::= GeneralNames
1183 // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
1185 // GeneralName ::= CHOICE {
1186 // otherName [0] OtherName,
1187 // rfc822Name [1] IA5String,
1188 // dNSName [2] IA5String,
1189 // x400Address [3] ORAddress,
1190 // directoryName [4] Name,
1191 // ediPartyName [5] EDIPartyName,
1192 // uniformResourceIdentifier [6] IA5String,
1193 // iPAddress [7] OCTET STRING,
1194 // registeredID [8] OBJECT IDENTIFIER }
1195 var seq asn1.RawValue
1197 if rest, err = asn1.Unmarshal(value, &seq); err != nil {
1199 } else if len(rest) != 0 {
1200 err = errors.New("x509: trailing data after X.509 extension")
1203 if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
1204 err = asn1.StructuralError{Msg: "bad SAN sequence"}
1211 rest, err = asn1.Unmarshal(rest, &v)
1217 emailAddresses = append(emailAddresses, string(v.Bytes))
1219 dnsNames = append(dnsNames, string(v.Bytes))
1221 switch len(v.Bytes) {
1222 case net.IPv4len, net.IPv6len:
1223 ipAddresses = append(ipAddresses, v.Bytes)
1225 err = errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes)))
1234 func parseCertificate(in *certificate) (*Certificate, error) {
1235 out := new(Certificate)
1237 out.RawTBSCertificate = in.TBSCertificate.Raw
1238 out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
1239 out.RawSubject = in.TBSCertificate.Subject.FullBytes
1240 out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
1242 out.Signature = in.SignatureValue.RightAlign()
1243 out.SignatureAlgorithm =
1244 getSignatureAlgorithmFromAI(in.TBSCertificate.SignatureAlgorithm)
1246 out.PublicKeyAlgorithm =
1247 getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
1249 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
1254 out.Version = in.TBSCertificate.Version + 1
1255 out.SerialNumber = in.TBSCertificate.SerialNumber
1257 var issuer, subject pkix.RDNSequence
1258 if rest, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
1260 } else if len(rest) != 0 {
1261 return nil, errors.New("x509: trailing data after X.509 subject")
1263 if rest, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
1265 } else if len(rest) != 0 {
1266 return nil, errors.New("x509: trailing data after X.509 subject")
1269 out.Issuer.FillFromRDNSequence(&issuer)
1270 out.Subject.FillFromRDNSequence(&subject)
1272 out.NotBefore = in.TBSCertificate.Validity.NotBefore
1273 out.NotAfter = in.TBSCertificate.Validity.NotAfter
1275 for _, e := range in.TBSCertificate.Extensions {
1276 out.Extensions = append(out.Extensions, e)
1279 if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
1282 // RFC 5280, 4.2.1.3
1283 var usageBits asn1.BitString
1284 if rest, err := asn1.Unmarshal(e.Value, &usageBits); err != nil {
1286 } else if len(rest) != 0 {
1287 return nil, errors.New("x509: trailing data after X.509 KeyUsage")
1291 for i := 0; i < 9; i++ {
1292 if usageBits.At(i) != 0 {
1293 usage |= 1 << uint(i)
1296 out.KeyUsage = KeyUsage(usage)
1299 // RFC 5280, 4.2.1.9
1300 var constraints basicConstraints
1301 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1303 } else if len(rest) != 0 {
1304 return nil, errors.New("x509: trailing data after X.509 BasicConstraints")
1307 out.BasicConstraintsValid = true
1308 out.IsCA = constraints.IsCA
1309 out.MaxPathLen = constraints.MaxPathLen
1310 out.MaxPathLenZero = out.MaxPathLen == 0
1313 out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(e.Value)
1318 if len(out.DNSNames) == 0 && len(out.EmailAddresses) == 0 && len(out.IPAddresses) == 0 {
1319 // If we didn't parse anything then we do the critical check, below.
1324 // RFC 5280, 4.2.1.10
1326 // NameConstraints ::= SEQUENCE {
1327 // permittedSubtrees [0] GeneralSubtrees OPTIONAL,
1328 // excludedSubtrees [1] GeneralSubtrees OPTIONAL }
1330 // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
1332 // GeneralSubtree ::= SEQUENCE {
1333 // base GeneralName,
1334 // minimum [0] BaseDistance DEFAULT 0,
1335 // maximum [1] BaseDistance OPTIONAL }
1337 // BaseDistance ::= INTEGER (0..MAX)
1339 var constraints nameConstraints
1340 if rest, err := asn1.Unmarshal(e.Value, &constraints); err != nil {
1342 } else if len(rest) != 0 {
1343 return nil, errors.New("x509: trailing data after X.509 NameConstraints")
1346 if len(constraints.Excluded) > 0 && e.Critical {
1347 return out, UnhandledCriticalExtension{}
1350 for _, subtree := range constraints.Permitted {
1351 if len(subtree.Name) == 0 {
1353 return out, UnhandledCriticalExtension{}
1357 out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
1361 // RFC 5280, 4.2.1.13
1363 // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint
1365 // DistributionPoint ::= SEQUENCE {
1366 // distributionPoint [0] DistributionPointName OPTIONAL,
1367 // reasons [1] ReasonFlags OPTIONAL,
1368 // cRLIssuer [2] GeneralNames OPTIONAL }
1370 // DistributionPointName ::= CHOICE {
1371 // fullName [0] GeneralNames,
1372 // nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
1374 var cdp []distributionPoint
1375 if rest, err := asn1.Unmarshal(e.Value, &cdp); err != nil {
1377 } else if len(rest) != 0 {
1378 return nil, errors.New("x509: trailing data after X.509 CRL distribution point")
1381 for i := range cdp {
1382 // use index & pointer here to avoid value copy (each iteration copies 200 bytes)
1384 // Per RFC 5280, 4.2.1.13, one of distributionPoint or cRLIssuer may be empty.
1385 if len(dp.DistributionPoint.FullName.Bytes) == 0 {
1390 if _, err := asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n); err != nil {
1393 // Trailing data after the fullName is
1394 // allowed because other elements of
1395 // the SEQUENCE can appear.
1398 out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes))
1403 // RFC 5280, 4.2.1.1
1405 if rest, err := asn1.Unmarshal(e.Value, &a); err != nil {
1407 } else if len(rest) != 0 {
1408 return nil, errors.New("x509: trailing data after X.509 authority key-id")
1410 out.AuthorityKeyId = a.Id
1413 // RFC 5280, 4.2.1.12. Extended Key Usage
1415 // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
1417 // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
1419 // KeyPurposeId ::= OBJECT IDENTIFIER
1421 var keyUsage []asn1.ObjectIdentifier
1422 if rest, err := asn1.Unmarshal(e.Value, &keyUsage); err != nil {
1424 } else if len(rest) != 0 {
1425 return nil, errors.New("x509: trailing data after X.509 ExtendedKeyUsage")
1428 for _, u := range keyUsage {
1429 if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
1430 out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
1432 out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
1437 // RFC 5280, 4.2.1.2
1439 if rest, err := asn1.Unmarshal(e.Value, &keyid); err != nil {
1441 } else if len(rest) != 0 {
1442 return nil, errors.New("x509: trailing data after X.509 key-id")
1444 out.SubjectKeyId = keyid
1447 // RFC 5280 4.2.1.4: Certificate Policies
1448 var policies []policyInformation
1449 if rest, err := asn1.Unmarshal(e.Value, &policies); err != nil {
1451 } else if len(rest) != 0 {
1452 return nil, errors.New("x509: trailing data after X.509 certificate policies")
1454 out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
1455 for i, policy := range policies {
1456 out.PolicyIdentifiers[i] = policy.Policy
1460 // Unknown extensions are recorded if critical.
1463 } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) {
1464 // RFC 5280 4.2.2.1: Authority Information Access
1465 var aia []authorityInfoAccess
1466 if rest, err := asn1.Unmarshal(e.Value, &aia); err != nil {
1468 } else if len(rest) != 0 {
1469 return nil, errors.New("x509: trailing data after X.509 authority information")
1472 for _, v := range aia {
1473 // GeneralName: uniformResourceIdentifier [6] IA5String
1474 if v.Location.Tag != 6 {
1477 if v.Method.Equal(oidAuthorityInfoAccessOcsp) {
1478 out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes))
1479 } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) {
1480 out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes))
1484 // Unknown extensions are recorded if critical.
1488 if e.Critical && unhandled {
1489 out.UnhandledCriticalExtensions = append(out.UnhandledCriticalExtensions, e.Id)
1496 // ParseCertificate parses a single certificate from the given ASN.1 DER data.
1497 func ParseCertificate(asn1Data []byte) (*Certificate, error) {
1498 var cert certificate
1499 rest, err := asn1.Unmarshal(asn1Data, &cert)
1504 return nil, asn1.SyntaxError{Msg: "trailing data"}
1507 return parseCertificate(&cert)
1510 // ParseCertificates parses one or more certificates from the given ASN.1 DER
1511 // data. The certificates must be concatenated with no intermediate padding.
1512 func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
1513 var v []*certificate
1515 for len(asn1Data) > 0 {
1516 cert := new(certificate)
1518 asn1Data, err = asn1.Unmarshal(asn1Data, cert)
1525 ret := make([]*Certificate, len(v))
1526 for i, ci := range v {
1527 cert, err := parseCertificate(ci)
1537 func reverseBitsInAByte(in byte) byte {
1539 b2 := b1>>2&0x33 | b1<<2&0xcc
1540 b3 := b2>>1&0x55 | b2<<1&0xaa
1544 // asn1BitLength returns the bit-length of bitString by considering the
1545 // most-significant bit in a byte to be the "first" bit. This convention
1546 // matches ASN.1, but differs from almost everything else.
1547 func asn1BitLength(bitString []byte) int {
1548 bitLen := len(bitString) * 8
1550 for i := range bitString {
1551 b := bitString[len(bitString)-i-1]
1553 for bit := uint(0); bit < 8; bit++ {
1554 if (b>>bit)&1 == 1 {
1565 oidExtensionSubjectKeyId = []int{2, 5, 29, 14}
1566 oidExtensionKeyUsage = []int{2, 5, 29, 15}
1567 oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37}
1568 oidExtensionAuthorityKeyId = []int{2, 5, 29, 35}
1569 oidExtensionBasicConstraints = []int{2, 5, 29, 19}
1570 oidExtensionSubjectAltName = []int{2, 5, 29, 17}
1571 oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
1572 oidExtensionNameConstraints = []int{2, 5, 29, 30}
1573 oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31}
1574 oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1}
1578 oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1}
1579 oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2}
1582 // oidNotInExtensions returns whether an extension with the given oid exists in
1584 func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool {
1585 for _, e := range extensions {
1586 if e.Id.Equal(oid) {
1593 // marshalSANs marshals a list of addresses into a the contents of an X.509
1594 // SubjectAlternativeName extension.
1595 func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) {
1596 var rawValues []asn1.RawValue
1597 for _, name := range dnsNames {
1598 rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
1600 for _, email := range emailAddresses {
1601 rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
1603 for _, rawIP := range ipAddresses {
1604 // If possible, we always want to encode IPv4 addresses in 4 bytes.
1609 rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
1611 return asn1.Marshal(rawValues)
1614 func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
1615 ret = make([]pkix.Extension, 10 /* maximum number of elements. */)
1618 if template.KeyUsage != 0 &&
1619 !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) {
1620 ret[n].Id = oidExtensionKeyUsage
1621 ret[n].Critical = true
1624 a[0] = reverseBitsInAByte(byte(template.KeyUsage))
1625 a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
1633 ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: bitString, BitLength: asn1BitLength(bitString)})
1640 if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) &&
1641 !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) {
1642 ret[n].Id = oidExtensionExtendedKeyUsage
1644 var oids []asn1.ObjectIdentifier
1645 for _, u := range template.ExtKeyUsage {
1646 if oid, ok := oidFromExtKeyUsage(u); ok {
1647 oids = append(oids, oid)
1649 panic("internal error")
1653 oids = append(oids, template.UnknownExtKeyUsage...)
1655 ret[n].Value, err = asn1.Marshal(oids)
1662 if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) {
1663 // Leaving MaxPathLen as zero indicates that no maximum path
1664 // length is desired, unless MaxPathLenZero is set. A value of
1665 // -1 causes encoding/asn1 to omit the value as desired.
1666 maxPathLen := template.MaxPathLen
1667 if maxPathLen == 0 && !template.MaxPathLenZero {
1670 ret[n].Id = oidExtensionBasicConstraints
1671 ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, maxPathLen})
1672 ret[n].Critical = true
1679 if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) {
1680 ret[n].Id = oidExtensionSubjectKeyId
1681 ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
1688 if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) {
1689 ret[n].Id = oidExtensionAuthorityKeyId
1690 ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
1697 if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) &&
1698 !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) {
1699 ret[n].Id = oidExtensionAuthorityInfoAccess
1700 var aiaValues []authorityInfoAccess
1701 for _, name := range template.OCSPServer {
1702 aiaValues = append(aiaValues, authorityInfoAccess{
1703 Method: oidAuthorityInfoAccessOcsp,
1704 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1707 for _, name := range template.IssuingCertificateURL {
1708 aiaValues = append(aiaValues, authorityInfoAccess{
1709 Method: oidAuthorityInfoAccessIssuers,
1710 Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)},
1713 ret[n].Value, err = asn1.Marshal(aiaValues)
1720 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
1721 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
1722 ret[n].Id = oidExtensionSubjectAltName
1723 ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses)
1730 if len(template.PolicyIdentifiers) > 0 &&
1731 !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) {
1732 ret[n].Id = oidExtensionCertificatePolicies
1733 policies := make([]policyInformation, len(template.PolicyIdentifiers))
1734 for i, policy := range template.PolicyIdentifiers {
1735 policies[i].Policy = policy
1737 ret[n].Value, err = asn1.Marshal(policies)
1744 if len(template.PermittedDNSDomains) > 0 &&
1745 !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) {
1746 ret[n].Id = oidExtensionNameConstraints
1747 ret[n].Critical = template.PermittedDNSDomainsCritical
1749 var out nameConstraints
1750 out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
1751 for i, permitted := range template.PermittedDNSDomains {
1752 out.Permitted[i] = generalSubtree{Name: permitted}
1754 ret[n].Value, err = asn1.Marshal(out)
1761 if len(template.CRLDistributionPoints) > 0 &&
1762 !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) {
1763 ret[n].Id = oidExtensionCRLDistributionPoints
1765 var crlDp []distributionPoint
1766 for _, name := range template.CRLDistributionPoints {
1767 rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)})
1769 dp := distributionPoint{
1770 DistributionPoint: distributionPointName{
1771 FullName: asn1.RawValue{Tag: 0, Class: 2, IsCompound: true, Bytes: rawFullName},
1774 crlDp = append(crlDp, dp)
1777 ret[n].Value, err = asn1.Marshal(crlDp)
1784 // Adding another extension here? Remember to update the maximum number
1785 // of elements in the make() at the top of the function.
1787 return append(ret[:n], template.ExtraExtensions...), nil
1790 func subjectBytes(cert *Certificate) ([]byte, error) {
1791 if len(cert.RawSubject) > 0 {
1792 return cert.RawSubject, nil
1795 return asn1.Marshal(cert.Subject.ToRDNSequence())
1798 // signingParamsForPublicKey returns the parameters to use for signing with
1799 // priv. If requestedSigAlgo is not zero then it overrides the default
1800 // signature algorithm.
1801 func signingParamsForPublicKey(pub interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
1802 var pubType PublicKeyAlgorithm
1804 switch pub := pub.(type) {
1805 case *rsa.PublicKey:
1808 sigAlgo.Algorithm = oidSignatureSHA256WithRSA
1809 sigAlgo.Parameters = asn1.RawValue{
1813 case *ecdsa.PublicKey:
1816 case elliptic.P224(), elliptic.P256():
1818 sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
1819 case elliptic.P384():
1821 sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
1822 case elliptic.P521():
1824 sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
1826 err = errors.New("x509: unknown elliptic curve")
1833 sigAlgo.Algorithm = oidSignatureSM2WithSM3
1835 err = errors.New("x509: unknown SM2 curve")
1838 err = errors.New("x509: only RSA and ECDSA keys supported")
1845 if requestedSigAlgo == 0 {
1850 for _, details := range signatureAlgorithmDetails {
1851 if details.algo == requestedSigAlgo {
1852 if details.pubKeyAlgo != pubType {
1853 err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
1856 sigAlgo.Algorithm, hashFunc = details.oid, details.hash
1858 err = errors.New("x509: cannot sign with hash function requested")
1861 if requestedSigAlgo.isRSAPSS() {
1862 sigAlgo.Parameters = rsaPSSParameters(hashFunc)
1870 err = errors.New("x509: unknown SignatureAlgorithm")
1876 // CreateCertificate creates a new certificate based on a template. The
1877 // following members of template are used: SerialNumber, Subject, NotBefore,
1878 // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
1879 // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
1880 // PermittedDNSDomains, SignatureAlgorithm.
1882 // The certificate is signed by parent. If parent is equal to template then the
1883 // certificate is self-signed. The parameter pub is the public key of the
1884 // signee and priv is the private key of the signer.
1886 // The returned slice is the certificate in DER encoding.
1888 // All keys types that are implemented via crypto.Signer are supported (This
1889 // includes *rsa.PublicKey and *ecdsa.PublicKey.)
1890 func CreateCertificate(rand io.Reader, template, parent *Certificate, pub, priv interface{}) (cert []byte, err error) {
1891 key, ok := priv.(crypto.Signer)
1893 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
1896 if template.SerialNumber == nil {
1897 return nil, errors.New("x509: no SerialNumber given")
1900 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
1905 publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub)
1910 asn1Issuer, err := subjectBytes(parent)
1915 asn1Subject, err := subjectBytes(template)
1920 if !bytes.Equal(asn1Issuer, asn1Subject) && len(parent.SubjectKeyId) > 0 {
1921 template.AuthorityKeyId = parent.SubjectKeyId
1924 extensions, err := buildExtensions(template)
1928 encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
1929 c := tbsCertificate{
1931 SerialNumber: template.SerialNumber,
1932 SignatureAlgorithm: signatureAlgorithm,
1933 Issuer: asn1.RawValue{FullBytes: asn1Issuer},
1934 Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
1935 Subject: asn1.RawValue{FullBytes: asn1Subject},
1936 PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
1937 Extensions: extensions,
1940 tbsCertContents, err := asn1.Marshal(c)
1945 c.Raw = tbsCertContents
1948 h.Write(tbsCertContents)
1949 digest := h.Sum(nil)
1951 var signerOpts crypto.SignerOpts
1952 signerOpts = hashFunc
1953 if template.SignatureAlgorithm != 0 && template.SignatureAlgorithm.isRSAPSS() {
1954 signerOpts = &rsa.PSSOptions{
1955 SaltLength: rsa.PSSSaltLengthEqualsHash,
1956 Hash: crypto.Hash(hashFunc),
1960 var signature []byte
1961 signature, err = key.Sign(rand, digest, signerOpts)
1966 return asn1.Marshal(certificate{
1970 asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
1974 // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
1976 var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
1978 // pemType is the type of a PEM encoded CRL.
1979 var pemType = "X509 CRL"
1981 // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
1982 // encoded CRLs will appear where they should be DER encoded, so this function
1983 // will transparently handle PEM encoding as long as there isn't any leading
1985 func ParseCRL(crlBytes []byte) (*pkix.CertificateList, error) {
1986 if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
1987 block, _ := pem.Decode(crlBytes)
1988 if block != nil && block.Type == pemType {
1989 crlBytes = block.Bytes
1992 return ParseDERCRL(crlBytes)
1995 // ParseDERCRL parses a DER encoded CRL from the given bytes.
1996 func ParseDERCRL(derBytes []byte) (*pkix.CertificateList, error) {
1997 certList := new(pkix.CertificateList)
1998 if rest, err := asn1.Unmarshal(derBytes, certList); err != nil {
2000 } else if len(rest) != 0 {
2001 return nil, errors.New("x509: trailing data after CRL")
2003 return certList, nil
2006 // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
2007 // contains the given list of revoked certificates.
2008 func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
2009 key, ok := priv.(crypto.Signer)
2011 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2014 hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(key.Public(), 0)
2019 // Force revocation times to UTC per RFC 5280.
2020 revokedCertsUTC := make([]pkix.RevokedCertificate, len(revokedCerts))
2021 for i, rc := range revokedCerts {
2022 rc.RevocationTime = rc.RevocationTime.UTC()
2023 revokedCertsUTC[i] = rc
2026 tbsCertList := pkix.TBSCertificateList{
2028 Signature: signatureAlgorithm,
2029 Issuer: c.Subject.ToRDNSequence(),
2030 ThisUpdate: now.UTC(),
2031 NextUpdate: expiry.UTC(),
2032 RevokedCertificates: revokedCertsUTC,
2036 if len(c.SubjectKeyId) > 0 {
2037 var aki pkix.Extension
2038 aki.Id = oidExtensionAuthorityKeyId
2039 aki.Value, err = asn1.Marshal(authKeyId{Id: c.SubjectKeyId})
2043 tbsCertList.Extensions = append(tbsCertList.Extensions, aki)
2046 tbsCertListContents, err := asn1.Marshal(tbsCertList)
2052 h.Write(tbsCertListContents)
2053 digest := h.Sum(nil)
2055 var signature []byte
2056 signature, err = key.Sign(rand, digest, hashFunc)
2061 return asn1.Marshal(pkix.CertificateList{
2062 TBSCertList: tbsCertList,
2063 SignatureAlgorithm: signatureAlgorithm,
2064 SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
2068 // CertificateRequest represents a PKCS #10, certificate signature request.
2069 type CertificateRequest struct {
2070 Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature).
2071 RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content.
2072 RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
2073 RawSubject []byte // DER encoded Subject.
2077 SignatureAlgorithm SignatureAlgorithm
2079 PublicKeyAlgorithm PublicKeyAlgorithm
2080 PublicKey interface{}
2084 // Attributes is the dried husk of a bug and shouldn't be used.
2085 Attributes []pkix.AttributeTypeAndValueSET
2087 // Extensions contains raw X.509 extensions. When parsing CSRs, this
2088 // can be used to extract extensions that are not parsed by this
2090 Extensions []pkix.Extension
2092 // ExtraExtensions contains extensions to be copied, raw, into any
2093 // marshaled CSR. Values override any extensions that would otherwise
2094 // be produced based on the other fields but are overridden by any
2095 // extensions specified in Attributes.
2097 // The ExtraExtensions field is not populated when parsing CSRs, see
2099 ExtraExtensions []pkix.Extension
2101 // Subject Alternate Name values.
2103 EmailAddresses []string
2104 IPAddresses []net.IP
2107 // These structures reflect the ASN.1 structure of X.509 certificate
2108 // signature requests (see RFC 2986):
2110 type tbsCertificateRequest struct {
2113 Subject asn1.RawValue
2114 PublicKey publicKeyInfo
2115 RawAttributes []asn1.RawValue `asn1:"tag:0"`
2118 type certificateRequest struct {
2120 TBSCSR tbsCertificateRequest
2121 SignatureAlgorithm pkix.AlgorithmIdentifier
2122 SignatureValue asn1.BitString
2125 // oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested
2126 // extensions in a CSR.
2127 var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14}
2129 // newRawAttributes converts AttributeTypeAndValueSETs from a template
2130 // CertificateRequest's Attributes into tbsCertificateRequest RawAttributes.
2131 func newRawAttributes(attributes []pkix.AttributeTypeAndValueSET) ([]asn1.RawValue, error) {
2132 var rawAttributes []asn1.RawValue
2133 b, err := asn1.Marshal(attributes)
2137 rest, err := asn1.Unmarshal(b, &rawAttributes)
2142 return nil, errors.New("x509: failed to unmarshal raw CSR Attributes")
2144 return rawAttributes, nil
2147 // parseRawAttributes Unmarshals RawAttributes intos AttributeTypeAndValueSETs.
2148 func parseRawAttributes(rawAttributes []asn1.RawValue) []pkix.AttributeTypeAndValueSET {
2149 var attributes []pkix.AttributeTypeAndValueSET
2150 for _, rawAttr := range rawAttributes {
2151 var attr pkix.AttributeTypeAndValueSET
2152 rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr)
2153 // Ignore attributes that don't parse into pkix.AttributeTypeAndValueSET
2154 // (i.e.: challengePassword or unstructuredName).
2155 if err == nil && len(rest) == 0 {
2156 attributes = append(attributes, attr)
2162 // parseCSRExtensions parses the attributes from a CSR and extracts any
2163 // requested extensions.
2164 func parseCSRExtensions(rawAttributes []asn1.RawValue) ([]pkix.Extension, error) {
2165 // pkcs10Attribute reflects the Attribute structure from section 4.1 of
2166 // https://tools.ietf.org/html/rfc2986.
2167 type pkcs10Attribute struct {
2168 Id asn1.ObjectIdentifier
2169 Values []asn1.RawValue `asn1:"set"`
2172 var ret []pkix.Extension
2173 for _, rawAttr := range rawAttributes {
2174 var attr pkcs10Attribute
2175 if rest, err := asn1.Unmarshal(rawAttr.FullBytes, &attr); err != nil || len(rest) != 0 || len(attr.Values) == 0 {
2176 // Ignore attributes that don't parse.
2180 if !attr.Id.Equal(oidExtensionRequest) {
2184 var extensions []pkix.Extension
2185 if _, err := asn1.Unmarshal(attr.Values[0].FullBytes, &extensions); err != nil {
2188 ret = append(ret, extensions...)
2194 // CreateCertificateRequest creates a new certificate request based on a template.
2195 // The following members of template are used: Subject, Attributes,
2196 // SignatureAlgorithm, Extensions, DNSNames, EmailAddresses, and IPAddresses.
2197 // The private key is the private key of the signer.
2199 // The returned slice is the certificate request in DER encoding.
2201 // All keys types that are implemented via crypto.Signer are supported (This
2202 // includes *rsa.PublicKey and *ecdsa.PublicKey.)
2203 func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) {
2204 key, ok := priv.(crypto.Signer)
2206 return nil, errors.New("x509: certificate private key does not implement crypto.Signer")
2210 var sigAlgo pkix.AlgorithmIdentifier
2211 hashFunc, sigAlgo, err = signingParamsForPublicKey(key.Public(), template.SignatureAlgorithm)
2216 var publicKeyBytes []byte
2217 var publicKeyAlgorithm pkix.AlgorithmIdentifier
2218 publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(key.Public())
2223 var extensions []pkix.Extension
2225 if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) &&
2226 !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) {
2227 sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses)
2232 extensions = append(extensions, pkix.Extension{
2233 Id: oidExtensionSubjectAltName,
2238 extensions = append(extensions, template.ExtraExtensions...)
2240 var attributes []pkix.AttributeTypeAndValueSET
2241 attributes = append(attributes, template.Attributes...)
2243 if len(extensions) > 0 {
2244 // specifiedExtensions contains all the extensions that we
2245 // found specified via template.Attributes.
2246 specifiedExtensions := make(map[string]bool)
2248 for _, atvSet := range template.Attributes {
2249 if !atvSet.Type.Equal(oidExtensionRequest) {
2253 for _, atvs := range atvSet.Value {
2254 for _, atv := range atvs {
2255 specifiedExtensions[atv.Type.String()] = true
2260 atvs := make([]pkix.AttributeTypeAndValue, 0, len(extensions))
2261 for _, e := range extensions {
2262 if specifiedExtensions[e.Id.String()] {
2263 // Attributes already contained a value for
2264 // this extension and it takes priority.
2268 atvs = append(atvs, pkix.AttributeTypeAndValue{
2269 // There is no place for the critical flag in a CSR.
2275 // Append the extensions to an existing attribute if possible.
2277 for _, atvSet := range attributes {
2278 if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 {
2282 atvSet.Value[0] = append(atvSet.Value[0], atvs...)
2287 // Otherwise, add a new attribute for the extensions.
2289 attributes = append(attributes, pkix.AttributeTypeAndValueSET{
2290 Type: oidExtensionRequest,
2291 Value: [][]pkix.AttributeTypeAndValue{
2298 asn1Subject := template.RawSubject
2299 if len(asn1Subject) == 0 {
2300 asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence())
2306 rawAttributes, err := newRawAttributes(attributes)
2311 tbsCSR := tbsCertificateRequest{
2312 Version: 0, // PKCS #10, RFC 2986
2313 Subject: asn1.RawValue{FullBytes: asn1Subject},
2314 PublicKey: publicKeyInfo{
2315 Algorithm: publicKeyAlgorithm,
2316 PublicKey: asn1.BitString{
2317 Bytes: publicKeyBytes,
2318 BitLength: len(publicKeyBytes) * 8,
2321 RawAttributes: rawAttributes,
2324 tbsCSRContents, err := asn1.Marshal(tbsCSR)
2328 tbsCSR.Raw = tbsCSRContents
2331 h.Write(tbsCSRContents)
2332 digest := h.Sum(nil)
2334 var signature []byte
2335 signature, err = key.Sign(rand, digest, hashFunc)
2340 return asn1.Marshal(certificateRequest{
2342 SignatureAlgorithm: sigAlgo,
2343 SignatureValue: asn1.BitString{
2345 BitLength: len(signature) * 8,
2350 // ParseCertificateRequest parses a single certificate request from the
2351 // given ASN.1 DER data.
2352 func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) {
2353 var csr certificateRequest
2355 rest, err := asn1.Unmarshal(asn1Data, &csr)
2358 } else if len(rest) != 0 {
2359 return nil, asn1.SyntaxError{Msg: "trailing data"}
2362 return parseCertificateRequest(&csr)
2365 func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) {
2366 out := &CertificateRequest{
2368 RawTBSCertificateRequest: in.TBSCSR.Raw,
2369 RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw,
2370 RawSubject: in.TBSCSR.Subject.FullBytes,
2372 Signature: in.SignatureValue.RightAlign(),
2373 SignatureAlgorithm: getSignatureAlgorithmFromAI(in.SignatureAlgorithm),
2375 PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm),
2377 Version: in.TBSCSR.Version,
2378 Attributes: parseRawAttributes(in.TBSCSR.RawAttributes),
2382 out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey)
2387 var subject pkix.RDNSequence
2388 if rest, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil {
2390 } else if len(rest) != 0 {
2391 return nil, errors.New("x509: trailing data after X.509 Subject")
2394 out.Subject.FillFromRDNSequence(&subject)
2396 if out.Extensions, err = parseCSRExtensions(in.TBSCSR.RawAttributes); err != nil {
2400 for _, extension := range out.Extensions {
2401 if extension.Id.Equal(oidExtensionSubjectAltName) {
2402 out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(extension.Value)
2412 // CheckSignature reports whether the signature on c is valid.
2413 func (c *CertificateRequest) CheckSignature() error {
2414 return checkSignature(c.SignatureAlgorithm, c.RawTBSCertificateRequest, c.Signature, c.PublicKey)
2417 func ReadCertificateRequestFromMem(data []byte) (*CertificateRequest, error) {
2418 block, _ := pem.Decode(data)
2420 return nil, errors.New("failed to decode certificate request")
2422 return ParseCertificateRequest(block.Bytes)
2425 func ReadCertificateRequestFromPem(FileName string) (*CertificateRequest, error) {
2426 data, err := ioutil.ReadFile(FileName)
2430 return ReadCertificateRequestFromMem(data)
2433 func CreateCertificateRequestToMem(template *CertificateRequest, privKey *PrivateKey) ([]byte, error) {
2434 der, err := CreateCertificateRequest(rand.Reader, template, privKey)
2438 block := &pem.Block{
2439 Type: "CERTIFICATE REQUEST",
2442 return pem.EncodeToMemory(block), nil
2445 func CreateCertificateRequestToPem(FileName string, template *CertificateRequest,
2446 privKey *PrivateKey) (bool, error) {
2447 der, err := CreateCertificateRequest(rand.Reader, template, privKey)
2451 block := &pem.Block{
2452 Type: "CERTIFICATE REQUEST",
2455 file, err := os.Create(FileName)
2460 err = pem.Encode(file, block)
2467 func ReadCertificateFromMem(data []byte) (*Certificate, error) {
2468 block, _ := pem.Decode(data)
2470 return nil, errors.New("failed to decode certificate request")
2472 return ParseCertificate(block.Bytes)
2475 func ReadCertificateFromPem(FileName string) (*Certificate, error) {
2476 data, err := ioutil.ReadFile(FileName)
2480 return ReadCertificateFromMem(data)
2483 func CreateCertificateToMem(template, parent *Certificate, pubKey *PublicKey, privKey *PrivateKey) ([]byte, error) {
2484 der, err := CreateCertificate(rand.Reader, template, parent, pubKey, privKey)
2488 block := &pem.Block{
2489 Type: "CERTIFICATE",
2492 return pem.EncodeToMemory(block), nil
2495 func CreateCertificateToPem(FileName string, template, parent *Certificate, pubKey *PublicKey, privKey *PrivateKey) (bool, error) {
2496 der, err := CreateCertificate(rand.Reader, template, parent, pubKey, privKey)
2500 block := &pem.Block{
2501 Type: "CERTIFICATE",
2504 file, err := os.Create(FileName)
2509 err = pem.Encode(file, block)