Home | History | Annotate | Download | only in x509
      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.
      4 
      5 package x509
      6 
      7 import (
      8 	"bytes"
      9 	"crypto/dsa"
     10 	"crypto/ecdsa"
     11 	"crypto/elliptic"
     12 	"crypto/rand"
     13 	"crypto/rsa"
     14 	_ "crypto/sha256"
     15 	_ "crypto/sha512"
     16 	"crypto/x509/pkix"
     17 	"encoding/asn1"
     18 	"encoding/base64"
     19 	"encoding/hex"
     20 	"encoding/pem"
     21 	"fmt"
     22 	"internal/testenv"
     23 	"math/big"
     24 	"net"
     25 	"os/exec"
     26 	"reflect"
     27 	"runtime"
     28 	"strings"
     29 	"testing"
     30 	"time"
     31 )
     32 
     33 func TestParsePKCS1PrivateKey(t *testing.T) {
     34 	block, _ := pem.Decode([]byte(pemPrivateKey))
     35 	priv, err := ParsePKCS1PrivateKey(block.Bytes)
     36 	if err != nil {
     37 		t.Errorf("Failed to parse private key: %s", err)
     38 		return
     39 	}
     40 	if priv.PublicKey.N.Cmp(rsaPrivateKey.PublicKey.N) != 0 ||
     41 		priv.PublicKey.E != rsaPrivateKey.PublicKey.E ||
     42 		priv.D.Cmp(rsaPrivateKey.D) != 0 ||
     43 		priv.Primes[0].Cmp(rsaPrivateKey.Primes[0]) != 0 ||
     44 		priv.Primes[1].Cmp(rsaPrivateKey.Primes[1]) != 0 {
     45 		t.Errorf("got:%+v want:%+v", priv, rsaPrivateKey)
     46 	}
     47 
     48 	// This private key includes an invalid prime that
     49 	// rsa.PrivateKey.Validate should reject.
     50 	data := []byte("0\x16\x02\x00\x02\x02\u007f\x00\x02\x0200\x02\x0200\x02\x02\x00\x01\x02\x02\u007f\x00")
     51 	if _, err := ParsePKCS1PrivateKey(data); err == nil {
     52 		t.Errorf("parsing invalid private key did not result in an error")
     53 	}
     54 }
     55 
     56 func TestParsePKIXPublicKey(t *testing.T) {
     57 	block, _ := pem.Decode([]byte(pemPublicKey))
     58 	pub, err := ParsePKIXPublicKey(block.Bytes)
     59 	if err != nil {
     60 		t.Errorf("Failed to parse RSA public key: %s", err)
     61 		return
     62 	}
     63 	rsaPub, ok := pub.(*rsa.PublicKey)
     64 	if !ok {
     65 		t.Errorf("Value returned from ParsePKIXPublicKey was not an RSA public key")
     66 		return
     67 	}
     68 
     69 	pubBytes2, err := MarshalPKIXPublicKey(rsaPub)
     70 	if err != nil {
     71 		t.Errorf("Failed to marshal RSA public key for the second time: %s", err)
     72 		return
     73 	}
     74 	if !bytes.Equal(pubBytes2, block.Bytes) {
     75 		t.Errorf("Reserialization of public key didn't match. got %x, want %x", pubBytes2, block.Bytes)
     76 	}
     77 }
     78 
     79 var pemPublicKey = `-----BEGIN PUBLIC KEY-----
     80 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3VoPN9PKUjKFLMwOge6+
     81 wnDi8sbETGIx2FKXGgqtAKpzmem53kRGEQg8WeqRmp12wgp74TGpkEXsGae7RS1k
     82 enJCnma4fii+noGH7R0qKgHvPrI2Bwa9hzsH8tHxpyM3qrXslOmD45EH9SxIDUBJ
     83 FehNdaPbLP1gFyahKMsdfxFJLUvbUycuZSJ2ZnIgeVxwm4qbSvZInL9Iu4FzuPtg
     84 fINKcbbovy1qq4KvPIrXzhbY3PWDc6btxCf3SE0JdE1MCPThntB62/bLMSQ7xdDR
     85 FF53oIpvxe/SCOymfWq/LW849Ytv3Xwod0+wzAP8STXG4HSELS4UedPYeHJJJYcZ
     86 +QIDAQAB
     87 -----END PUBLIC KEY-----
     88 `
     89 
     90 var pemPrivateKey = `
     91 -----BEGIN RSA PRIVATE KEY-----
     92 MIICXAIBAAKBgQCxoeCUW5KJxNPxMp+KmCxKLc1Zv9Ny+4CFqcUXVUYH69L3mQ7v
     93 IWrJ9GBfcaA7BPQqUlWxWM+OCEQZH1EZNIuqRMNQVuIGCbz5UQ8w6tS0gcgdeGX7
     94 J7jgCQ4RK3F/PuCM38QBLaHx988qG8NMc6VKErBjctCXFHQt14lerd5KpQIDAQAB
     95 AoGAYrf6Hbk+mT5AI33k2Jt1kcweodBP7UkExkPxeuQzRVe0KVJw0EkcFhywKpr1
     96 V5eLMrILWcJnpyHE5slWwtFHBG6a5fLaNtsBBtcAIfqTQ0Vfj5c6SzVaJv0Z5rOd
     97 7gQF6isy3t3w9IF3We9wXQKzT6q5ypPGdm6fciKQ8RnzREkCQQDZwppKATqQ41/R
     98 vhSj90fFifrGE6aVKC1hgSpxGQa4oIdsYYHwMzyhBmWW9Xv/R+fPyr8ZwPxp2c12
     99 33QwOLPLAkEA0NNUb+z4ebVVHyvSwF5jhfJxigim+s49KuzJ1+A2RaSApGyBZiwS
    100 rWvWkB471POAKUYt5ykIWVZ83zcceQiNTwJBAMJUFQZX5GDqWFc/zwGoKkeR49Yi
    101 MTXIvf7Wmv6E++eFcnT461FlGAUHRV+bQQXGsItR/opIG7mGogIkVXa3E1MCQARX
    102 AAA7eoZ9AEHflUeuLn9QJI/r0hyQQLEtrpwv6rDT1GCWaLII5HJ6NUFVf4TTcqxo
    103 6vdM4QGKTJoO+SaCyP0CQFdpcxSAuzpFcKv0IlJ8XzS/cy+mweCMwyJ1PFEc4FX6
    104 wg/HcAJWY60xZTJDFN+Qfx8ZQvBEin6c2/h+zZi5IVY=
    105 -----END RSA PRIVATE KEY-----
    106 `
    107 
    108 var testPrivateKey *rsa.PrivateKey
    109 
    110 func init() {
    111 	block, _ := pem.Decode([]byte(pemPrivateKey))
    112 
    113 	var err error
    114 	if testPrivateKey, err = ParsePKCS1PrivateKey(block.Bytes); err != nil {
    115 		panic("Failed to parse private key: " + err.Error())
    116 	}
    117 }
    118 
    119 func bigFromString(s string) *big.Int {
    120 	ret := new(big.Int)
    121 	ret.SetString(s, 10)
    122 	return ret
    123 }
    124 
    125 func fromBase10(base10 string) *big.Int {
    126 	i := new(big.Int)
    127 	i.SetString(base10, 10)
    128 	return i
    129 }
    130 
    131 func bigFromHexString(s string) *big.Int {
    132 	ret := new(big.Int)
    133 	ret.SetString(s, 16)
    134 	return ret
    135 }
    136 
    137 var rsaPrivateKey = &rsa.PrivateKey{
    138 	PublicKey: rsa.PublicKey{
    139 		N: bigFromString("124737666279038955318614287965056875799409043964547386061640914307192830334599556034328900586693254156136128122194531292927142396093148164407300419162827624945636708870992355233833321488652786796134504707628792159725681555822420087112284637501705261187690946267527866880072856272532711620639179596808018872997"),
    140 		E: 65537,
    141 	},
    142 	D: bigFromString("69322600686866301945688231018559005300304807960033948687567105312977055197015197977971637657636780793670599180105424702854759606794705928621125408040473426339714144598640466128488132656829419518221592374964225347786430566310906679585739468938549035854760501049443920822523780156843263434219450229353270690889"),
    143 	Primes: []*big.Int{
    144 		bigFromString("11405025354575369741595561190164746858706645478381139288033759331174478411254205003127028642766986913445391069745480057674348716675323735886284176682955723"),
    145 		bigFromString("10937079261204603443118731009201819560867324167189758120988909645641782263430128449826989846631183550578761324239709121189827307416350485191350050332642639"),
    146 	},
    147 }
    148 
    149 func TestMarshalRSAPrivateKey(t *testing.T) {
    150 	priv := &rsa.PrivateKey{
    151 		PublicKey: rsa.PublicKey{
    152 			N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"),
    153 			E: 3,
    154 		},
    155 		D: fromBase10("10897585948254795600358846499957366070880176878341177571733155050184921896034527397712889205732614568234385175145686545381899460748279607074689061600935843283397424506622998458510302603922766336783617368686090042765718290914099334449154829375179958369993407724946186243249568928237086215759259909861748642124071874879861299389874230489928271621259294894142840428407196932444474088857746123104978617098858619445675532587787023228852383149557470077802718705420275739737958953794088728369933811184572620857678792001136676902250566845618813972833750098806496641114644760255910789397593428910198080271317419213080834885003"),
    156 		Primes: []*big.Int{
    157 			fromBase10("1025363189502892836833747188838978207017355117492483312747347695538428729137306368764177201532277413433182799108299960196606011786562992097313508180436744488171474690412562218914213688661311117337381958560443"),
    158 			fromBase10("3467903426626310123395340254094941045497208049900750380025518552334536945536837294961497712862519984786362199788654739924501424784631315081391467293694361474867825728031147665777546570788493758372218019373"),
    159 			fromBase10("4597024781409332673052708605078359346966325141767460991205742124888960305710298765592730135879076084498363772408626791576005136245060321874472727132746643162385746062759369754202494417496879741537284589047"),
    160 		},
    161 	}
    162 
    163 	derBytes := MarshalPKCS1PrivateKey(priv)
    164 
    165 	priv2, err := ParsePKCS1PrivateKey(derBytes)
    166 	if err != nil {
    167 		t.Errorf("error parsing serialized key: %s", err)
    168 		return
    169 	}
    170 	if priv.PublicKey.N.Cmp(priv2.PublicKey.N) != 0 ||
    171 		priv.PublicKey.E != priv2.PublicKey.E ||
    172 		priv.D.Cmp(priv2.D) != 0 ||
    173 		len(priv2.Primes) != 3 ||
    174 		priv.Primes[0].Cmp(priv2.Primes[0]) != 0 ||
    175 		priv.Primes[1].Cmp(priv2.Primes[1]) != 0 ||
    176 		priv.Primes[2].Cmp(priv2.Primes[2]) != 0 {
    177 		t.Errorf("got:%+v want:%+v", priv, priv2)
    178 	}
    179 }
    180 
    181 type matchHostnamesTest struct {
    182 	pattern, host string
    183 	ok            bool
    184 }
    185 
    186 var matchHostnamesTests = []matchHostnamesTest{
    187 	{"a.b.c", "a.b.c", true},
    188 	{"a.b.c", "b.b.c", false},
    189 	{"", "b.b.c", false},
    190 	{"a.b.c", "", false},
    191 	{"example.com", "example.com", true},
    192 	{"example.com", "www.example.com", false},
    193 	{"*.example.com", "example.com", false},
    194 	{"*.example.com", "www.example.com", true},
    195 	{"*.example.com", "www.example.com.", true},
    196 	{"*.example.com", "xyz.www.example.com", false},
    197 	{"*.*.example.com", "xyz.www.example.com", false},
    198 	{"*.www.*.com", "xyz.www.example.com", false},
    199 	{"*bar.example.com", "foobar.example.com", false},
    200 	{"f*.example.com", "foobar.example.com", false},
    201 	{"", ".", false},
    202 	{".", "", false},
    203 	{".", ".", false},
    204 	{"example.com", "example.com.", true},
    205 	{"example.com.", "example.com", true},
    206 	{"example.com.", "example.com.", true},
    207 	{"*.com.", "example.com.", true},
    208 	{"*.com.", "example.com", true},
    209 	{"*.com", "example.com", true},
    210 	{"*.com", "example.com.", true},
    211 }
    212 
    213 func TestMatchHostnames(t *testing.T) {
    214 	for i, test := range matchHostnamesTests {
    215 		r := matchHostnames(test.pattern, test.host)
    216 		if r != test.ok {
    217 			t.Errorf("#%d mismatch got: %t want: %t when matching '%s' against '%s'", i, r, test.ok, test.host, test.pattern)
    218 		}
    219 	}
    220 }
    221 
    222 func TestMatchIP(t *testing.T) {
    223 	// Check that pattern matching is working.
    224 	c := &Certificate{
    225 		DNSNames: []string{"*.foo.bar.baz"},
    226 		Subject: pkix.Name{
    227 			CommonName: "*.foo.bar.baz",
    228 		},
    229 	}
    230 	err := c.VerifyHostname("quux.foo.bar.baz")
    231 	if err != nil {
    232 		t.Fatalf("VerifyHostname(quux.foo.bar.baz): %v", err)
    233 	}
    234 
    235 	// But check that if we change it to be matching against an IP address,
    236 	// it is rejected.
    237 	c = &Certificate{
    238 		DNSNames: []string{"*.2.3.4"},
    239 		Subject: pkix.Name{
    240 			CommonName: "*.2.3.4",
    241 		},
    242 	}
    243 	err = c.VerifyHostname("1.2.3.4")
    244 	if err == nil {
    245 		t.Fatalf("VerifyHostname(1.2.3.4) should have failed, did not")
    246 	}
    247 
    248 	c = &Certificate{
    249 		IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
    250 	}
    251 	err = c.VerifyHostname("127.0.0.1")
    252 	if err != nil {
    253 		t.Fatalf("VerifyHostname(127.0.0.1): %v", err)
    254 	}
    255 	err = c.VerifyHostname("::1")
    256 	if err != nil {
    257 		t.Fatalf("VerifyHostname(::1): %v", err)
    258 	}
    259 	err = c.VerifyHostname("[::1]")
    260 	if err != nil {
    261 		t.Fatalf("VerifyHostname([::1]): %v", err)
    262 	}
    263 }
    264 
    265 func TestCertificateParse(t *testing.T) {
    266 	s, _ := hex.DecodeString(certBytes)
    267 	certs, err := ParseCertificates(s)
    268 	if err != nil {
    269 		t.Error(err)
    270 	}
    271 	if len(certs) != 2 {
    272 		t.Errorf("Wrong number of certs: got %d want 2", len(certs))
    273 		return
    274 	}
    275 
    276 	err = certs[0].CheckSignatureFrom(certs[1])
    277 	if err != nil {
    278 		t.Error(err)
    279 	}
    280 
    281 	if err := certs[0].VerifyHostname("mail.google.com"); err != nil {
    282 		t.Error(err)
    283 	}
    284 
    285 	const expectedExtensions = 4
    286 	if n := len(certs[0].Extensions); n != expectedExtensions {
    287 		t.Errorf("want %d extensions, got %d", expectedExtensions, n)
    288 	}
    289 }
    290 
    291 var certBytes = "308203223082028ba00302010202106edf0d9499fd4533dd1297fc42a93be1300d06092a864886" +
    292 	"f70d0101050500304c310b3009060355040613025a4131253023060355040a131c546861777465" +
    293 	"20436f6e73756c74696e67202850747929204c74642e311630140603550403130d546861777465" +
    294 	"20534743204341301e170d3039303332353136343932395a170d3130303332353136343932395a" +
    295 	"3069310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630" +
    296 	"140603550407130d4d6f756e7461696e205669657731133011060355040a130a476f6f676c6520" +
    297 	"496e63311830160603550403130f6d61696c2e676f6f676c652e636f6d30819f300d06092a8648" +
    298 	"86f70d010101050003818d0030818902818100c5d6f892fccaf5614b064149e80a2c9581a218ef" +
    299 	"41ec35bd7a58125ae76f9ea54ddc893abbeb029f6b73616bf0ffd868791fba7af9c4aebf3706ba" +
    300 	"3eeaeed27435b4ddcfb157c05f351d66aa87fee0de072d66d773affbd36ab78bef090e0cc861a9" +
    301 	"03ac90dd98b51c9c41566c017f0beec3bff391051ffba0f5cc6850ad2a590203010001a381e730" +
    302 	"81e430280603551d250421301f06082b0601050507030106082b06010505070302060960864801" +
    303 	"86f842040130360603551d1f042f302d302ba029a0278625687474703a2f2f63726c2e74686177" +
    304 	"74652e636f6d2f54686177746553474343412e63726c307206082b060105050701010466306430" +
    305 	"2206082b060105050730018616687474703a2f2f6f6373702e7468617774652e636f6d303e0608" +
    306 	"2b060105050730028632687474703a2f2f7777772e7468617774652e636f6d2f7265706f736974" +
    307 	"6f72792f5468617774655f5347435f43412e637274300c0603551d130101ff04023000300d0609" +
    308 	"2a864886f70d01010505000381810062f1f3050ebc105e497c7aedf87e24d2f4a986bb3b837bd1" +
    309 	"9b91ebcad98b065992f6bd2b49b7d6d3cb2e427a99d606c7b1d46352527fac39e6a8b6726de5bf" +
    310 	"70212a52cba07634a5e332011bd1868e78eb5e3c93cf03072276786f207494feaa0ed9d53b2110" +
    311 	"a76571f90209cdae884385c882587030ee15f33d761e2e45a6bc308203233082028ca003020102" +
    312 	"020430000002300d06092a864886f70d0101050500305f310b3009060355040613025553311730" +
    313 	"15060355040a130e566572695369676e2c20496e632e31373035060355040b132e436c61737320" +
    314 	"33205075626c6963205072696d6172792043657274696669636174696f6e20417574686f726974" +
    315 	"79301e170d3034303531333030303030305a170d3134303531323233353935395a304c310b3009" +
    316 	"060355040613025a4131253023060355040a131c54686177746520436f6e73756c74696e672028" +
    317 	"50747929204c74642e311630140603550403130d5468617774652053474320434130819f300d06" +
    318 	"092a864886f70d010101050003818d0030818902818100d4d367d08d157faecd31fe7d1d91a13f" +
    319 	"0b713cacccc864fb63fc324b0794bd6f80ba2fe10493c033fc093323e90b742b71c403c6d2cde2" +
    320 	"2ff50963cdff48a500bfe0e7f388b72d32de9836e60aad007bc4644a3b847503f270927d0e62f5" +
    321 	"21ab693684317590f8bfc76c881b06957cc9e5a8de75a12c7a68dfd5ca1c875860190203010001" +
    322 	"a381fe3081fb30120603551d130101ff040830060101ff020100300b0603551d0f040403020106" +
    323 	"301106096086480186f842010104040302010630280603551d110421301fa41d301b3119301706" +
    324 	"035504031310507269766174654c6162656c332d313530310603551d1f042a30283026a024a022" +
    325 	"8620687474703a2f2f63726c2e766572697369676e2e636f6d2f706361332e63726c303206082b" +
    326 	"0601050507010104263024302206082b060105050730018616687474703a2f2f6f6373702e7468" +
    327 	"617774652e636f6d30340603551d25042d302b06082b0601050507030106082b06010505070302" +
    328 	"06096086480186f8420401060a6086480186f845010801300d06092a864886f70d010105050003" +
    329 	"81810055ac63eadea1ddd2905f9f0bce76be13518f93d9052bc81b774bad6950a1eededcfddb07" +
    330 	"e9e83994dcab72792f06bfab8170c4a8edea5334edef1e53d906c7562bd15cf4d18a8eb42bb137" +
    331 	"9048084225c53e8acb7feb6f04d16dc574a2f7a27c7b603c77cd0ece48027f012fb69b37e02a2a" +
    332 	"36dcd585d6ace53f546f961e05af"
    333 
    334 func TestCreateSelfSignedCertificate(t *testing.T) {
    335 	random := rand.Reader
    336 
    337 	ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    338 	if err != nil {
    339 		t.Fatalf("Failed to generate ECDSA key: %s", err)
    340 	}
    341 
    342 	tests := []struct {
    343 		name      string
    344 		pub, priv interface{}
    345 		checkSig  bool
    346 		sigAlgo   SignatureAlgorithm
    347 	}{
    348 		{"RSA/RSA", &testPrivateKey.PublicKey, testPrivateKey, true, SHA1WithRSA},
    349 		{"RSA/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
    350 		{"ECDSA/RSA", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSA},
    351 		{"ECDSA/ECDSA", &ecdsaPriv.PublicKey, ecdsaPriv, true, ECDSAWithSHA1},
    352 		{"RSAPSS/RSAPSS", &testPrivateKey.PublicKey, testPrivateKey, true, SHA256WithRSAPSS},
    353 		{"ECDSA/RSAPSS", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSAPSS},
    354 		{"RSAPSS/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
    355 	}
    356 
    357 	testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth}
    358 	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
    359 	extraExtensionData := []byte("extra extension")
    360 
    361 	for _, test := range tests {
    362 		commonName := "test.example.com"
    363 		template := Certificate{
    364 			// SerialNumber is negative to ensure that negative
    365 			// values are parsed. This is due to the prevalence of
    366 			// buggy code that produces certificates with negative
    367 			// serial numbers.
    368 			SerialNumber: big.NewInt(-1),
    369 			Subject: pkix.Name{
    370 				CommonName:   commonName,
    371 				Organization: []string{" Acme Co"},
    372 				Country:      []string{"US"},
    373 				ExtraNames: []pkix.AttributeTypeAndValue{
    374 					{
    375 						Type:  []int{2, 5, 4, 42},
    376 						Value: "Gopher",
    377 					},
    378 					// This should override the Country, above.
    379 					{
    380 						Type:  []int{2, 5, 4, 6},
    381 						Value: "NL",
    382 					},
    383 				},
    384 			},
    385 			NotBefore: time.Unix(1000, 0),
    386 			NotAfter:  time.Unix(100000, 0),
    387 
    388 			SignatureAlgorithm: test.sigAlgo,
    389 
    390 			SubjectKeyId: []byte{1, 2, 3, 4},
    391 			KeyUsage:     KeyUsageCertSign,
    392 
    393 			ExtKeyUsage:        testExtKeyUsage,
    394 			UnknownExtKeyUsage: testUnknownExtKeyUsage,
    395 
    396 			BasicConstraintsValid: true,
    397 			IsCA: true,
    398 
    399 			OCSPServer:            []string{"http://ocsp.example.com"},
    400 			IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
    401 
    402 			DNSNames:       []string{"test.example.com"},
    403 			EmailAddresses: []string{"gopher (a] golang.org"},
    404 			IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
    405 
    406 			PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
    407 			PermittedDNSDomains: []string{".example.com", "example.com"},
    408 
    409 			CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
    410 
    411 			ExtraExtensions: []pkix.Extension{
    412 				{
    413 					Id:    []int{1, 2, 3, 4},
    414 					Value: extraExtensionData,
    415 				},
    416 				// This extension should override the SubjectKeyId, above.
    417 				{
    418 					Id:       oidExtensionSubjectKeyId,
    419 					Critical: false,
    420 					Value:    []byte{0x04, 0x04, 4, 3, 2, 1},
    421 				},
    422 			},
    423 		}
    424 
    425 		derBytes, err := CreateCertificate(random, &template, &template, test.pub, test.priv)
    426 		if err != nil {
    427 			t.Errorf("%s: failed to create certificate: %s", test.name, err)
    428 			continue
    429 		}
    430 
    431 		cert, err := ParseCertificate(derBytes)
    432 		if err != nil {
    433 			t.Errorf("%s: failed to parse certificate: %s", test.name, err)
    434 			continue
    435 		}
    436 
    437 		if len(cert.PolicyIdentifiers) != 1 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) {
    438 			t.Errorf("%s: failed to parse policy identifiers: got:%#v want:%#v", test.name, cert.PolicyIdentifiers, template.PolicyIdentifiers)
    439 		}
    440 
    441 		if len(cert.PermittedDNSDomains) != 2 || cert.PermittedDNSDomains[0] != ".example.com" || cert.PermittedDNSDomains[1] != "example.com" {
    442 			t.Errorf("%s: failed to parse name constraints: %#v", test.name, cert.PermittedDNSDomains)
    443 		}
    444 
    445 		if cert.Subject.CommonName != commonName {
    446 			t.Errorf("%s: subject wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Subject.CommonName, commonName)
    447 		}
    448 
    449 		if len(cert.Subject.Country) != 1 || cert.Subject.Country[0] != "NL" {
    450 			t.Errorf("%s: ExtraNames didn't override Country", test.name)
    451 		}
    452 
    453 		found := false
    454 		for _, atv := range cert.Subject.Names {
    455 			if atv.Type.Equal([]int{2, 5, 4, 42}) {
    456 				found = true
    457 				break
    458 			}
    459 		}
    460 		if !found {
    461 			t.Errorf("%s: Names didn't contain oid 2.5.4.42 from ExtraNames", test.name)
    462 		}
    463 
    464 		if cert.Issuer.CommonName != commonName {
    465 			t.Errorf("%s: issuer wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Issuer.CommonName, commonName)
    466 		}
    467 
    468 		if cert.SignatureAlgorithm != test.sigAlgo {
    469 			t.Errorf("%s: SignatureAlgorithm wasn't copied from template. Got %v, want %v", test.name, cert.SignatureAlgorithm, test.sigAlgo)
    470 		}
    471 
    472 		if !reflect.DeepEqual(cert.ExtKeyUsage, testExtKeyUsage) {
    473 			t.Errorf("%s: extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.ExtKeyUsage, testExtKeyUsage)
    474 		}
    475 
    476 		if !reflect.DeepEqual(cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) {
    477 			t.Errorf("%s: unknown extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.UnknownExtKeyUsage, testUnknownExtKeyUsage)
    478 		}
    479 
    480 		if !reflect.DeepEqual(cert.OCSPServer, template.OCSPServer) {
    481 			t.Errorf("%s: OCSP servers differ from template. Got %v, want %v", test.name, cert.OCSPServer, template.OCSPServer)
    482 		}
    483 
    484 		if !reflect.DeepEqual(cert.IssuingCertificateURL, template.IssuingCertificateURL) {
    485 			t.Errorf("%s: Issuing certificate URLs differ from template. Got %v, want %v", test.name, cert.IssuingCertificateURL, template.IssuingCertificateURL)
    486 		}
    487 
    488 		if !reflect.DeepEqual(cert.DNSNames, template.DNSNames) {
    489 			t.Errorf("%s: SAN DNS names differ from template. Got %v, want %v", test.name, cert.DNSNames, template.DNSNames)
    490 		}
    491 
    492 		if !reflect.DeepEqual(cert.EmailAddresses, template.EmailAddresses) {
    493 			t.Errorf("%s: SAN emails differ from template. Got %v, want %v", test.name, cert.EmailAddresses, template.EmailAddresses)
    494 		}
    495 
    496 		if !reflect.DeepEqual(cert.IPAddresses, template.IPAddresses) {
    497 			t.Errorf("%s: SAN IPs differ from template. Got %v, want %v", test.name, cert.IPAddresses, template.IPAddresses)
    498 		}
    499 
    500 		if !reflect.DeepEqual(cert.CRLDistributionPoints, template.CRLDistributionPoints) {
    501 			t.Errorf("%s: CRL distribution points differ from template. Got %v, want %v", test.name, cert.CRLDistributionPoints, template.CRLDistributionPoints)
    502 		}
    503 
    504 		if !bytes.Equal(cert.SubjectKeyId, []byte{4, 3, 2, 1}) {
    505 			t.Errorf("%s: ExtraExtensions didn't override SubjectKeyId", test.name)
    506 		}
    507 
    508 		if !bytes.Contains(derBytes, extraExtensionData) {
    509 			t.Errorf("%s: didn't find extra extension in DER output", test.name)
    510 		}
    511 
    512 		if test.checkSig {
    513 			err = cert.CheckSignatureFrom(cert)
    514 			if err != nil {
    515 				t.Errorf("%s: signature verification failed: %s", test.name, err)
    516 			}
    517 		}
    518 	}
    519 }
    520 
    521 func TestUnknownCriticalExtension(t *testing.T) {
    522 	priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    523 	if err != nil {
    524 		t.Fatalf("Failed to generate ECDSA key: %s", err)
    525 	}
    526 
    527 	oids := []asn1.ObjectIdentifier{
    528 		// This OID is in the PKIX arc, but unknown.
    529 		{2, 5, 29, 999999},
    530 		// This is a nonsense, unassigned OID.
    531 		{1, 2, 3, 4},
    532 	}
    533 
    534 	for _, oid := range oids {
    535 		template := Certificate{
    536 			SerialNumber: big.NewInt(1),
    537 			Subject: pkix.Name{
    538 				CommonName: "foo",
    539 			},
    540 			NotBefore: time.Unix(1000, 0),
    541 			NotAfter:  time.Now().AddDate(1, 0, 0),
    542 
    543 			BasicConstraintsValid: true,
    544 			IsCA: true,
    545 
    546 			KeyUsage:    KeyUsageCertSign,
    547 			ExtKeyUsage: []ExtKeyUsage{ExtKeyUsageServerAuth},
    548 
    549 			ExtraExtensions: []pkix.Extension{
    550 				{
    551 					Id:       oid,
    552 					Critical: true,
    553 					Value:    nil,
    554 				},
    555 			},
    556 		}
    557 
    558 		derBytes, err := CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
    559 		if err != nil {
    560 			t.Fatalf("failed to create certificate: %s", err)
    561 		}
    562 
    563 		cert, err := ParseCertificate(derBytes)
    564 		if err != nil {
    565 			t.Fatalf("Certificate with unknown critical extension was not parsed: %s", err)
    566 		}
    567 
    568 		roots := NewCertPool()
    569 		roots.AddCert(cert)
    570 
    571 		// Setting Roots ensures that Verify won't delegate to the OS
    572 		// library and thus the correct error should always be
    573 		// returned.
    574 		_, err = cert.Verify(VerifyOptions{Roots: roots})
    575 		if err == nil {
    576 			t.Fatal("Certificate with unknown critical extension was verified without error")
    577 		}
    578 		if _, ok := err.(UnhandledCriticalExtension); !ok {
    579 			t.Fatalf("Error was %#v, but wanted one of type UnhandledCriticalExtension", err)
    580 		}
    581 
    582 		cert.UnhandledCriticalExtensions = nil
    583 		if _, err = cert.Verify(VerifyOptions{Roots: roots}); err != nil {
    584 			t.Errorf("Certificate failed to verify after unhandled critical extensions were cleared: %s", err)
    585 		}
    586 	}
    587 }
    588 
    589 // Self-signed certificate using ECDSA with SHA1 & secp256r1
    590 var ecdsaSHA1CertPem = `
    591 -----BEGIN CERTIFICATE-----
    592 MIICDjCCAbUCCQDF6SfN0nsnrjAJBgcqhkjOPQQBMIGPMQswCQYDVQQGEwJVUzET
    593 MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEVMBMG
    594 A1UECgwMR29vZ2xlLCBJbmMuMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
    595 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIwMjAyMDUw
    596 WhcNMjIwNTE4MjAyMDUwWjCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
    597 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTATBgNVBAoMDEdvb2dsZSwg
    598 SW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAhBgkqhkiG9w0BCQEWFGdv
    599 bGFuZy1kZXZAZ21haWwuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/Wgn
    600 WQDo5+bz71T0327ERgd5SDDXFbXLpzIZDXTkjpe8QTEbsF+ezsQfrekrpDPC4Cd3
    601 P9LY0tG+aI8IyVKdUjAJBgcqhkjOPQQBA0gAMEUCIGlsqMcRqWVIWTD6wXwe6Jk2
    602 DKxL46r/FLgJYnzBEH99AiEA3fBouObsvV1R3oVkb4BQYnD4/4LeId6lAT43YvyV
    603 a/A=
    604 -----END CERTIFICATE-----
    605 `
    606 
    607 // Self-signed certificate using ECDSA with SHA256 & secp256r1
    608 var ecdsaSHA256p256CertPem = `
    609 -----BEGIN CERTIFICATE-----
    610 MIICDzCCAbYCCQDlsuMWvgQzhTAKBggqhkjOPQQDAjCBjzELMAkGA1UEBhMCVVMx
    611 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTAT
    612 BgNVBAoMDEdvb2dsZSwgSW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAh
    613 BgkqhkiG9w0BCQEWFGdvbGFuZy1kZXZAZ21haWwuY29tMB4XDTEyMDUyMTAwMTkx
    614 NloXDTIyMDUxOTAwMTkxNlowgY8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp
    615 Zm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRUwEwYDVQQKDAxHb29nbGUs
    616 IEluYy4xFzAVBgNVBAMMDnd3dy5nb29nbGUuY29tMSMwIQYJKoZIhvcNAQkBFhRn
    617 b2xhbmctZGV2QGdtYWlsLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPMt
    618 2ErhxAty5EJRu9yM+MTy+hUXm3pdW1ensAv382KoGExSXAFWP7pjJnNtHO+XSwVm
    619 YNtqjcAGFKpweoN//kQwCgYIKoZIzj0EAwIDRwAwRAIgIYSaUA/IB81gjbIw/hUV
    620 70twxJr5EcgOo0hLp3Jm+EYCIFDO3NNcgmURbJ1kfoS3N/0O+irUtoPw38YoNkqJ
    621 h5wi
    622 -----END CERTIFICATE-----
    623 `
    624 
    625 // Self-signed certificate using ECDSA with SHA256 & secp384r1
    626 var ecdsaSHA256p384CertPem = `
    627 -----BEGIN CERTIFICATE-----
    628 MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx
    629 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
    630 BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
    631 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0
    632 WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
    633 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
    634 SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
    635 YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK
    636 jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze
    637 qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI
    638 zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr
    639 PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh
    640 3yILeYQzllt/g0rKVRk=
    641 -----END CERTIFICATE-----
    642 `
    643 
    644 // Self-signed certificate using ECDSA with SHA384 & secp521r1
    645 var ecdsaSHA384p521CertPem = `
    646 -----BEGIN CERTIFICATE-----
    647 MIICljCCAfcCCQDhp1AFD/ahKjAKBggqhkjOPQQDAzCBjjELMAkGA1UEBhMCVVMx
    648 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
    649 BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
    650 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMTUwNDI5
    651 WhcNMjIwNTE5MTUwNDI5WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
    652 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
    653 SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
    654 YW5nLWRldkBnbWFpbC5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACqx9Rv
    655 IssRs1LWYcNN+WffwlHw4Tv3y8/LIAA9MF1ZScIonU9nRMxt4a2uGJVCPDw6JHpz
    656 PaYc0E9puLoE9AfKpwFr59Jkot7dBg55SKPEFkddoip/rvmN7NPAWjMBirOwjOkm
    657 8FPthvPhGPqsu9AvgVuHu3PosWiHGNrhh379pva8MzAKBggqhkjOPQQDAwOBjAAw
    658 gYgCQgEHNmswkUdPpHqrVxp9PvLVl+xxPuHBkT+75z9JizyxtqykHQo9Uh6SWCYH
    659 BF9KLolo01wMt8DjoYP5Fb3j5MH7xwJCAbWZzTOp4l4DPkIvAh4LeC4VWbwPPyqh
    660 kBg71w/iEcSY3wUKgHGcJJrObZw7wys91I5kENljqw/Samdr3ka+jBJa
    661 -----END CERTIFICATE-----
    662 `
    663 
    664 var ecdsaTests = []struct {
    665 	sigAlgo SignatureAlgorithm
    666 	pemCert string
    667 }{
    668 	{ECDSAWithSHA1, ecdsaSHA1CertPem},
    669 	{ECDSAWithSHA256, ecdsaSHA256p256CertPem},
    670 	{ECDSAWithSHA256, ecdsaSHA256p384CertPem},
    671 	{ECDSAWithSHA384, ecdsaSHA384p521CertPem},
    672 }
    673 
    674 func TestECDSA(t *testing.T) {
    675 	for i, test := range ecdsaTests {
    676 		pemBlock, _ := pem.Decode([]byte(test.pemCert))
    677 		cert, err := ParseCertificate(pemBlock.Bytes)
    678 		if err != nil {
    679 			t.Errorf("%d: failed to parse certificate: %s", i, err)
    680 			continue
    681 		}
    682 		if sa := cert.SignatureAlgorithm; sa != test.sigAlgo {
    683 			t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo)
    684 		}
    685 		if parsedKey, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok {
    686 			t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey)
    687 		}
    688 		if pka := cert.PublicKeyAlgorithm; pka != ECDSA {
    689 			t.Errorf("%d: public key algorithm is %v, want ECDSA", i, pka)
    690 		}
    691 		if err = cert.CheckSignatureFrom(cert); err != nil {
    692 			t.Errorf("%d: certificate verification failed: %s", i, err)
    693 		}
    694 	}
    695 }
    696 
    697 // Self-signed certificate using DSA with SHA1
    698 var dsaCertPem = `-----BEGIN CERTIFICATE-----
    699 MIIEDTCCA82gAwIBAgIJALHPghaoxeDhMAkGByqGSM44BAMweTELMAkGA1UEBhMC
    700 VVMxCzAJBgNVBAgTAk5DMQ8wDQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2ds
    701 ZSwgSW5jMRIwEAYDVQQDEwlKb24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFs
    702 bGllQGdvb2dsZS5jb20wHhcNMTEwNTE0MDMwMTQ1WhcNMTEwNjEzMDMwMTQ1WjB5
    703 MQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkMxDzANBgNVBAcTBk5ld3RvbjEUMBIG
    704 A1UEChMLR29vZ2xlLCBJbmMxEjAQBgNVBAMTCUpvbiBBbGxpZTEiMCAGCSqGSIb3
    705 DQEJARYTam9uYWxsaWVAZ29vZ2xlLmNvbTCCAbcwggEsBgcqhkjOOAQBMIIBHwKB
    706 gQC8hLUnQ7FpFYu4WXTj6DKvXvz8QrJkNJCVMTpKAT7uBpobk32S5RrPKXocd4gN
    707 8lyGB9ggS03EVlEwXvSmO0DH2MQtke2jl9j1HLydClMf4sbx5V6TV9IFw505U1iW
    708 jL7awRMgxge+FsudtJK254FjMFo03ZnOQ8ZJJ9E6AEDrlwIVAJpnBn9moyP11Ox5
    709 Asc/5dnjb6dPAoGBAJFHd4KVv1iTVCvEG6gGiYop5DJh28hUQcN9kul+2A0yPUSC
    710 X93oN00P8Vh3eYgSaCWZsha7zDG53MrVJ0Zf6v/X/CoZNhLldeNOepivTRAzn+Rz
    711 kKUYy5l1sxYLHQKF0UGNCXfFKZT0PCmgU+PWhYNBBMn6/cIh44vp85ideo5CA4GE
    712 AAKBgFmifCafzeRaohYKXJgMGSEaggCVCRq5xdyDCat+wbOkjC4mfG01/um3G8u5
    713 LxasjlWRKTR/tcAL7t0QuokVyQaYdVypZXNaMtx1db7YBuHjj3aP+8JOQRI9xz8c
    714 bp5NDJ5pISiFOv4p3GZfqZPcqckDt78AtkQrmnal2txhhjF6o4HeMIHbMB0GA1Ud
    715 DgQWBBQVyyr7hO11ZFFpWX50298Sa3V+rzCBqwYDVR0jBIGjMIGggBQVyyr7hO11
    716 ZFFpWX50298Sa3V+r6F9pHsweTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAk5DMQ8w
    717 DQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2dsZSwgSW5jMRIwEAYDVQQDEwlK
    718 b24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFsbGllQGdvb2dsZS5jb22CCQCx
    719 z4IWqMXg4TAMBgNVHRMEBTADAQH/MAkGByqGSM44BAMDLwAwLAIUPtn/5j8Q1jJI
    720 7ggOIsgrhgUdjGQCFCsmDq1H11q9+9Wp9IMeGrTSKHIM
    721 -----END CERTIFICATE-----
    722 `
    723 
    724 func TestParseCertificateWithDsaPublicKey(t *testing.T) {
    725 	expectedKey := &dsa.PublicKey{
    726 		Parameters: dsa.Parameters{
    727 			P: bigFromHexString("00BC84B52743B169158BB85974E3E832AF5EFCFC42B264349095313A4A013EEE069A1B937D92E51ACF297A1C77880DF25C8607D8204B4DC45651305EF4A63B40C7D8C42D91EDA397D8F51CBC9D0A531FE2C6F1E55E9357D205C39D395358968CBEDAC11320C607BE16CB9DB492B6E78163305A34DD99CE43C64927D13A0040EB97"),
    728 			Q: bigFromHexString("009A67067F66A323F5D4EC7902C73FE5D9E36FA74F"),
    729 			G: bigFromHexString("009147778295BF5893542BC41BA806898A29E43261DBC85441C37D92E97ED80D323D44825FDDE8374D0FF15877798812682599B216BBCC31B9DCCAD527465FEAFFD7FC2A193612E575E34E7A98AF4D10339FE47390A518CB9975B3160B1D0285D1418D0977C52994F43C29A053E3D685834104C9FAFDC221E38BE9F3989D7A8E42"),
    730 		},
    731 		Y: bigFromHexString("59A27C269FCDE45AA2160A5C980C19211A820095091AB9C5DC8309AB7EC1B3A48C2E267C6D35FEE9B71BCBB92F16AC8E559129347FB5C00BEEDD10BA8915C90698755CA965735A32DC7575BED806E1E38F768FFBC24E41123DC73F1C6E9E4D0C9E692128853AFE29DC665FA993DCA9C903B7BF00B6442B9A76A5DADC6186317A"),
    732 	}
    733 	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
    734 	cert, err := ParseCertificate(pemBlock.Bytes)
    735 	if err != nil {
    736 		t.Fatalf("Failed to parse certificate: %s", err)
    737 	}
    738 	if cert.PublicKeyAlgorithm != DSA {
    739 		t.Errorf("Parsed key algorithm was not DSA")
    740 	}
    741 	parsedKey, ok := cert.PublicKey.(*dsa.PublicKey)
    742 	if !ok {
    743 		t.Fatalf("Parsed key was not a DSA key: %s", err)
    744 	}
    745 	if expectedKey.Y.Cmp(parsedKey.Y) != 0 ||
    746 		expectedKey.P.Cmp(parsedKey.P) != 0 ||
    747 		expectedKey.Q.Cmp(parsedKey.Q) != 0 ||
    748 		expectedKey.G.Cmp(parsedKey.G) != 0 {
    749 		t.Fatal("Parsed key differs from expected key")
    750 	}
    751 }
    752 
    753 func TestParseCertificateWithDSASignatureAlgorithm(t *testing.T) {
    754 	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
    755 	cert, err := ParseCertificate(pemBlock.Bytes)
    756 	if err != nil {
    757 		t.Fatalf("Failed to parse certificate: %s", err)
    758 	}
    759 	if cert.SignatureAlgorithm != DSAWithSHA1 {
    760 		t.Errorf("Parsed signature algorithm was not DSAWithSHA1")
    761 	}
    762 }
    763 
    764 func TestVerifyCertificateWithDSASignature(t *testing.T) {
    765 	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
    766 	cert, err := ParseCertificate(pemBlock.Bytes)
    767 	if err != nil {
    768 		t.Fatalf("Failed to parse certificate: %s", err)
    769 	}
    770 	// test cert is self-signed
    771 	if err = cert.CheckSignatureFrom(cert); err != nil {
    772 		t.Fatalf("DSA Certificate verification failed: %s", err)
    773 	}
    774 }
    775 
    776 var rsaPSSSelfSignedPEM = `-----BEGIN CERTIFICATE-----
    777 MIIGHjCCA9KgAwIBAgIBdjBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA
    778 oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCASAwbjELMAkGA1UEBhMC
    779 SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
    780 aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
    781 U0NBMB4XDTEzMDUxNDA1MDczMFoXDTI5MDUxNDA1MDczMFowbjELMAkGA1UEBhMC
    782 SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
    783 aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
    784 U0NBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAx/E3WRVxcCDXhoST
    785 8nVSLjW6hwM4Ni99AegWzcGtfGFo0zjFA1Cl5URqxauvYu3gQgQHBGA1CovWeGrl
    786 yVSRzOL1imcYsSgLOcnhVYB3Xcrof4ebv9+W+TwNdc9YzAwcj8rNd5nP6PKXIQ+W
    787 PCkEOXdyb80YEnxuT+NPjkVfFSPBS7QYZpvT2fwy4fZ0eh48253+7VleSmTO0mqj
    788 7TlzaG56q150SLZbhpOd8jD8bM/wACnLCPR88wj4hCcDLEwoLyY85HJCTIQQMnoT
    789 UpqyzEeupPREIm6yi4d8C9YqIWFn2YTnRcWcmMaJLzq+kYwKoudfnoC6RW2vzZXn
    790 defQs68IZuK+uALu9G3JWGPgu0CQGj0JNDT8zkiDV++4eNrZczWKjr1YnAL+VbLK
    791 bApwL2u19l2WDpfUklimhWfraqHNIUKU6CjZOG31RzXcplIj0mtqs0E1r7r357Es
    792 yFoB28iNo4cz1lCulh0E4WJzWzLZcT4ZspHHRCFyvYnXoibXEV1nULq8ByKKG0FS
    793 7nn4SseoV+8PvjHLPhmHGMvi4mxkbcXdV3wthHT1/HXdqY84A4xHWt1+sB/TpTek
    794 tDhFlEfcUygvTu58UtOnysomOVVeERmi7WSujfzKsGJAJYeetiA5R+zX7BxeyFVE
    795 qW0zh1Tkwh0S8LRe5diJh4+6FG0CAwEAAaNfMF0wHQYDVR0OBBYEFD+oahaikBTV
    796 Urk81Uz7kRS2sx0aMA4GA1UdDwEB/wQEAwIBBjAYBgNVHSAEETAPMA0GCyqDCIaP
    797 fgYFAQEBMBIGA1UdEwEB/wQIMAYBAf8CAQAwQQYJKoZIhvcNAQEKMDSgDzANBglg
    798 hkgBZQMEAgEFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgEFAKIDAgEgA4IC
    799 AQAaxWBQn5CZuNBfyzL57mn31ukHUFd61OMROSX3PT7oCv1Dy+C2AdRlxOcbN3/n
    800 li0yfXUUqiY3COlLAHKRlkr97mLtxEFoJ0R8nVN2IQdChNQM/XSCzSGyY8NVa1OR
    801 TTpEWLnexJ9kvIdbFXwUqdTnAkOI0m7Rg8j+E+lRRHg1xDAA1qKttrtUj3HRQWf3
    802 kNTu628SiMvap6aIdncburaK56MP7gkR1Wr/ichOfjIA3Jgw2PapI31i0GqeMd66
    803 U1+lC9FeyMAJpuSVp/SoiYzYo+79SFcVoM2yw3yAnIKg7q9GLYYqzncdykT6C06c
    804 15gWFI6igmReAsD9ITSvYh0jLrLHfEYcPTOD3ZXJ4EwwHtWSoO3gq1EAtOYKu/Lv
    805 C8zfBsZcFdsHvsSiYeBU8Oioe42mguky3Ax9O7D805Ek6R68ra07MW/G4YxvV7IN
    806 2BfSaYy8MX9IG0ZMIOcoc0FeF5xkFmJ7kdrlTaJzC0IE9PNxNaH5QnOAFB8vxHcO
    807 FioUxb6UKdHcPLR1VZtAdTdTMjSJxUqD/35Cdfqs7oDJXz8f6TXO2Tdy6G++YUs9
    808 qsGZWxzFvvkXUkQSl0dQQ5jO/FtUJcAVXVVp20LxPemfatAHpW31WdJYeWSQWky2
    809 +f9b5TXKXVyjlUL7uHxowWrT2AtTchDH22wTEtqLEF9Z3Q==
    810 -----END CERTIFICATE-----`
    811 
    812 func TestRSAPSSSelfSigned(t *testing.T) {
    813 	der, _ := pem.Decode([]byte(rsaPSSSelfSignedPEM))
    814 	if der == nil {
    815 		t.Fatal("Failed to find PEM block")
    816 	}
    817 
    818 	cert, err := ParseCertificate(der.Bytes)
    819 	if err != nil {
    820 		t.Fatal(err)
    821 	}
    822 
    823 	if err = cert.CheckSignatureFrom(cert); err != nil {
    824 		t.Fatal(err)
    825 	}
    826 }
    827 
    828 const pemCertificate = `-----BEGIN CERTIFICATE-----
    829 MIIDATCCAemgAwIBAgIRAKQkkrFx1T/dgB/Go/xBM5swDQYJKoZIhvcNAQELBQAw
    830 EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xNjA4MTcyMDM2MDdaFw0xNzA4MTcyMDM2
    831 MDdaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
    832 ggEKAoIBAQDAoJtjG7M6InsWwIo+l3qq9u+g2rKFXNu9/mZ24XQ8XhV6PUR+5HQ4
    833 jUFWC58ExYhottqK5zQtKGkw5NuhjowFUgWB/VlNGAUBHtJcWR/062wYrHBYRxJH
    834 qVXOpYKbIWwFKoXu3hcpg/CkdOlDWGKoZKBCwQwUBhWE7MDhpVdQ+ZljUJWL+FlK
    835 yQK5iRsJd5TGJ6VUzLzdT4fmN2DzeK6GLeyMpVpU3sWV90JJbxWQ4YrzkKzYhMmB
    836 EcpXTG2wm+ujiHU/k2p8zlf8Sm7VBM/scmnMFt0ynNXop4FWvJzEm1G0xD2t+e2I
    837 5Utr04dOZPCgkm++QJgYhtZvgW7ZZiGTAgMBAAGjUjBQMA4GA1UdDwEB/wQEAwIF
    838 oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBsGA1UdEQQUMBKC
    839 EHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEBADpqKQxrthH5InC7
    840 X96UP0OJCu/lLEMkrjoEWYIQaFl7uLPxKH5AmQPH4lYwF7u7gksR7owVG9QU9fs6
    841 1fK7II9CVgCd/4tZ0zm98FmU4D0lHGtPARrrzoZaqVZcAvRnFTlPX5pFkPhVjjai
    842 /mkxX9LpD8oK1445DFHxK5UjLMmPIIWd8EOi+v5a+hgGwnJpoW7hntSl8kHMtTmy
    843 fnnktsblSUV4lRCit0ymC7Ojhe+gzCCwkgs5kDzVVag+tnl/0e2DloIjASwOhpbH
    844 KVcg7fBd484ht/sS+l0dsB4KDOSpd8JzVDMF8OZqlaydizoJO0yWr9GbCN1+OKq5
    845 EhLrEqU=
    846 -----END CERTIFICATE-----`
    847 
    848 func TestCRLCreation(t *testing.T) {
    849 	block, _ := pem.Decode([]byte(pemPrivateKey))
    850 	priv, _ := ParsePKCS1PrivateKey(block.Bytes)
    851 	block, _ = pem.Decode([]byte(pemCertificate))
    852 	cert, _ := ParseCertificate(block.Bytes)
    853 
    854 	loc := time.FixedZone("Oz/Atlantis", int((2 * time.Hour).Seconds()))
    855 
    856 	now := time.Unix(1000, 0).In(loc)
    857 	nowUTC := now.UTC()
    858 	expiry := time.Unix(10000, 0)
    859 
    860 	revokedCerts := []pkix.RevokedCertificate{
    861 		{
    862 			SerialNumber:   big.NewInt(1),
    863 			RevocationTime: nowUTC,
    864 		},
    865 		{
    866 			SerialNumber: big.NewInt(42),
    867 			// RevocationTime should be converted to UTC before marshaling.
    868 			RevocationTime: now,
    869 		},
    870 	}
    871 	expectedCerts := []pkix.RevokedCertificate{
    872 		{
    873 			SerialNumber:   big.NewInt(1),
    874 			RevocationTime: nowUTC,
    875 		},
    876 		{
    877 			SerialNumber:   big.NewInt(42),
    878 			RevocationTime: nowUTC,
    879 		},
    880 	}
    881 
    882 	crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry)
    883 	if err != nil {
    884 		t.Errorf("error creating CRL: %s", err)
    885 	}
    886 
    887 	parsedCRL, err := ParseDERCRL(crlBytes)
    888 	if err != nil {
    889 		t.Errorf("error reparsing CRL: %s", err)
    890 	}
    891 	if !reflect.DeepEqual(parsedCRL.TBSCertList.RevokedCertificates, expectedCerts) {
    892 		t.Errorf("RevokedCertificates mismatch: got %v; want %v.",
    893 			parsedCRL.TBSCertList.RevokedCertificates, expectedCerts)
    894 	}
    895 }
    896 
    897 func fromBase64(in string) []byte {
    898 	out := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
    899 	n, err := base64.StdEncoding.Decode(out, []byte(in))
    900 	if err != nil {
    901 		panic("failed to base64 decode")
    902 	}
    903 	return out[:n]
    904 }
    905 
    906 func TestParseDERCRL(t *testing.T) {
    907 	derBytes := fromBase64(derCRLBase64)
    908 	certList, err := ParseDERCRL(derBytes)
    909 	if err != nil {
    910 		t.Errorf("error parsing: %s", err)
    911 		return
    912 	}
    913 	numCerts := len(certList.TBSCertList.RevokedCertificates)
    914 	expected := 88
    915 	if numCerts != expected {
    916 		t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
    917 	}
    918 
    919 	if certList.HasExpired(time.Unix(1302517272, 0)) {
    920 		t.Errorf("CRL has expired (but shouldn't have)")
    921 	}
    922 
    923 	// Can't check the signature here without a package cycle.
    924 }
    925 
    926 func TestCRLWithoutExpiry(t *testing.T) {
    927 	derBytes := fromBase64("MIHYMIGZMAkGByqGSM44BAMwEjEQMA4GA1UEAxMHQ2FybERTUxcNOTkwODI3MDcwMDAwWjBpMBMCAgDIFw05OTA4MjIwNzAwMDBaMBMCAgDJFw05OTA4MjIwNzAwMDBaMBMCAgDTFw05OTA4MjIwNzAwMDBaMBMCAgDSFw05OTA4MjIwNzAwMDBaMBMCAgDUFw05OTA4MjQwNzAwMDBaMAkGByqGSM44BAMDLwAwLAIUfmVSdjP+NHMX0feW+aDU2G1cfT0CFAJ6W7fVWxjBz4fvftok8yqDnDWh")
    928 	certList, err := ParseDERCRL(derBytes)
    929 	if err != nil {
    930 		t.Fatal(err)
    931 	}
    932 	if !certList.TBSCertList.NextUpdate.IsZero() {
    933 		t.Errorf("NextUpdate is not the zero value")
    934 	}
    935 }
    936 
    937 func TestParsePEMCRL(t *testing.T) {
    938 	pemBytes := fromBase64(pemCRLBase64)
    939 	certList, err := ParseCRL(pemBytes)
    940 	if err != nil {
    941 		t.Errorf("error parsing: %s", err)
    942 		return
    943 	}
    944 	numCerts := len(certList.TBSCertList.RevokedCertificates)
    945 	expected := 2
    946 	if numCerts != expected {
    947 		t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
    948 	}
    949 
    950 	if certList.HasExpired(time.Unix(1302517272, 0)) {
    951 		t.Errorf("CRL has expired (but shouldn't have)")
    952 	}
    953 
    954 	// Can't check the signature here without a package cycle.
    955 }
    956 
    957 func TestImports(t *testing.T) {
    958 	testenv.MustHaveGoRun(t)
    959 
    960 	if err := exec.Command(testenv.GoToolPath(t), "run", "x509_test_import.go").Run(); err != nil {
    961 		t.Errorf("failed to run x509_test_import.go: %s", err)
    962 	}
    963 }
    964 
    965 const derCRLBase64 = "MIINqzCCDJMCAQEwDQYJKoZIhvcNAQEFBQAwVjEZMBcGA1UEAxMQUEtJIEZJTk1FQ0NBTklDQTEVMBMGA1UEChMMRklOTUVDQ0FOSUNBMRUwEwYDVQQLEwxGSU5NRUNDQU5JQ0ExCzAJBgNVBAYTAklUFw0xMTA1MDQxNjU3NDJaFw0xMTA1MDQyMDU3NDJaMIIMBzAhAg4Ze1od49Lt1qIXBydAzhcNMDkwNzE2MDg0MzIyWjAAMCECDl0HSL9bcZ1Ci/UHJ0DPFw0wOTA3MTYwODQzMTNaMAAwIQIOESB9tVAmX3cY7QcnQNAXDTA5MDcxNjA4NDUyMlowADAhAg4S1tGAQ3mHt8uVBydA1RcNMDkwODA0MTUyNTIyWjAAMCECDlQ249Y7vtC25ScHJ0DWFw0wOTA4MDQxNTI1MzdaMAAwIQIOISMop3NkA4PfYwcnQNkXDTA5MDgwNDExMDAzNFowADAhAg56/BMoS29KEShTBydA2hcNMDkwODA0MTEwMTAzWjAAMCECDnBp/22HPH5CSWoHJ0DbFw0wOTA4MDQxMDU0NDlaMAAwIQIOV9IP+8CD8bK+XAcnQNwXDTA5MDgwNDEwNTcxN1owADAhAg4v5aRz0IxWqYiXBydA3RcNMDkwODA0MTA1NzQ1WjAAMCECDlOU34VzvZAybQwHJ0DeFw0wOTA4MDQxMDU4MjFaMAAwIAINO4CD9lluIxcwBydBAxcNMDkwNzIyMTUzMTU5WjAAMCECDgOllfO8Y1QA7/wHJ0ExFw0wOTA3MjQxMTQxNDNaMAAwIQIOJBX7jbiCdRdyjgcnQUQXDTA5MDkxNjA5MzAwOFowADAhAg5iYSAgmDrlH/RZBydBRRcNMDkwOTE2MDkzMDE3WjAAMCECDmu6k6sr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VhQU9MUGc1N2ZNTVhEVEF5TVRBeU16RTBOVEF4TkZvd0dqQVlCZ05WDQpIUmdFRVJnUE1qQXdNakV3TWpNeE5EVXdNVFJhb0RBd0xqQWZCZ05WSFNNRUdEQVdnQlQxVERGNlVRTS9MTmVMDQpsNWx2cUhHUXEzZzltekFMQmdOVkhSUUVCQUlDQUlRd0RRWUpLb1pJaHZjTkFRRUZCUUFEZ1lFQUZVNUFzNk16DQpxNVBSc2lmYW9iUVBHaDFhSkx5QytNczVBZ2MwYld5QTNHQWR4dXI1U3BQWmVSV0NCamlQL01FSEJXSkNsQkhQDQpHUmNxNXlJZDNFakRrYUV5eFJhK2k2N0x6dmhJNmMyOUVlNks5cFNZd2ppLzdSVWhtbW5Qclh0VHhsTDBsckxyDQptUVFKNnhoRFJhNUczUUE0Q21VZHNITnZicnpnbUNZcHZWRT0NCi0tLS0tRU5EIFg1MDkgQ1JMLS0tLS0NCg0K"
    968 
    969 func TestCreateCertificateRequest(t *testing.T) {
    970 	random := rand.Reader
    971 
    972 	ecdsa256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
    973 	if err != nil {
    974 		t.Fatalf("Failed to generate ECDSA key: %s", err)
    975 	}
    976 
    977 	ecdsa384Priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
    978 	if err != nil {
    979 		t.Fatalf("Failed to generate ECDSA key: %s", err)
    980 	}
    981 
    982 	ecdsa521Priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
    983 	if err != nil {
    984 		t.Fatalf("Failed to generate ECDSA key: %s", err)
    985 	}
    986 
    987 	tests := []struct {
    988 		name    string
    989 		priv    interface{}
    990 		sigAlgo SignatureAlgorithm
    991 	}{
    992 		{"RSA", testPrivateKey, SHA1WithRSA},
    993 		{"ECDSA-256", ecdsa256Priv, ECDSAWithSHA1},
    994 		{"ECDSA-384", ecdsa384Priv, ECDSAWithSHA1},
    995 		{"ECDSA-521", ecdsa521Priv, ECDSAWithSHA1},
    996 	}
    997 
    998 	for _, test := range tests {
    999 		template := CertificateRequest{
   1000 			Subject: pkix.Name{
   1001 				CommonName:   "test.example.com",
   1002 				Organization: []string{" Acme Co"},
   1003 			},
   1004 			SignatureAlgorithm: test.sigAlgo,
   1005 			DNSNames:           []string{"test.example.com"},
   1006 			EmailAddresses:     []string{"gopher (a] golang.org"},
   1007 			IPAddresses:        []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
   1008 		}
   1009 
   1010 		derBytes, err := CreateCertificateRequest(random, &template, test.priv)
   1011 		if err != nil {
   1012 			t.Errorf("%s: failed to create certificate request: %s", test.name, err)
   1013 			continue
   1014 		}
   1015 
   1016 		out, err := ParseCertificateRequest(derBytes)
   1017 		if err != nil {
   1018 			t.Errorf("%s: failed to create certificate request: %s", test.name, err)
   1019 			continue
   1020 		}
   1021 
   1022 		err = out.CheckSignature()
   1023 		if err != nil {
   1024 			t.Errorf("%s: failed to check certificate request signature: %s", test.name, err)
   1025 			continue
   1026 		}
   1027 
   1028 		if out.Subject.CommonName != template.Subject.CommonName {
   1029 			t.Errorf("%s: output subject common name and template subject common name don't match", test.name)
   1030 		} else if len(out.Subject.Organization) != len(template.Subject.Organization) {
   1031 			t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name)
   1032 		} else if len(out.DNSNames) != len(template.DNSNames) {
   1033 			t.Errorf("%s: output DNS names and template DNS names don't match", test.name)
   1034 		} else if len(out.EmailAddresses) != len(template.EmailAddresses) {
   1035 			t.Errorf("%s: output email addresses and template email addresses don't match", test.name)
   1036 		} else if len(out.IPAddresses) != len(template.IPAddresses) {
   1037 			t.Errorf("%s: output IP addresses and template IP addresses names don't match", test.name)
   1038 		}
   1039 	}
   1040 }
   1041 
   1042 func marshalAndParseCSR(t *testing.T, template *CertificateRequest) *CertificateRequest {
   1043 	derBytes, err := CreateCertificateRequest(rand.Reader, template, testPrivateKey)
   1044 	if err != nil {
   1045 		t.Fatal(err)
   1046 	}
   1047 
   1048 	csr, err := ParseCertificateRequest(derBytes)
   1049 	if err != nil {
   1050 		t.Fatal(err)
   1051 	}
   1052 
   1053 	return csr
   1054 }
   1055 
   1056 func TestCertificateRequestOverrides(t *testing.T) {
   1057 	sanContents, err := marshalSANs([]string{"foo.example.com"}, nil, nil)
   1058 	if err != nil {
   1059 		t.Fatal(err)
   1060 	}
   1061 
   1062 	template := CertificateRequest{
   1063 		Subject: pkix.Name{
   1064 			CommonName:   "test.example.com",
   1065 			Organization: []string{" Acme Co"},
   1066 		},
   1067 		DNSNames: []string{"test.example.com"},
   1068 
   1069 		// An explicit extension should override the DNSNames from the
   1070 		// template.
   1071 		ExtraExtensions: []pkix.Extension{
   1072 			{
   1073 				Id:    oidExtensionSubjectAltName,
   1074 				Value: sanContents,
   1075 			},
   1076 		},
   1077 	}
   1078 
   1079 	csr := marshalAndParseCSR(t, &template)
   1080 
   1081 	if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo.example.com" {
   1082 		t.Errorf("Extension did not override template. Got %v\n", csr.DNSNames)
   1083 	}
   1084 
   1085 	// If there is already an attribute with X.509 extensions then the
   1086 	// extra extensions should be added to it rather than creating a CSR
   1087 	// with two extension attributes.
   1088 
   1089 	template.Attributes = []pkix.AttributeTypeAndValueSET{
   1090 		{
   1091 			Type: oidExtensionRequest,
   1092 			Value: [][]pkix.AttributeTypeAndValue{
   1093 				{
   1094 					{
   1095 						Type:  oidExtensionAuthorityInfoAccess,
   1096 						Value: []byte("foo"),
   1097 					},
   1098 				},
   1099 			},
   1100 		},
   1101 	}
   1102 
   1103 	csr = marshalAndParseCSR(t, &template)
   1104 	if l := len(csr.Attributes); l != 1 {
   1105 		t.Errorf("incorrect number of attributes: %d\n", l)
   1106 	}
   1107 
   1108 	if !csr.Attributes[0].Type.Equal(oidExtensionRequest) ||
   1109 		len(csr.Attributes[0].Value) != 1 ||
   1110 		len(csr.Attributes[0].Value[0]) != 2 {
   1111 		t.Errorf("bad attributes: %#v\n", csr.Attributes)
   1112 	}
   1113 
   1114 	sanContents2, err := marshalSANs([]string{"foo2.example.com"}, nil, nil)
   1115 	if err != nil {
   1116 		t.Fatal(err)
   1117 	}
   1118 
   1119 	// Extensions in Attributes should override those in ExtraExtensions.
   1120 	template.Attributes[0].Value[0] = append(template.Attributes[0].Value[0], pkix.AttributeTypeAndValue{
   1121 		Type:  oidExtensionSubjectAltName,
   1122 		Value: sanContents2,
   1123 	})
   1124 
   1125 	csr = marshalAndParseCSR(t, &template)
   1126 
   1127 	if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo2.example.com" {
   1128 		t.Errorf("Attributes did not override ExtraExtensions. Got %v\n", csr.DNSNames)
   1129 	}
   1130 }
   1131 
   1132 func TestParseCertificateRequest(t *testing.T) {
   1133 	for _, csrBase64 := range csrBase64Array {
   1134 		csrBytes := fromBase64(csrBase64)
   1135 		csr, err := ParseCertificateRequest(csrBytes)
   1136 		if err != nil {
   1137 			t.Fatalf("failed to parse CSR: %s", err)
   1138 		}
   1139 
   1140 		if len(csr.EmailAddresses) != 1 || csr.EmailAddresses[0] != "gopher (a] golang.org" {
   1141 			t.Errorf("incorrect email addresses found: %v", csr.EmailAddresses)
   1142 		}
   1143 
   1144 		if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "test.example.com" {
   1145 			t.Errorf("incorrect DNS names found: %v", csr.DNSNames)
   1146 		}
   1147 
   1148 		if len(csr.Subject.Country) != 1 || csr.Subject.Country[0] != "AU" {
   1149 			t.Errorf("incorrect Subject name: %v", csr.Subject)
   1150 		}
   1151 
   1152 		found := false
   1153 		for _, e := range csr.Extensions {
   1154 			if e.Id.Equal(oidExtensionBasicConstraints) {
   1155 				found = true
   1156 				break
   1157 			}
   1158 		}
   1159 		if !found {
   1160 			t.Errorf("basic constraints extension not found in CSR")
   1161 		}
   1162 	}
   1163 }
   1164 
   1165 func TestCriticalFlagInCSRRequestedExtensions(t *testing.T) {
   1166 	// This CSR contains an extension request where the extensions have a
   1167 	// critical flag in them. In the past we failed to handle this.
   1168 	const csrBase64 = "MIICrTCCAZUCAQIwMzEgMB4GA1UEAwwXU0NFUCBDQSBmb3IgRGV2ZWxlciBTcmwxDzANBgNVBAsMBjQzNTk3MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALFMAJ7Zy9YyfgbNlbUWAW0LalNRMPs7aXmLANsCpjhnw3lLlfDPaLeWyKh1nK5I5ojaJOW6KIOSAcJkDUe3rrE0wR0RVt3UxArqs0R/ND3u5Q+bDQY2X1HAFUHzUzcdm5JRAIA355v90teMckaWAIlkRQjDE22Lzc6NAl64KOd1rqOUNj8+PfX6fSo20jm94Pp1+a6mfk3G/RUWVuSm7owO5DZI/Fsi2ijdmb4NUar6K/bDKYTrDFkzcqAyMfP3TitUtBp19Mp3B1yAlHjlbp/r5fSSXfOGHZdgIvp0WkLuK2u5eQrX5l7HMB/5epgUs3HQxKY6ljhh5wAjDwz//LsCAwEAAaA1MDMGCSqGSIb3DQEJDjEmMCQwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAoQwDQYJKoZIhvcNAQEFBQADggEBAAMq3bxJSPQEgzLYR/yaVvgjCDrc3zUbIwdOis6Go06Q4RnjH5yRaSZAqZQTDsPurQcnz2I39VMGEiSkFJFavf4QHIZ7QFLkyXadMtALc87tm17Ej719SbHcBSSZayR9VYJUNXRLayI6HvyUrmqcMKh+iX3WY3ICr59/wlM0tYa8DYN4yzmOa2Onb29gy3YlaF5A2AKAMmk003cRT9gY26mjpv7d21czOSSeNyVIoZ04IR9ee71vWTMdv0hu/af5kSjQ+ZG5/Qgc0+mnECLz/1gtxt1srLYbtYQ/qAY8oX1DCSGFS61tN/vl+4cxGMD/VGcGzADRLRHSlVqy2Qgss6Q="
   1169 
   1170 	csrBytes := fromBase64(csrBase64)
   1171 	csr, err := ParseCertificateRequest(csrBytes)
   1172 	if err != nil {
   1173 		t.Fatalf("failed to parse CSR: %s", err)
   1174 	}
   1175 
   1176 	expected := []struct {
   1177 		Id    asn1.ObjectIdentifier
   1178 		Value []byte
   1179 	}{
   1180 		{oidExtensionBasicConstraints, fromBase64("MAYBAf8CAQA=")},
   1181 		{oidExtensionKeyUsage, fromBase64("AwIChA==")},
   1182 	}
   1183 
   1184 	if n := len(csr.Extensions); n != len(expected) {
   1185 		t.Fatalf("expected to find %d extensions but found %d", len(expected), n)
   1186 	}
   1187 
   1188 	for i, extension := range csr.Extensions {
   1189 		if !extension.Id.Equal(expected[i].Id) {
   1190 			t.Fatalf("extension #%d has unexpected type %v (expected %v)", i, extension.Id, expected[i].Id)
   1191 		}
   1192 
   1193 		if !bytes.Equal(extension.Value, expected[i].Value) {
   1194 			t.Fatalf("extension #%d has unexpected contents %x (expected %x)", i, extension.Value, expected[i].Value)
   1195 		}
   1196 	}
   1197 }
   1198 
   1199 // serialiseAndParse generates a self-signed certificate from template and
   1200 // returns a parsed version of it.
   1201 func serialiseAndParse(t *testing.T, template *Certificate) *Certificate {
   1202 	derBytes, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey)
   1203 	if err != nil {
   1204 		t.Fatalf("failed to create certificate: %s", err)
   1205 		return nil
   1206 	}
   1207 
   1208 	cert, err := ParseCertificate(derBytes)
   1209 	if err != nil {
   1210 		t.Fatalf("failed to parse certificate: %s", err)
   1211 		return nil
   1212 	}
   1213 
   1214 	return cert
   1215 }
   1216 
   1217 func TestMaxPathLen(t *testing.T) {
   1218 	template := &Certificate{
   1219 		SerialNumber: big.NewInt(1),
   1220 		Subject: pkix.Name{
   1221 			CommonName: " Acme Co",
   1222 		},
   1223 		NotBefore: time.Unix(1000, 0),
   1224 		NotAfter:  time.Unix(100000, 0),
   1225 
   1226 		BasicConstraintsValid: true,
   1227 		IsCA: true,
   1228 	}
   1229 
   1230 	cert1 := serialiseAndParse(t, template)
   1231 	if m := cert1.MaxPathLen; m != -1 {
   1232 		t.Errorf("Omitting MaxPathLen didn't turn into -1, got %d", m)
   1233 	}
   1234 	if cert1.MaxPathLenZero {
   1235 		t.Errorf("Omitting MaxPathLen resulted in MaxPathLenZero")
   1236 	}
   1237 
   1238 	template.MaxPathLen = 1
   1239 	cert2 := serialiseAndParse(t, template)
   1240 	if m := cert2.MaxPathLen; m != 1 {
   1241 		t.Errorf("Setting MaxPathLen didn't work. Got %d but set 1", m)
   1242 	}
   1243 	if cert2.MaxPathLenZero {
   1244 		t.Errorf("Setting MaxPathLen resulted in MaxPathLenZero")
   1245 	}
   1246 
   1247 	template.MaxPathLen = 0
   1248 	template.MaxPathLenZero = true
   1249 	cert3 := serialiseAndParse(t, template)
   1250 	if m := cert3.MaxPathLen; m != 0 {
   1251 		t.Errorf("Setting MaxPathLenZero didn't work, got %d", m)
   1252 	}
   1253 	if !cert3.MaxPathLenZero {
   1254 		t.Errorf("Setting MaxPathLen to zero didn't result in MaxPathLenZero")
   1255 	}
   1256 }
   1257 
   1258 func TestNoAuthorityKeyIdInSelfSignedCert(t *testing.T) {
   1259 	template := &Certificate{
   1260 		SerialNumber: big.NewInt(1),
   1261 		Subject: pkix.Name{
   1262 			CommonName: " Acme Co",
   1263 		},
   1264 		NotBefore: time.Unix(1000, 0),
   1265 		NotAfter:  time.Unix(100000, 0),
   1266 
   1267 		BasicConstraintsValid: true,
   1268 		IsCA:         true,
   1269 		SubjectKeyId: []byte{1, 2, 3, 4},
   1270 	}
   1271 
   1272 	if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) != 0 {
   1273 		t.Fatalf("self-signed certificate contained default authority key id")
   1274 	}
   1275 
   1276 	template.AuthorityKeyId = []byte{1, 2, 3, 4}
   1277 	if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) == 0 {
   1278 		t.Fatalf("self-signed certificate erased explicit authority key id")
   1279 	}
   1280 }
   1281 
   1282 func TestASN1BitLength(t *testing.T) {
   1283 	tests := []struct {
   1284 		bytes  []byte
   1285 		bitLen int
   1286 	}{
   1287 		{nil, 0},
   1288 		{[]byte{0x00}, 0},
   1289 		{[]byte{0x00, 0x00}, 0},
   1290 		{[]byte{0xf0}, 4},
   1291 		{[]byte{0x88}, 5},
   1292 		{[]byte{0xff}, 8},
   1293 		{[]byte{0xff, 0x80}, 9},
   1294 		{[]byte{0xff, 0x81}, 16},
   1295 	}
   1296 
   1297 	for i, test := range tests {
   1298 		if got := asn1BitLength(test.bytes); got != test.bitLen {
   1299 			t.Errorf("#%d: calculated bit-length of %d for %x, wanted %d", i, got, test.bytes, test.bitLen)
   1300 		}
   1301 	}
   1302 }
   1303 
   1304 func TestVerifyEmptyCertificate(t *testing.T) {
   1305 	if _, err := new(Certificate).Verify(VerifyOptions{}); err != errNotParsed {
   1306 		t.Errorf("Verifying empty certificate resulted in unexpected error: %q (wanted %q)", err, errNotParsed)
   1307 	}
   1308 }
   1309 
   1310 func TestInsecureAlgorithmErrorString(t *testing.T) {
   1311 	tests := []struct {
   1312 		sa   SignatureAlgorithm
   1313 		want string
   1314 	}{
   1315 		{MD2WithRSA, "x509: cannot verify signature: insecure algorithm MD2-RSA"},
   1316 		{-1, "x509: cannot verify signature: insecure algorithm -1"},
   1317 		{0, "x509: cannot verify signature: insecure algorithm 0"},
   1318 		{9999, "x509: cannot verify signature: insecure algorithm 9999"},
   1319 	}
   1320 	for i, tt := range tests {
   1321 		if got := fmt.Sprint(InsecureAlgorithmError(tt.sa)); got != tt.want {
   1322 			t.Errorf("%d. mismatch.\n got: %s\nwant: %s\n", i, got, tt.want)
   1323 		}
   1324 	}
   1325 }
   1326 
   1327 // These CSR was generated with OpenSSL:
   1328 //  openssl req -out CSR.csr -new -sha256 -nodes -keyout privateKey.key -config openssl.cnf
   1329 //
   1330 // With openssl.cnf containing the following sections:
   1331 //   [ v3_req ]
   1332 //   basicConstraints = CA:FALSE
   1333 //   keyUsage = nonRepudiation, digitalSignature, keyEncipherment
   1334 //   subjectAltName = email:gopher (a] golang.org,DNS:test.example.com
   1335 //   [ req_attributes ]
   1336 //   challengePassword = ignored challenge
   1337 //   unstructuredName  = ignored unstructured name
   1338 var csrBase64Array = [...]string{
   1339 	// Just [ v3_req ]
   1340 	"MIIDHDCCAgQCAQAwfjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEUMBIGA1UEAwwLQ29tbW9uIE5hbWUxITAfBgkqhkiG9w0BCQEWEnRlc3RAZW1haWwuYWRkcmVzczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK1GY4YFx2ujlZEOJxQVYmsjUnLsd5nFVnNpLE4cV+77sgv9NPNlB8uhn3MXt5leD34rm/2BisCHOifPucYlSrszo2beuKhvwn4+2FxDmWtBEMu/QA16L5IvoOfYZm/gJTsPwKDqvaR0tTU67a9OtxwNTBMI56YKtmwd/o8d3hYv9cg+9ZGAZ/gKONcg/OWYx/XRh6bd0g8DMbCikpWgXKDsvvK1Nk+VtkDO1JxuBaj4Lz/p/MifTfnHoqHxWOWl4EaTs4Ychxsv34/rSj1KD1tJqorIv5Xv2aqv4sjxfbrYzX4kvS5SC1goIovLnhj5UjmQ3Qy8u65eow/LLWw+YFcCAwEAAaBZMFcGCSqGSIb3DQEJDjFKMEgwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwLgYDVR0RBCcwJYERZ29waGVyQGdvbGFuZy5vcmeCEHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEBAB6VPMRrchvNW61Tokyq3ZvO6/NoGIbuwUn54q6l5VZW0Ep5Nq8juhegSSnaJ0jrovmUgKDN9vEo2KxuAtwG6udS6Ami3zP+hRd4k9Q8djJPb78nrjzWiindLK5Fps9U5mMoi1ER8ViveyAOTfnZt/jsKUaRsscY2FzE9t9/o5moE6LTcHUS4Ap1eheR+J72WOnQYn3cifYaemsA9MJuLko+kQ6xseqttbh9zjqd9fiCSh/LNkzos9c+mg2yMADitaZinAh+HZi50ooEbjaT3erNq9O6RqwJlgD00g6MQdoz9bTAryCU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XHdL5UfUbiJxx299CHgyBRL+hBUIPfz8p+ZgamyAuDLfnj54zzcRVyLlrmMLNPZNll1Q70RxoU6uWvLH8wB8vQe3Q/guSGubLyLRTUQVPh+dw1L4t8MKFWfX/48jwRM4gIRHFHPeAAE9D9YAoqdIvj/iFm/eQ++7DP8MDwOZWsXeB6jjwHuLmkQ==",
   1343 }
   1344 
   1345 var md5cert = `
   1346 -----BEGIN CERTIFICATE-----
   1347 MIIB4TCCAUoCCQCfmw3vMgPS5TANBgkqhkiG9w0BAQQFADA1MQswCQYDVQQGEwJB
   1348 VTETMBEGA1UECBMKU29tZS1TdGF0ZTERMA8GA1UEChMITUQ1IEluYy4wHhcNMTUx
   1349 MjAzMTkyOTMyWhcNMjkwODEyMTkyOTMyWjA1MQswCQYDVQQGEwJBVTETMBEGA1UE
   1350 CBMKU29tZS1TdGF0ZTERMA8GA1UEChMITUQ1IEluYy4wgZ8wDQYJKoZIhvcNAQEB
   1351 BQADgY0AMIGJAoGBANrq2nhLQj5mlXbpVX3QUPhfEm/vdEqPkoWtR/jRZIWm4WGf
   1352 Wpq/LKHJx2Pqwn+t117syN8l4U5unyAi1BJSXjBwPZNd7dXjcuJ+bRLV7FZ/iuvs
   1353 cfYyQQFTxan4TaJMd0x1HoNDbNbjHa02IyjjYE/r3mb/PIg+J2t5AZEh80lPAgMB
   1354 AAEwDQYJKoZIhvcNAQEEBQADgYEAjGzp3K3ey/YfKHohf33yHHWd695HQxDAP+wY
   1355 cs9/TAyLR+gJzJP7d18EcDDLJWVi7bhfa4EAD86di05azOh9kWSn4b3o9QYRGCSw
   1356 GNnI3Zk0cwNKA49hZntKKiy22DhRk7JAHF01d6Bu3KkHkmENrtJ+zj/+159WAnUa
   1357 qViorq4=
   1358 -----END CERTIFICATE-----
   1359 `
   1360 
   1361 func TestMD5(t *testing.T) {
   1362 	pemBlock, _ := pem.Decode([]byte(md5cert))
   1363 	cert, err := ParseCertificate(pemBlock.Bytes)
   1364 	if err != nil {
   1365 		t.Fatalf("failed to parse certificate: %s", err)
   1366 	}
   1367 	if sa := cert.SignatureAlgorithm; sa != MD5WithRSA {
   1368 		t.Errorf("signature algorithm is %v, want %v", sa, MD5WithRSA)
   1369 	}
   1370 	if err = cert.CheckSignatureFrom(cert); err == nil {
   1371 		t.Fatalf("certificate verification succeeded incorrectly")
   1372 	}
   1373 	if _, ok := err.(InsecureAlgorithmError); !ok {
   1374 		t.Fatalf("certificate verification returned %v (%T), wanted InsecureAlgorithmError", err, err)
   1375 	}
   1376 }
   1377 
   1378 // certMissingRSANULL contains an RSA public key where the AlgorithmIdentifer
   1379 // parameters are omitted rather than being an ASN.1 NULL.
   1380 const certMissingRSANULL = `
   1381 -----BEGIN CERTIFICATE-----
   1382 MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD
   1383 bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4
   1384 MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc
   1385 MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG
   1386 hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE
   1387 ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e
   1388 E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw
   1389 DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A
   1390 p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4
   1391 hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE
   1392 GFGNEH5PlGffo05wc46QkYU=
   1393 -----END CERTIFICATE-----`
   1394 
   1395 func TestRSAMissingNULLParameters(t *testing.T) {
   1396 	block, _ := pem.Decode([]byte(certMissingRSANULL))
   1397 	if _, err := ParseCertificate(block.Bytes); err == nil {
   1398 		t.Error("unexpected success when parsing certificate with missing RSA NULL parameter")
   1399 	} else if !strings.Contains(err.Error(), "missing NULL") {
   1400 		t.Errorf("unrecognised error when parsing certificate with missing RSA NULL parameter: %s", err)
   1401 	}
   1402 }
   1403 
   1404 const certISOOID = `
   1405 -----BEGIN CERTIFICATE-----
   1406 MIIB5TCCAVKgAwIBAgIQtwyL3RPWV7dJQp34HwZG9DAJBgUrDgMCHQUAMBExDzAN
   1407 BgNVBAMTBm15dGVzdDAeFw0xNjA4MDkyMjExMDVaFw0zOTEyMzEyMzU5NTlaMBEx
   1408 DzANBgNVBAMTBm15dGVzdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArzIH
   1409 GsyDB3ohIGkkvijF2PTRUX1bvOtY1eUUpjwHyu0twpAKSuaQv2Ha+/63+aHe8O86
   1410 BT+98wjXFX6RFSagtAujo80rIF2dSm33BGt18pDN8v6zp93dnAm0jRaSQrHJ75xw
   1411 5O+S1oEYR1LtUoFJy6qB104j6aINBAgOiLIKiMkCAwEAAaNGMEQwQgYDVR0BBDsw
   1412 OYAQVuYVQ/WDjdGSkZRlTtJDNKETMBExDzANBgNVBAMTBm15dGVzdIIQtwyL3RPW
   1413 V7dJQp34HwZG9DAJBgUrDgMCHQUAA4GBABngrSkH7vG5lY4sa4AZF59lAAXqBVJE
   1414 J4TBiKC62hCdZv18rBleP6ETfhbPg7pTs8p4ebQbpmtNxRS9Lw3MzQ8Ya5Ybwzj2
   1415 NwBSyCtCQl7mrEg4nJqJl4A2EUhnET/oVxU0oTV/SZ3ziGXcY1oG1s6vidV7TZTu
   1416 MCRtdSdaM7g3
   1417 -----END CERTIFICATE-----`
   1418 
   1419 func TestISOOIDInCertificate(t *testing.T) {
   1420 	block, _ := pem.Decode([]byte(certISOOID))
   1421 	if cert, err := ParseCertificate(block.Bytes); err != nil {
   1422 		t.Errorf("certificate with ISO OID failed to parse: %s", err)
   1423 	} else if cert.SignatureAlgorithm == UnknownSignatureAlgorithm {
   1424 		t.Errorf("ISO OID not recognised in certificate")
   1425 	}
   1426 }
   1427 
   1428 // certMultipleRDN contains a RelativeDistinguishedName with two elements (the
   1429 // common name and serial number). This particular certificate was the first
   1430 // such certificate in the Pilot Certificate Transparency log.
   1431 const certMultipleRDN = `
   1432 -----BEGIN CERTIFICATE-----
   1433 MIIFRzCCBC+gAwIBAgIEOl59NTANBgkqhkiG9w0BAQUFADA9MQswCQYDVQQGEwJz
   1434 aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMREwDwYDVQQLEwhzaWdvdi1j
   1435 YTAeFw0xMjExMTYxMDUyNTdaFw0xNzExMTYxMjQ5MDVaMIGLMQswCQYDVQQGEwJz
   1436 aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMRkwFwYDVQQLExB3ZWItY2Vy
   1437 dGlmaWNhdGVzMRAwDgYDVQQLEwdTZXJ2ZXJzMTIwFAYDVQQFEw0xMjM2NDg0MDEw
   1438 MDEwMBoGA1UEAxMTZXBvcnRhbC5tc3MuZWR1cy5zaTCCASIwDQYJKoZIhvcNAQEB
   1439 BQADggEPADCCAQoCggEBAMrNkZH9MPuBTjMGNk3sJX8V+CkFx/4ru7RTlLS6dlYM
   1440 098dtSfJ3s2w0p/1NB9UmR8j0yS0Kg6yoZ3ShsSO4DWBtcQD8820a6BYwqxxQTNf
   1441 HSRZOc+N/4TQrvmK6t4k9Aw+YEYTMrWOU4UTeyhDeCcUsBdh7HjfWsVaqNky+2sv
   1442 oic3zP5gF+2QfPkvOoHT3FLR8olNhViIE6Kk3eFIEs4dkq/ZzlYdLb8pHQoj/sGI
   1443 zFmA5AFvm1HURqOmJriFjBwaCtn8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jqPE5nehwYUPVu9R
   1459 uH6/skk4OEKcfOtN0hCnISOVuKYyS4ANARWRG5VGHIH06z3lGUVARFRJ61gtAprd
   1460 La+fgSS+LVZ+kU2TkeoWAKvGq8MAgDq4D4Xqwekg7WKFeuyusi/NI5rm40XgjBMF
   1461 DF72IUofoVt7wo0=
   1462 -----END CERTIFICATE-----`
   1463 
   1464 func TestMultipleRDN(t *testing.T) {
   1465 	block, _ := pem.Decode([]byte(certMultipleRDN))
   1466 	cert, err := ParseCertificate(block.Bytes)
   1467 	if err != nil {
   1468 		t.Fatalf("certificate with two elements in an RDN failed to parse: %v", err)
   1469 	}
   1470 
   1471 	if want := "eportal.mss.edus.si"; cert.Subject.CommonName != want {
   1472 		t.Errorf("got common name of %q, but want %q", cert.Subject.CommonName, want)
   1473 	}
   1474 
   1475 	if want := "1236484010010"; cert.Subject.SerialNumber != want {
   1476 		t.Errorf("got serial number of %q, but want %q", cert.Subject.SerialNumber, want)
   1477 	}
   1478 }
   1479 
   1480 func TestSystemCertPool(t *testing.T) {
   1481 	if runtime.GOOS == "windows" {
   1482 		t.Skip("not implemented on Windows; Issue 16736, 18609")
   1483 	}
   1484 	_, err := SystemCertPool()
   1485 	if err != nil {
   1486 		t.Fatal(err)
   1487 	}
   1488 }
   1489