github.com/mattn/go@v0.0.0-20171011075504-07f7db3ea99f/src/crypto/x509/x509_test.go (about)

     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  func TestMismatchedSignatureAlgorithm(t *testing.T) {
   292  	der, _ := pem.Decode([]byte(rsaPSSSelfSignedPEM))
   293  	if der == nil {
   294  		t.Fatal("Failed to find PEM block")
   295  	}
   296  
   297  	cert, err := ParseCertificate(der.Bytes)
   298  	if err != nil {
   299  		t.Fatal(err)
   300  	}
   301  
   302  	if err = cert.CheckSignature(ECDSAWithSHA256, nil, nil); err == nil {
   303  		t.Fatal("CheckSignature unexpectedly return no error")
   304  	}
   305  
   306  	const expectedSubstring = " but have public key of type "
   307  	if !strings.Contains(err.Error(), expectedSubstring) {
   308  		t.Errorf("Expected error containing %q, but got %q", expectedSubstring, err)
   309  	}
   310  }
   311  
   312  var certBytes = "308203223082028ba00302010202106edf0d9499fd4533dd1297fc42a93be1300d06092a864886" +
   313  	"f70d0101050500304c310b3009060355040613025a4131253023060355040a131c546861777465" +
   314  	"20436f6e73756c74696e67202850747929204c74642e311630140603550403130d546861777465" +
   315  	"20534743204341301e170d3039303332353136343932395a170d3130303332353136343932395a" +
   316  	"3069310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630" +
   317  	"140603550407130d4d6f756e7461696e205669657731133011060355040a130a476f6f676c6520" +
   318  	"496e63311830160603550403130f6d61696c2e676f6f676c652e636f6d30819f300d06092a8648" +
   319  	"86f70d010101050003818d0030818902818100c5d6f892fccaf5614b064149e80a2c9581a218ef" +
   320  	"41ec35bd7a58125ae76f9ea54ddc893abbeb029f6b73616bf0ffd868791fba7af9c4aebf3706ba" +
   321  	"3eeaeed27435b4ddcfb157c05f351d66aa87fee0de072d66d773affbd36ab78bef090e0cc861a9" +
   322  	"03ac90dd98b51c9c41566c017f0beec3bff391051ffba0f5cc6850ad2a590203010001a381e730" +
   323  	"81e430280603551d250421301f06082b0601050507030106082b06010505070302060960864801" +
   324  	"86f842040130360603551d1f042f302d302ba029a0278625687474703a2f2f63726c2e74686177" +
   325  	"74652e636f6d2f54686177746553474343412e63726c307206082b060105050701010466306430" +
   326  	"2206082b060105050730018616687474703a2f2f6f6373702e7468617774652e636f6d303e0608" +
   327  	"2b060105050730028632687474703a2f2f7777772e7468617774652e636f6d2f7265706f736974" +
   328  	"6f72792f5468617774655f5347435f43412e637274300c0603551d130101ff04023000300d0609" +
   329  	"2a864886f70d01010505000381810062f1f3050ebc105e497c7aedf87e24d2f4a986bb3b837bd1" +
   330  	"9b91ebcad98b065992f6bd2b49b7d6d3cb2e427a99d606c7b1d46352527fac39e6a8b6726de5bf" +
   331  	"70212a52cba07634a5e332011bd1868e78eb5e3c93cf03072276786f207494feaa0ed9d53b2110" +
   332  	"a76571f90209cdae884385c882587030ee15f33d761e2e45a6bc308203233082028ca003020102" +
   333  	"020430000002300d06092a864886f70d0101050500305f310b3009060355040613025553311730" +
   334  	"15060355040a130e566572695369676e2c20496e632e31373035060355040b132e436c61737320" +
   335  	"33205075626c6963205072696d6172792043657274696669636174696f6e20417574686f726974" +
   336  	"79301e170d3034303531333030303030305a170d3134303531323233353935395a304c310b3009" +
   337  	"060355040613025a4131253023060355040a131c54686177746520436f6e73756c74696e672028" +
   338  	"50747929204c74642e311630140603550403130d5468617774652053474320434130819f300d06" +
   339  	"092a864886f70d010101050003818d0030818902818100d4d367d08d157faecd31fe7d1d91a13f" +
   340  	"0b713cacccc864fb63fc324b0794bd6f80ba2fe10493c033fc093323e90b742b71c403c6d2cde2" +
   341  	"2ff50963cdff48a500bfe0e7f388b72d32de9836e60aad007bc4644a3b847503f270927d0e62f5" +
   342  	"21ab693684317590f8bfc76c881b06957cc9e5a8de75a12c7a68dfd5ca1c875860190203010001" +
   343  	"a381fe3081fb30120603551d130101ff040830060101ff020100300b0603551d0f040403020106" +
   344  	"301106096086480186f842010104040302010630280603551d110421301fa41d301b3119301706" +
   345  	"035504031310507269766174654c6162656c332d313530310603551d1f042a30283026a024a022" +
   346  	"8620687474703a2f2f63726c2e766572697369676e2e636f6d2f706361332e63726c303206082b" +
   347  	"0601050507010104263024302206082b060105050730018616687474703a2f2f6f6373702e7468" +
   348  	"617774652e636f6d30340603551d25042d302b06082b0601050507030106082b06010505070302" +
   349  	"06096086480186f8420401060a6086480186f845010801300d06092a864886f70d010105050003" +
   350  	"81810055ac63eadea1ddd2905f9f0bce76be13518f93d9052bc81b774bad6950a1eededcfddb07" +
   351  	"e9e83994dcab72792f06bfab8170c4a8edea5334edef1e53d906c7562bd15cf4d18a8eb42bb137" +
   352  	"9048084225c53e8acb7feb6f04d16dc574a2f7a27c7b603c77cd0ece48027f012fb69b37e02a2a" +
   353  	"36dcd585d6ace53f546f961e05af"
   354  
   355  func TestCreateSelfSignedCertificate(t *testing.T) {
   356  	random := rand.Reader
   357  
   358  	ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   359  	if err != nil {
   360  		t.Fatalf("Failed to generate ECDSA key: %s", err)
   361  	}
   362  
   363  	tests := []struct {
   364  		name      string
   365  		pub, priv interface{}
   366  		checkSig  bool
   367  		sigAlgo   SignatureAlgorithm
   368  	}{
   369  		{"RSA/RSA", &testPrivateKey.PublicKey, testPrivateKey, true, SHA1WithRSA},
   370  		{"RSA/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
   371  		{"ECDSA/RSA", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSA},
   372  		{"ECDSA/ECDSA", &ecdsaPriv.PublicKey, ecdsaPriv, true, ECDSAWithSHA1},
   373  		{"RSAPSS/RSAPSS", &testPrivateKey.PublicKey, testPrivateKey, true, SHA256WithRSAPSS},
   374  		{"ECDSA/RSAPSS", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSAPSS},
   375  		{"RSAPSS/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
   376  	}
   377  
   378  	testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth}
   379  	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
   380  	extraExtensionData := []byte("extra extension")
   381  
   382  	for _, test := range tests {
   383  		commonName := "test.example.com"
   384  		template := Certificate{
   385  			// SerialNumber is negative to ensure that negative
   386  			// values are parsed. This is due to the prevalence of
   387  			// buggy code that produces certificates with negative
   388  			// serial numbers.
   389  			SerialNumber: big.NewInt(-1),
   390  			Subject: pkix.Name{
   391  				CommonName:   commonName,
   392  				Organization: []string{"Σ Acme Co"},
   393  				Country:      []string{"US"},
   394  				ExtraNames: []pkix.AttributeTypeAndValue{
   395  					{
   396  						Type:  []int{2, 5, 4, 42},
   397  						Value: "Gopher",
   398  					},
   399  					// This should override the Country, above.
   400  					{
   401  						Type:  []int{2, 5, 4, 6},
   402  						Value: "NL",
   403  					},
   404  				},
   405  			},
   406  			NotBefore: time.Unix(1000, 0),
   407  			NotAfter:  time.Unix(100000, 0),
   408  
   409  			SignatureAlgorithm: test.sigAlgo,
   410  
   411  			SubjectKeyId: []byte{1, 2, 3, 4},
   412  			KeyUsage:     KeyUsageCertSign,
   413  
   414  			ExtKeyUsage:        testExtKeyUsage,
   415  			UnknownExtKeyUsage: testUnknownExtKeyUsage,
   416  
   417  			BasicConstraintsValid: true,
   418  			IsCA: true,
   419  
   420  			OCSPServer:            []string{"http://ocsp.example.com"},
   421  			IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
   422  
   423  			DNSNames:       []string{"test.example.com"},
   424  			EmailAddresses: []string{"gopher@golang.org"},
   425  			IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
   426  
   427  			PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
   428  			PermittedDNSDomains: []string{".example.com", "example.com"},
   429  			ExcludedDNSDomains:  []string{"bar.example.com"},
   430  
   431  			CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
   432  
   433  			ExtraExtensions: []pkix.Extension{
   434  				{
   435  					Id:    []int{1, 2, 3, 4},
   436  					Value: extraExtensionData,
   437  				},
   438  				// This extension should override the SubjectKeyId, above.
   439  				{
   440  					Id:       oidExtensionSubjectKeyId,
   441  					Critical: false,
   442  					Value:    []byte{0x04, 0x04, 4, 3, 2, 1},
   443  				},
   444  			},
   445  		}
   446  
   447  		derBytes, err := CreateCertificate(random, &template, &template, test.pub, test.priv)
   448  		if err != nil {
   449  			t.Errorf("%s: failed to create certificate: %s", test.name, err)
   450  			continue
   451  		}
   452  
   453  		cert, err := ParseCertificate(derBytes)
   454  		if err != nil {
   455  			t.Errorf("%s: failed to parse certificate: %s", test.name, err)
   456  			continue
   457  		}
   458  
   459  		if len(cert.PolicyIdentifiers) != 1 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) {
   460  			t.Errorf("%s: failed to parse policy identifiers: got:%#v want:%#v", test.name, cert.PolicyIdentifiers, template.PolicyIdentifiers)
   461  		}
   462  
   463  		if len(cert.PermittedDNSDomains) != 2 || cert.PermittedDNSDomains[0] != ".example.com" || cert.PermittedDNSDomains[1] != "example.com" {
   464  			t.Errorf("%s: failed to parse name constraints: %#v", test.name, cert.PermittedDNSDomains)
   465  		}
   466  
   467  		if len(cert.ExcludedDNSDomains) != 1 || cert.ExcludedDNSDomains[0] != "bar.example.com" {
   468  			t.Errorf("%s: failed to parse name constraint exclusions: %#v", test.name, cert.ExcludedDNSDomains)
   469  		}
   470  
   471  		if cert.Subject.CommonName != commonName {
   472  			t.Errorf("%s: subject wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Subject.CommonName, commonName)
   473  		}
   474  
   475  		if len(cert.Subject.Country) != 1 || cert.Subject.Country[0] != "NL" {
   476  			t.Errorf("%s: ExtraNames didn't override Country", test.name)
   477  		}
   478  
   479  		found := false
   480  		for _, atv := range cert.Subject.Names {
   481  			if atv.Type.Equal([]int{2, 5, 4, 42}) {
   482  				found = true
   483  				break
   484  			}
   485  		}
   486  		if !found {
   487  			t.Errorf("%s: Names didn't contain oid 2.5.4.42 from ExtraNames", test.name)
   488  		}
   489  
   490  		if cert.Issuer.CommonName != commonName {
   491  			t.Errorf("%s: issuer wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Issuer.CommonName, commonName)
   492  		}
   493  
   494  		if cert.SignatureAlgorithm != test.sigAlgo {
   495  			t.Errorf("%s: SignatureAlgorithm wasn't copied from template. Got %v, want %v", test.name, cert.SignatureAlgorithm, test.sigAlgo)
   496  		}
   497  
   498  		if !reflect.DeepEqual(cert.ExtKeyUsage, testExtKeyUsage) {
   499  			t.Errorf("%s: extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.ExtKeyUsage, testExtKeyUsage)
   500  		}
   501  
   502  		if !reflect.DeepEqual(cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) {
   503  			t.Errorf("%s: unknown extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.UnknownExtKeyUsage, testUnknownExtKeyUsage)
   504  		}
   505  
   506  		if !reflect.DeepEqual(cert.OCSPServer, template.OCSPServer) {
   507  			t.Errorf("%s: OCSP servers differ from template. Got %v, want %v", test.name, cert.OCSPServer, template.OCSPServer)
   508  		}
   509  
   510  		if !reflect.DeepEqual(cert.IssuingCertificateURL, template.IssuingCertificateURL) {
   511  			t.Errorf("%s: Issuing certificate URLs differ from template. Got %v, want %v", test.name, cert.IssuingCertificateURL, template.IssuingCertificateURL)
   512  		}
   513  
   514  		if !reflect.DeepEqual(cert.DNSNames, template.DNSNames) {
   515  			t.Errorf("%s: SAN DNS names differ from template. Got %v, want %v", test.name, cert.DNSNames, template.DNSNames)
   516  		}
   517  
   518  		if !reflect.DeepEqual(cert.EmailAddresses, template.EmailAddresses) {
   519  			t.Errorf("%s: SAN emails differ from template. Got %v, want %v", test.name, cert.EmailAddresses, template.EmailAddresses)
   520  		}
   521  
   522  		if !reflect.DeepEqual(cert.IPAddresses, template.IPAddresses) {
   523  			t.Errorf("%s: SAN IPs differ from template. Got %v, want %v", test.name, cert.IPAddresses, template.IPAddresses)
   524  		}
   525  
   526  		if !reflect.DeepEqual(cert.CRLDistributionPoints, template.CRLDistributionPoints) {
   527  			t.Errorf("%s: CRL distribution points differ from template. Got %v, want %v", test.name, cert.CRLDistributionPoints, template.CRLDistributionPoints)
   528  		}
   529  
   530  		if !bytes.Equal(cert.SubjectKeyId, []byte{4, 3, 2, 1}) {
   531  			t.Errorf("%s: ExtraExtensions didn't override SubjectKeyId", test.name)
   532  		}
   533  
   534  		if !bytes.Contains(derBytes, extraExtensionData) {
   535  			t.Errorf("%s: didn't find extra extension in DER output", test.name)
   536  		}
   537  
   538  		if test.checkSig {
   539  			err = cert.CheckSignatureFrom(cert)
   540  			if err != nil {
   541  				t.Errorf("%s: signature verification failed: %s", test.name, err)
   542  			}
   543  		}
   544  	}
   545  }
   546  
   547  // Self-signed certificate using ECDSA with SHA1 & secp256r1
   548  var ecdsaSHA1CertPem = `
   549  -----BEGIN CERTIFICATE-----
   550  MIICDjCCAbUCCQDF6SfN0nsnrjAJBgcqhkjOPQQBMIGPMQswCQYDVQQGEwJVUzET
   551  MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEVMBMG
   552  A1UECgwMR29vZ2xlLCBJbmMuMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   553  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIwMjAyMDUw
   554  WhcNMjIwNTE4MjAyMDUwWjCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   555  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTATBgNVBAoMDEdvb2dsZSwg
   556  SW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAhBgkqhkiG9w0BCQEWFGdv
   557  bGFuZy1kZXZAZ21haWwuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/Wgn
   558  WQDo5+bz71T0327ERgd5SDDXFbXLpzIZDXTkjpe8QTEbsF+ezsQfrekrpDPC4Cd3
   559  P9LY0tG+aI8IyVKdUjAJBgcqhkjOPQQBA0gAMEUCIGlsqMcRqWVIWTD6wXwe6Jk2
   560  DKxL46r/FLgJYnzBEH99AiEA3fBouObsvV1R3oVkb4BQYnD4/4LeId6lAT43YvyV
   561  a/A=
   562  -----END CERTIFICATE-----
   563  `
   564  
   565  // Self-signed certificate using ECDSA with SHA256 & secp256r1
   566  var ecdsaSHA256p256CertPem = `
   567  -----BEGIN CERTIFICATE-----
   568  MIICDzCCAbYCCQDlsuMWvgQzhTAKBggqhkjOPQQDAjCBjzELMAkGA1UEBhMCVVMx
   569  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTAT
   570  BgNVBAoMDEdvb2dsZSwgSW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAh
   571  BgkqhkiG9w0BCQEWFGdvbGFuZy1kZXZAZ21haWwuY29tMB4XDTEyMDUyMTAwMTkx
   572  NloXDTIyMDUxOTAwMTkxNlowgY8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp
   573  Zm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRUwEwYDVQQKDAxHb29nbGUs
   574  IEluYy4xFzAVBgNVBAMMDnd3dy5nb29nbGUuY29tMSMwIQYJKoZIhvcNAQkBFhRn
   575  b2xhbmctZGV2QGdtYWlsLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPMt
   576  2ErhxAty5EJRu9yM+MTy+hUXm3pdW1ensAv382KoGExSXAFWP7pjJnNtHO+XSwVm
   577  YNtqjcAGFKpweoN//kQwCgYIKoZIzj0EAwIDRwAwRAIgIYSaUA/IB81gjbIw/hUV
   578  70twxJr5EcgOo0hLp3Jm+EYCIFDO3NNcgmURbJ1kfoS3N/0O+irUtoPw38YoNkqJ
   579  h5wi
   580  -----END CERTIFICATE-----
   581  `
   582  
   583  // Self-signed certificate using ECDSA with SHA256 & secp384r1
   584  var ecdsaSHA256p384CertPem = `
   585  -----BEGIN CERTIFICATE-----
   586  MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx
   587  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
   588  BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   589  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0
   590  WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   591  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
   592  SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
   593  YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK
   594  jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze
   595  qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI
   596  zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr
   597  PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh
   598  3yILeYQzllt/g0rKVRk=
   599  -----END CERTIFICATE-----
   600  `
   601  
   602  // Self-signed certificate using ECDSA with SHA384 & secp521r1
   603  var ecdsaSHA384p521CertPem = `
   604  -----BEGIN CERTIFICATE-----
   605  MIICljCCAfcCCQDhp1AFD/ahKjAKBggqhkjOPQQDAzCBjjELMAkGA1UEBhMCVVMx
   606  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
   607  BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   608  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMTUwNDI5
   609  WhcNMjIwNTE5MTUwNDI5WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   610  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
   611  SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
   612  YW5nLWRldkBnbWFpbC5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACqx9Rv
   613  IssRs1LWYcNN+WffwlHw4Tv3y8/LIAA9MF1ZScIonU9nRMxt4a2uGJVCPDw6JHpz
   614  PaYc0E9puLoE9AfKpwFr59Jkot7dBg55SKPEFkddoip/rvmN7NPAWjMBirOwjOkm
   615  8FPthvPhGPqsu9AvgVuHu3PosWiHGNrhh379pva8MzAKBggqhkjOPQQDAwOBjAAw
   616  gYgCQgEHNmswkUdPpHqrVxp9PvLVl+xxPuHBkT+75z9JizyxtqykHQo9Uh6SWCYH
   617  BF9KLolo01wMt8DjoYP5Fb3j5MH7xwJCAbWZzTOp4l4DPkIvAh4LeC4VWbwPPyqh
   618  kBg71w/iEcSY3wUKgHGcJJrObZw7wys91I5kENljqw/Samdr3ka+jBJa
   619  -----END CERTIFICATE-----
   620  `
   621  
   622  var ecdsaTests = []struct {
   623  	sigAlgo SignatureAlgorithm
   624  	pemCert string
   625  }{
   626  	{ECDSAWithSHA1, ecdsaSHA1CertPem},
   627  	{ECDSAWithSHA256, ecdsaSHA256p256CertPem},
   628  	{ECDSAWithSHA256, ecdsaSHA256p384CertPem},
   629  	{ECDSAWithSHA384, ecdsaSHA384p521CertPem},
   630  }
   631  
   632  func TestECDSA(t *testing.T) {
   633  	for i, test := range ecdsaTests {
   634  		pemBlock, _ := pem.Decode([]byte(test.pemCert))
   635  		cert, err := ParseCertificate(pemBlock.Bytes)
   636  		if err != nil {
   637  			t.Errorf("%d: failed to parse certificate: %s", i, err)
   638  			continue
   639  		}
   640  		if sa := cert.SignatureAlgorithm; sa != test.sigAlgo {
   641  			t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo)
   642  		}
   643  		if parsedKey, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok {
   644  			t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey)
   645  		}
   646  		if pka := cert.PublicKeyAlgorithm; pka != ECDSA {
   647  			t.Errorf("%d: public key algorithm is %v, want ECDSA", i, pka)
   648  		}
   649  		if err = cert.CheckSignatureFrom(cert); err != nil {
   650  			t.Errorf("%d: certificate verification failed: %s", i, err)
   651  		}
   652  	}
   653  }
   654  
   655  // Self-signed certificate using DSA with SHA1
   656  var dsaCertPem = `-----BEGIN CERTIFICATE-----
   657  MIIEDTCCA82gAwIBAgIJALHPghaoxeDhMAkGByqGSM44BAMweTELMAkGA1UEBhMC
   658  VVMxCzAJBgNVBAgTAk5DMQ8wDQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2ds
   659  ZSwgSW5jMRIwEAYDVQQDEwlKb24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFs
   660  bGllQGdvb2dsZS5jb20wHhcNMTEwNTE0MDMwMTQ1WhcNMTEwNjEzMDMwMTQ1WjB5
   661  MQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkMxDzANBgNVBAcTBk5ld3RvbjEUMBIG
   662  A1UEChMLR29vZ2xlLCBJbmMxEjAQBgNVBAMTCUpvbiBBbGxpZTEiMCAGCSqGSIb3
   663  DQEJARYTam9uYWxsaWVAZ29vZ2xlLmNvbTCCAbcwggEsBgcqhkjOOAQBMIIBHwKB
   664  gQC8hLUnQ7FpFYu4WXTj6DKvXvz8QrJkNJCVMTpKAT7uBpobk32S5RrPKXocd4gN
   665  8lyGB9ggS03EVlEwXvSmO0DH2MQtke2jl9j1HLydClMf4sbx5V6TV9IFw505U1iW
   666  jL7awRMgxge+FsudtJK254FjMFo03ZnOQ8ZJJ9E6AEDrlwIVAJpnBn9moyP11Ox5
   667  Asc/5dnjb6dPAoGBAJFHd4KVv1iTVCvEG6gGiYop5DJh28hUQcN9kul+2A0yPUSC
   668  X93oN00P8Vh3eYgSaCWZsha7zDG53MrVJ0Zf6v/X/CoZNhLldeNOepivTRAzn+Rz
   669  kKUYy5l1sxYLHQKF0UGNCXfFKZT0PCmgU+PWhYNBBMn6/cIh44vp85ideo5CA4GE
   670  AAKBgFmifCafzeRaohYKXJgMGSEaggCVCRq5xdyDCat+wbOkjC4mfG01/um3G8u5
   671  LxasjlWRKTR/tcAL7t0QuokVyQaYdVypZXNaMtx1db7YBuHjj3aP+8JOQRI9xz8c
   672  bp5NDJ5pISiFOv4p3GZfqZPcqckDt78AtkQrmnal2txhhjF6o4HeMIHbMB0GA1Ud
   673  DgQWBBQVyyr7hO11ZFFpWX50298Sa3V+rzCBqwYDVR0jBIGjMIGggBQVyyr7hO11
   674  ZFFpWX50298Sa3V+r6F9pHsweTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAk5DMQ8w
   675  DQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2dsZSwgSW5jMRIwEAYDVQQDEwlK
   676  b24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFsbGllQGdvb2dsZS5jb22CCQCx
   677  z4IWqMXg4TAMBgNVHRMEBTADAQH/MAkGByqGSM44BAMDLwAwLAIUPtn/5j8Q1jJI
   678  7ggOIsgrhgUdjGQCFCsmDq1H11q9+9Wp9IMeGrTSKHIM
   679  -----END CERTIFICATE-----
   680  `
   681  
   682  func TestParseCertificateWithDsaPublicKey(t *testing.T) {
   683  	expectedKey := &dsa.PublicKey{
   684  		Parameters: dsa.Parameters{
   685  			P: bigFromHexString("00BC84B52743B169158BB85974E3E832AF5EFCFC42B264349095313A4A013EEE069A1B937D92E51ACF297A1C77880DF25C8607D8204B4DC45651305EF4A63B40C7D8C42D91EDA397D8F51CBC9D0A531FE2C6F1E55E9357D205C39D395358968CBEDAC11320C607BE16CB9DB492B6E78163305A34DD99CE43C64927D13A0040EB97"),
   686  			Q: bigFromHexString("009A67067F66A323F5D4EC7902C73FE5D9E36FA74F"),
   687  			G: bigFromHexString("009147778295BF5893542BC41BA806898A29E43261DBC85441C37D92E97ED80D323D44825FDDE8374D0FF15877798812682599B216BBCC31B9DCCAD527465FEAFFD7FC2A193612E575E34E7A98AF4D10339FE47390A518CB9975B3160B1D0285D1418D0977C52994F43C29A053E3D685834104C9FAFDC221E38BE9F3989D7A8E42"),
   688  		},
   689  		Y: bigFromHexString("59A27C269FCDE45AA2160A5C980C19211A820095091AB9C5DC8309AB7EC1B3A48C2E267C6D35FEE9B71BCBB92F16AC8E559129347FB5C00BEEDD10BA8915C90698755CA965735A32DC7575BED806E1E38F768FFBC24E41123DC73F1C6E9E4D0C9E692128853AFE29DC665FA993DCA9C903B7BF00B6442B9A76A5DADC6186317A"),
   690  	}
   691  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   692  	cert, err := ParseCertificate(pemBlock.Bytes)
   693  	if err != nil {
   694  		t.Fatalf("Failed to parse certificate: %s", err)
   695  	}
   696  	if cert.PublicKeyAlgorithm != DSA {
   697  		t.Errorf("Parsed key algorithm was not DSA")
   698  	}
   699  	parsedKey, ok := cert.PublicKey.(*dsa.PublicKey)
   700  	if !ok {
   701  		t.Fatalf("Parsed key was not a DSA key: %s", err)
   702  	}
   703  	if expectedKey.Y.Cmp(parsedKey.Y) != 0 ||
   704  		expectedKey.P.Cmp(parsedKey.P) != 0 ||
   705  		expectedKey.Q.Cmp(parsedKey.Q) != 0 ||
   706  		expectedKey.G.Cmp(parsedKey.G) != 0 {
   707  		t.Fatal("Parsed key differs from expected key")
   708  	}
   709  }
   710  
   711  func TestParseCertificateWithDSASignatureAlgorithm(t *testing.T) {
   712  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   713  	cert, err := ParseCertificate(pemBlock.Bytes)
   714  	if err != nil {
   715  		t.Fatalf("Failed to parse certificate: %s", err)
   716  	}
   717  	if cert.SignatureAlgorithm != DSAWithSHA1 {
   718  		t.Errorf("Parsed signature algorithm was not DSAWithSHA1")
   719  	}
   720  }
   721  
   722  func TestVerifyCertificateWithDSASignature(t *testing.T) {
   723  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   724  	cert, err := ParseCertificate(pemBlock.Bytes)
   725  	if err != nil {
   726  		t.Fatalf("Failed to parse certificate: %s", err)
   727  	}
   728  	// test cert is self-signed
   729  	if err = cert.CheckSignatureFrom(cert); err != nil {
   730  		t.Fatalf("DSA Certificate verification failed: %s", err)
   731  	}
   732  }
   733  
   734  var rsaPSSSelfSignedPEM = `-----BEGIN CERTIFICATE-----
   735  MIIGHjCCA9KgAwIBAgIBdjBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA
   736  oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCASAwbjELMAkGA1UEBhMC
   737  SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
   738  aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
   739  U0NBMB4XDTEzMDUxNDA1MDczMFoXDTI5MDUxNDA1MDczMFowbjELMAkGA1UEBhMC
   740  SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
   741  aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
   742  U0NBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAx/E3WRVxcCDXhoST
   743  8nVSLjW6hwM4Ni99AegWzcGtfGFo0zjFA1Cl5URqxauvYu3gQgQHBGA1CovWeGrl
   744  yVSRzOL1imcYsSgLOcnhVYB3Xcrof4ebv9+W+TwNdc9YzAwcj8rNd5nP6PKXIQ+W
   745  PCkEOXdyb80YEnxuT+NPjkVfFSPBS7QYZpvT2fwy4fZ0eh48253+7VleSmTO0mqj
   746  7TlzaG56q150SLZbhpOd8jD8bM/wACnLCPR88wj4hCcDLEwoLyY85HJCTIQQMnoT
   747  UpqyzEeupPREIm6yi4d8C9YqIWFn2YTnRcWcmMaJLzq+kYwKoudfnoC6RW2vzZXn
   748  defQs68IZuK+uALu9G3JWGPgu0CQGj0JNDT8zkiDV++4eNrZczWKjr1YnAL+VbLK
   749  bApwL2u19l2WDpfUklimhWfraqHNIUKU6CjZOG31RzXcplIj0mtqs0E1r7r357Es
   750  yFoB28iNo4cz1lCulh0E4WJzWzLZcT4ZspHHRCFyvYnXoibXEV1nULq8ByKKG0FS
   751  7nn4SseoV+8PvjHLPhmHGMvi4mxkbcXdV3wthHT1/HXdqY84A4xHWt1+sB/TpTek
   752  tDhFlEfcUygvTu58UtOnysomOVVeERmi7WSujfzKsGJAJYeetiA5R+zX7BxeyFVE
   753  qW0zh1Tkwh0S8LRe5diJh4+6FG0CAwEAAaNfMF0wHQYDVR0OBBYEFD+oahaikBTV
   754  Urk81Uz7kRS2sx0aMA4GA1UdDwEB/wQEAwIBBjAYBgNVHSAEETAPMA0GCyqDCIaP
   755  fgYFAQEBMBIGA1UdEwEB/wQIMAYBAf8CAQAwQQYJKoZIhvcNAQEKMDSgDzANBglg
   756  hkgBZQMEAgEFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgEFAKIDAgEgA4IC
   757  AQAaxWBQn5CZuNBfyzL57mn31ukHUFd61OMROSX3PT7oCv1Dy+C2AdRlxOcbN3/n
   758  li0yfXUUqiY3COlLAHKRlkr97mLtxEFoJ0R8nVN2IQdChNQM/XSCzSGyY8NVa1OR
   759  TTpEWLnexJ9kvIdbFXwUqdTnAkOI0m7Rg8j+E+lRRHg1xDAA1qKttrtUj3HRQWf3
   760  kNTu628SiMvap6aIdncburaK56MP7gkR1Wr/ichOfjIA3Jgw2PapI31i0GqeMd66
   761  U1+lC9FeyMAJpuSVp/SoiYzYo+79SFcVoM2yw3yAnIKg7q9GLYYqzncdykT6C06c
   762  15gWFI6igmReAsD9ITSvYh0jLrLHfEYcPTOD3ZXJ4EwwHtWSoO3gq1EAtOYKu/Lv
   763  C8zfBsZcFdsHvsSiYeBU8Oioe42mguky3Ax9O7D805Ek6R68ra07MW/G4YxvV7IN
   764  2BfSaYy8MX9IG0ZMIOcoc0FeF5xkFmJ7kdrlTaJzC0IE9PNxNaH5QnOAFB8vxHcO
   765  FioUxb6UKdHcPLR1VZtAdTdTMjSJxUqD/35Cdfqs7oDJXz8f6TXO2Tdy6G++YUs9
   766  qsGZWxzFvvkXUkQSl0dQQ5jO/FtUJcAVXVVp20LxPemfatAHpW31WdJYeWSQWky2
   767  +f9b5TXKXVyjlUL7uHxowWrT2AtTchDH22wTEtqLEF9Z3Q==
   768  -----END CERTIFICATE-----`
   769  
   770  func TestRSAPSSSelfSigned(t *testing.T) {
   771  	der, _ := pem.Decode([]byte(rsaPSSSelfSignedPEM))
   772  	if der == nil {
   773  		t.Fatal("Failed to find PEM block")
   774  	}
   775  
   776  	cert, err := ParseCertificate(der.Bytes)
   777  	if err != nil {
   778  		t.Fatal(err)
   779  	}
   780  
   781  	if err = cert.CheckSignatureFrom(cert); err != nil {
   782  		t.Fatal(err)
   783  	}
   784  }
   785  
   786  const pemCertificate = `-----BEGIN CERTIFICATE-----
   787  MIIDATCCAemgAwIBAgIRAKQkkrFx1T/dgB/Go/xBM5swDQYJKoZIhvcNAQELBQAw
   788  EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xNjA4MTcyMDM2MDdaFw0xNzA4MTcyMDM2
   789  MDdaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
   790  ggEKAoIBAQDAoJtjG7M6InsWwIo+l3qq9u+g2rKFXNu9/mZ24XQ8XhV6PUR+5HQ4
   791  jUFWC58ExYhottqK5zQtKGkw5NuhjowFUgWB/VlNGAUBHtJcWR/062wYrHBYRxJH
   792  qVXOpYKbIWwFKoXu3hcpg/CkdOlDWGKoZKBCwQwUBhWE7MDhpVdQ+ZljUJWL+FlK
   793  yQK5iRsJd5TGJ6VUzLzdT4fmN2DzeK6GLeyMpVpU3sWV90JJbxWQ4YrzkKzYhMmB
   794  EcpXTG2wm+ujiHU/k2p8zlf8Sm7VBM/scmnMFt0ynNXop4FWvJzEm1G0xD2t+e2I
   795  5Utr04dOZPCgkm++QJgYhtZvgW7ZZiGTAgMBAAGjUjBQMA4GA1UdDwEB/wQEAwIF
   796  oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBsGA1UdEQQUMBKC
   797  EHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEBADpqKQxrthH5InC7
   798  X96UP0OJCu/lLEMkrjoEWYIQaFl7uLPxKH5AmQPH4lYwF7u7gksR7owVG9QU9fs6
   799  1fK7II9CVgCd/4tZ0zm98FmU4D0lHGtPARrrzoZaqVZcAvRnFTlPX5pFkPhVjjai
   800  /mkxX9LpD8oK1445DFHxK5UjLMmPIIWd8EOi+v5a+hgGwnJpoW7hntSl8kHMtTmy
   801  fnnktsblSUV4lRCit0ymC7Ojhe+gzCCwkgs5kDzVVag+tnl/0e2DloIjASwOhpbH
   802  KVcg7fBd484ht/sS+l0dsB4KDOSpd8JzVDMF8OZqlaydizoJO0yWr9GbCN1+OKq5
   803  EhLrEqU=
   804  -----END CERTIFICATE-----`
   805  
   806  func TestCRLCreation(t *testing.T) {
   807  	block, _ := pem.Decode([]byte(pemPrivateKey))
   808  	priv, _ := ParsePKCS1PrivateKey(block.Bytes)
   809  	block, _ = pem.Decode([]byte(pemCertificate))
   810  	cert, _ := ParseCertificate(block.Bytes)
   811  
   812  	loc := time.FixedZone("Oz/Atlantis", int((2 * time.Hour).Seconds()))
   813  
   814  	now := time.Unix(1000, 0).In(loc)
   815  	nowUTC := now.UTC()
   816  	expiry := time.Unix(10000, 0)
   817  
   818  	revokedCerts := []pkix.RevokedCertificate{
   819  		{
   820  			SerialNumber:   big.NewInt(1),
   821  			RevocationTime: nowUTC,
   822  		},
   823  		{
   824  			SerialNumber: big.NewInt(42),
   825  			// RevocationTime should be converted to UTC before marshaling.
   826  			RevocationTime: now,
   827  		},
   828  	}
   829  	expectedCerts := []pkix.RevokedCertificate{
   830  		{
   831  			SerialNumber:   big.NewInt(1),
   832  			RevocationTime: nowUTC,
   833  		},
   834  		{
   835  			SerialNumber:   big.NewInt(42),
   836  			RevocationTime: nowUTC,
   837  		},
   838  	}
   839  
   840  	crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry)
   841  	if err != nil {
   842  		t.Errorf("error creating CRL: %s", err)
   843  	}
   844  
   845  	parsedCRL, err := ParseDERCRL(crlBytes)
   846  	if err != nil {
   847  		t.Errorf("error reparsing CRL: %s", err)
   848  	}
   849  	if !reflect.DeepEqual(parsedCRL.TBSCertList.RevokedCertificates, expectedCerts) {
   850  		t.Errorf("RevokedCertificates mismatch: got %v; want %v.",
   851  			parsedCRL.TBSCertList.RevokedCertificates, expectedCerts)
   852  	}
   853  }
   854  
   855  func fromBase64(in string) []byte {
   856  	out := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
   857  	n, err := base64.StdEncoding.Decode(out, []byte(in))
   858  	if err != nil {
   859  		panic("failed to base64 decode")
   860  	}
   861  	return out[:n]
   862  }
   863  
   864  func TestParseDERCRL(t *testing.T) {
   865  	derBytes := fromBase64(derCRLBase64)
   866  	certList, err := ParseDERCRL(derBytes)
   867  	if err != nil {
   868  		t.Errorf("error parsing: %s", err)
   869  		return
   870  	}
   871  	numCerts := len(certList.TBSCertList.RevokedCertificates)
   872  	expected := 88
   873  	if numCerts != expected {
   874  		t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
   875  	}
   876  
   877  	if certList.HasExpired(time.Unix(1302517272, 0)) {
   878  		t.Errorf("CRL has expired (but shouldn't have)")
   879  	}
   880  
   881  	// Can't check the signature here without a package cycle.
   882  }
   883  
   884  func TestCRLWithoutExpiry(t *testing.T) {
   885  	derBytes := fromBase64("MIHYMIGZMAkGByqGSM44BAMwEjEQMA4GA1UEAxMHQ2FybERTUxcNOTkwODI3MDcwMDAwWjBpMBMCAgDIFw05OTA4MjIwNzAwMDBaMBMCAgDJFw05OTA4MjIwNzAwMDBaMBMCAgDTFw05OTA4MjIwNzAwMDBaMBMCAgDSFw05OTA4MjIwNzAwMDBaMBMCAgDUFw05OTA4MjQwNzAwMDBaMAkGByqGSM44BAMDLwAwLAIUfmVSdjP+NHMX0feW+aDU2G1cfT0CFAJ6W7fVWxjBz4fvftok8yqDnDWh")
   886  	certList, err := ParseDERCRL(derBytes)
   887  	if err != nil {
   888  		t.Fatal(err)
   889  	}
   890  	if !certList.TBSCertList.NextUpdate.IsZero() {
   891  		t.Errorf("NextUpdate is not the zero value")
   892  	}
   893  }
   894  
   895  func TestParsePEMCRL(t *testing.T) {
   896  	pemBytes := fromBase64(pemCRLBase64)
   897  	certList, err := ParseCRL(pemBytes)
   898  	if err != nil {
   899  		t.Errorf("error parsing: %s", err)
   900  		return
   901  	}
   902  	numCerts := len(certList.TBSCertList.RevokedCertificates)
   903  	expected := 2
   904  	if numCerts != expected {
   905  		t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
   906  	}
   907  
   908  	if certList.HasExpired(time.Unix(1302517272, 0)) {
   909  		t.Errorf("CRL has expired (but shouldn't have)")
   910  	}
   911  
   912  	// Can't check the signature here without a package cycle.
   913  }
   914  
   915  func TestImports(t *testing.T) {
   916  	testenv.MustHaveGoRun(t)
   917  
   918  	if err := exec.Command(testenv.GoToolPath(t), "run", "x509_test_import.go").Run(); err != nil {
   919  		t.Errorf("failed to run x509_test_import.go: %s", err)
   920  	}
   921  }
   922  
   923  const derCRLBase64 = "MIINqzCCDJMCAQEwDQYJKoZIhvcNAQEFBQAwVjEZMBcGA1UEAxMQUEtJIEZJTk1FQ0NBTklDQTEVMBMGA1UEChMMRklOTUVDQ0FOSUNBMRUwEwYDVQQLEwxGSU5NRUNDQU5JQ0ExCzAJBgNVBAYTAklUFw0xMTA1MDQxNjU3NDJaFw0xMTA1MDQyMDU3NDJaMIIMBzAhAg4Ze1od49Lt1qIXBydAzhcNMDkwNzE2MDg0MzIyWjAAMCECDl0HSL9bcZ1Ci/UHJ0DPFw0wOTA3MTYwODQzMTNaMAAwIQIOESB9tVAmX3cY7QcnQNAXDTA5MDcxNjA4NDUyMlowADAhAg4S1tGAQ3mHt8uVBydA1RcNMDkwODA0MTUyNTIyWjAAMCECDlQ249Y7vtC25ScHJ0DWFw0wOTA4MDQxNTI1MzdaMAAwIQ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DQpNSUlCOWpDQ0FWOENBUUV3RFFZSktvWklodmNOQVFFRkJRQXdiREVhTUJnR0ExVUVDaE1SVWxOQklGTmxZM1Z5DQphWFI1SUVsdVl5NHhIakFjQmdOVkJBTVRGVkpUUVNCUWRXSnNhV01nVW05dmRDQkRRU0IyTVRFdU1Dd0dDU3FHDQpTSWIzRFFFSkFSWWZjbk5oYTJWdmJuSnZiM1J6YVdkdVFISnpZWE5sWTNWeWFYUjVMbU52YlJjTk1URXdNakl6DQpNVGt5T0RNd1doY05NVEV3T0RJeU1Ua3lPRE13V2pDQmpEQktBaEVBckRxb2g5RkhKSFhUN09QZ3V1bjQrQmNODQpNRGt4TVRBeU1UUXlOekE1V2pBbU1Bb0dBMVVkRlFRRENnRUpNQmdHQTFVZEdBUVJHQTh5TURBNU1URXdNakUwDQpNalExTlZvd1BnSVJBTEd6blowOTVQQjVhQU9MUGc1N2ZNTVhEVEF5TVRBeU16RTBOVEF4TkZvd0dqQVlCZ05WDQpIUmdFRVJnUE1qQXdNakV3TWpNeE5EVXdNVFJhb0RBd0xqQWZCZ05WSFNNRUdEQVdnQlQxVERGNlVRTS9MTmVMDQpsNWx2cUhHUXEzZzltekFMQmdOVkhSUUVCQUlDQUlRd0RRWUpLb1pJaHZjTkFRRUZCUUFEZ1lFQUZVNUFzNk16DQpxNVBSc2lmYW9iUVBHaDFhSkx5QytNczVBZ2MwYld5QTNHQWR4dXI1U3BQWmVSV0NCamlQL01FSEJXSkNsQkhQDQpHUmNxNXlJZDNFakRrYUV5eFJhK2k2N0x6dmhJNmMyOUVlNks5cFNZd2ppLzdSVWhtbW5Qclh0VHhsTDBsckxyDQptUVFKNnhoRFJhNUczUUE0Q21VZHNITnZicnpnbUNZcHZWRT0NCi0tLS0tRU5EIFg1MDkgQ1JMLS0tLS0NCg0K"
   926  
   927  func TestCreateCertificateRequest(t *testing.T) {
   928  	random := rand.Reader
   929  
   930  	ecdsa256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   931  	if err != nil {
   932  		t.Fatalf("Failed to generate ECDSA key: %s", err)
   933  	}
   934  
   935  	ecdsa384Priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
   936  	if err != nil {
   937  		t.Fatalf("Failed to generate ECDSA key: %s", err)
   938  	}
   939  
   940  	ecdsa521Priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
   941  	if err != nil {
   942  		t.Fatalf("Failed to generate ECDSA key: %s", err)
   943  	}
   944  
   945  	tests := []struct {
   946  		name    string
   947  		priv    interface{}
   948  		sigAlgo SignatureAlgorithm
   949  	}{
   950  		{"RSA", testPrivateKey, SHA1WithRSA},
   951  		{"ECDSA-256", ecdsa256Priv, ECDSAWithSHA1},
   952  		{"ECDSA-384", ecdsa384Priv, ECDSAWithSHA1},
   953  		{"ECDSA-521", ecdsa521Priv, ECDSAWithSHA1},
   954  	}
   955  
   956  	for _, test := range tests {
   957  		template := CertificateRequest{
   958  			Subject: pkix.Name{
   959  				CommonName:   "test.example.com",
   960  				Organization: []string{"Σ Acme Co"},
   961  			},
   962  			SignatureAlgorithm: test.sigAlgo,
   963  			DNSNames:           []string{"test.example.com"},
   964  			EmailAddresses:     []string{"gopher@golang.org"},
   965  			IPAddresses:        []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
   966  		}
   967  
   968  		derBytes, err := CreateCertificateRequest(random, &template, test.priv)
   969  		if err != nil {
   970  			t.Errorf("%s: failed to create certificate request: %s", test.name, err)
   971  			continue
   972  		}
   973  
   974  		out, err := ParseCertificateRequest(derBytes)
   975  		if err != nil {
   976  			t.Errorf("%s: failed to create certificate request: %s", test.name, err)
   977  			continue
   978  		}
   979  
   980  		err = out.CheckSignature()
   981  		if err != nil {
   982  			t.Errorf("%s: failed to check certificate request signature: %s", test.name, err)
   983  			continue
   984  		}
   985  
   986  		if out.Subject.CommonName != template.Subject.CommonName {
   987  			t.Errorf("%s: output subject common name and template subject common name don't match", test.name)
   988  		} else if len(out.Subject.Organization) != len(template.Subject.Organization) {
   989  			t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name)
   990  		} else if len(out.DNSNames) != len(template.DNSNames) {
   991  			t.Errorf("%s: output DNS names and template DNS names don't match", test.name)
   992  		} else if len(out.EmailAddresses) != len(template.EmailAddresses) {
   993  			t.Errorf("%s: output email addresses and template email addresses don't match", test.name)
   994  		} else if len(out.IPAddresses) != len(template.IPAddresses) {
   995  			t.Errorf("%s: output IP addresses and template IP addresses names don't match", test.name)
   996  		}
   997  	}
   998  }
   999  
  1000  func marshalAndParseCSR(t *testing.T, template *CertificateRequest) *CertificateRequest {
  1001  	derBytes, err := CreateCertificateRequest(rand.Reader, template, testPrivateKey)
  1002  	if err != nil {
  1003  		t.Fatal(err)
  1004  	}
  1005  
  1006  	csr, err := ParseCertificateRequest(derBytes)
  1007  	if err != nil {
  1008  		t.Fatal(err)
  1009  	}
  1010  
  1011  	return csr
  1012  }
  1013  
  1014  func TestCertificateRequestOverrides(t *testing.T) {
  1015  	sanContents, err := marshalSANs([]string{"foo.example.com"}, nil, nil)
  1016  	if err != nil {
  1017  		t.Fatal(err)
  1018  	}
  1019  
  1020  	template := CertificateRequest{
  1021  		Subject: pkix.Name{
  1022  			CommonName:   "test.example.com",
  1023  			Organization: []string{"Σ Acme Co"},
  1024  		},
  1025  		DNSNames: []string{"test.example.com"},
  1026  
  1027  		// An explicit extension should override the DNSNames from the
  1028  		// template.
  1029  		ExtraExtensions: []pkix.Extension{
  1030  			{
  1031  				Id:    oidExtensionSubjectAltName,
  1032  				Value: sanContents,
  1033  			},
  1034  		},
  1035  	}
  1036  
  1037  	csr := marshalAndParseCSR(t, &template)
  1038  
  1039  	if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo.example.com" {
  1040  		t.Errorf("Extension did not override template. Got %v\n", csr.DNSNames)
  1041  	}
  1042  
  1043  	// If there is already an attribute with X.509 extensions then the
  1044  	// extra extensions should be added to it rather than creating a CSR
  1045  	// with two extension attributes.
  1046  
  1047  	template.Attributes = []pkix.AttributeTypeAndValueSET{
  1048  		{
  1049  			Type: oidExtensionRequest,
  1050  			Value: [][]pkix.AttributeTypeAndValue{
  1051  				{
  1052  					{
  1053  						Type:  oidExtensionAuthorityInfoAccess,
  1054  						Value: []byte("foo"),
  1055  					},
  1056  				},
  1057  			},
  1058  		},
  1059  	}
  1060  
  1061  	csr = marshalAndParseCSR(t, &template)
  1062  	if l := len(csr.Attributes); l != 1 {
  1063  		t.Errorf("incorrect number of attributes: %d\n", l)
  1064  	}
  1065  
  1066  	if !csr.Attributes[0].Type.Equal(oidExtensionRequest) ||
  1067  		len(csr.Attributes[0].Value) != 1 ||
  1068  		len(csr.Attributes[0].Value[0]) != 2 {
  1069  		t.Errorf("bad attributes: %#v\n", csr.Attributes)
  1070  	}
  1071  
  1072  	sanContents2, err := marshalSANs([]string{"foo2.example.com"}, nil, nil)
  1073  	if err != nil {
  1074  		t.Fatal(err)
  1075  	}
  1076  
  1077  	// Extensions in Attributes should override those in ExtraExtensions.
  1078  	template.Attributes[0].Value[0] = append(template.Attributes[0].Value[0], pkix.AttributeTypeAndValue{
  1079  		Type:  oidExtensionSubjectAltName,
  1080  		Value: sanContents2,
  1081  	})
  1082  
  1083  	csr = marshalAndParseCSR(t, &template)
  1084  
  1085  	if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo2.example.com" {
  1086  		t.Errorf("Attributes did not override ExtraExtensions. Got %v\n", csr.DNSNames)
  1087  	}
  1088  }
  1089  
  1090  func TestParseCertificateRequest(t *testing.T) {
  1091  	for _, csrBase64 := range csrBase64Array {
  1092  		csrBytes := fromBase64(csrBase64)
  1093  		csr, err := ParseCertificateRequest(csrBytes)
  1094  		if err != nil {
  1095  			t.Fatalf("failed to parse CSR: %s", err)
  1096  		}
  1097  
  1098  		if len(csr.EmailAddresses) != 1 || csr.EmailAddresses[0] != "gopher@golang.org" {
  1099  			t.Errorf("incorrect email addresses found: %v", csr.EmailAddresses)
  1100  		}
  1101  
  1102  		if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "test.example.com" {
  1103  			t.Errorf("incorrect DNS names found: %v", csr.DNSNames)
  1104  		}
  1105  
  1106  		if len(csr.Subject.Country) != 1 || csr.Subject.Country[0] != "AU" {
  1107  			t.Errorf("incorrect Subject name: %v", csr.Subject)
  1108  		}
  1109  
  1110  		found := false
  1111  		for _, e := range csr.Extensions {
  1112  			if e.Id.Equal(oidExtensionBasicConstraints) {
  1113  				found = true
  1114  				break
  1115  			}
  1116  		}
  1117  		if !found {
  1118  			t.Errorf("basic constraints extension not found in CSR")
  1119  		}
  1120  	}
  1121  }
  1122  
  1123  func TestCriticalFlagInCSRRequestedExtensions(t *testing.T) {
  1124  	// This CSR contains an extension request where the extensions have a
  1125  	// critical flag in them. In the past we failed to handle this.
  1126  	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="
  1127  
  1128  	csrBytes := fromBase64(csrBase64)
  1129  	csr, err := ParseCertificateRequest(csrBytes)
  1130  	if err != nil {
  1131  		t.Fatalf("failed to parse CSR: %s", err)
  1132  	}
  1133  
  1134  	expected := []struct {
  1135  		Id    asn1.ObjectIdentifier
  1136  		Value []byte
  1137  	}{
  1138  		{oidExtensionBasicConstraints, fromBase64("MAYBAf8CAQA=")},
  1139  		{oidExtensionKeyUsage, fromBase64("AwIChA==")},
  1140  	}
  1141  
  1142  	if n := len(csr.Extensions); n != len(expected) {
  1143  		t.Fatalf("expected to find %d extensions but found %d", len(expected), n)
  1144  	}
  1145  
  1146  	for i, extension := range csr.Extensions {
  1147  		if !extension.Id.Equal(expected[i].Id) {
  1148  			t.Fatalf("extension #%d has unexpected type %v (expected %v)", i, extension.Id, expected[i].Id)
  1149  		}
  1150  
  1151  		if !bytes.Equal(extension.Value, expected[i].Value) {
  1152  			t.Fatalf("extension #%d has unexpected contents %x (expected %x)", i, extension.Value, expected[i].Value)
  1153  		}
  1154  	}
  1155  }
  1156  
  1157  // serialiseAndParse generates a self-signed certificate from template and
  1158  // returns a parsed version of it.
  1159  func serialiseAndParse(t *testing.T, template *Certificate) *Certificate {
  1160  	derBytes, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey)
  1161  	if err != nil {
  1162  		t.Fatalf("failed to create certificate: %s", err)
  1163  		return nil
  1164  	}
  1165  
  1166  	cert, err := ParseCertificate(derBytes)
  1167  	if err != nil {
  1168  		t.Fatalf("failed to parse certificate: %s", err)
  1169  		return nil
  1170  	}
  1171  
  1172  	return cert
  1173  }
  1174  
  1175  func TestMaxPathLen(t *testing.T) {
  1176  	template := &Certificate{
  1177  		SerialNumber: big.NewInt(1),
  1178  		Subject: pkix.Name{
  1179  			CommonName: "Σ Acme Co",
  1180  		},
  1181  		NotBefore: time.Unix(1000, 0),
  1182  		NotAfter:  time.Unix(100000, 0),
  1183  
  1184  		BasicConstraintsValid: true,
  1185  		IsCA: true,
  1186  	}
  1187  
  1188  	cert1 := serialiseAndParse(t, template)
  1189  	if m := cert1.MaxPathLen; m != -1 {
  1190  		t.Errorf("Omitting MaxPathLen didn't turn into -1, got %d", m)
  1191  	}
  1192  	if cert1.MaxPathLenZero {
  1193  		t.Errorf("Omitting MaxPathLen resulted in MaxPathLenZero")
  1194  	}
  1195  
  1196  	template.MaxPathLen = 1
  1197  	cert2 := serialiseAndParse(t, template)
  1198  	if m := cert2.MaxPathLen; m != 1 {
  1199  		t.Errorf("Setting MaxPathLen didn't work. Got %d but set 1", m)
  1200  	}
  1201  	if cert2.MaxPathLenZero {
  1202  		t.Errorf("Setting MaxPathLen resulted in MaxPathLenZero")
  1203  	}
  1204  
  1205  	template.MaxPathLen = 0
  1206  	template.MaxPathLenZero = true
  1207  	cert3 := serialiseAndParse(t, template)
  1208  	if m := cert3.MaxPathLen; m != 0 {
  1209  		t.Errorf("Setting MaxPathLenZero didn't work, got %d", m)
  1210  	}
  1211  	if !cert3.MaxPathLenZero {
  1212  		t.Errorf("Setting MaxPathLen to zero didn't result in MaxPathLenZero")
  1213  	}
  1214  }
  1215  
  1216  func TestNoAuthorityKeyIdInSelfSignedCert(t *testing.T) {
  1217  	template := &Certificate{
  1218  		SerialNumber: big.NewInt(1),
  1219  		Subject: pkix.Name{
  1220  			CommonName: "Σ Acme Co",
  1221  		},
  1222  		NotBefore: time.Unix(1000, 0),
  1223  		NotAfter:  time.Unix(100000, 0),
  1224  
  1225  		BasicConstraintsValid: true,
  1226  		IsCA:         true,
  1227  		SubjectKeyId: []byte{1, 2, 3, 4},
  1228  	}
  1229  
  1230  	if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) != 0 {
  1231  		t.Fatalf("self-signed certificate contained default authority key id")
  1232  	}
  1233  
  1234  	template.AuthorityKeyId = []byte{1, 2, 3, 4}
  1235  	if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) == 0 {
  1236  		t.Fatalf("self-signed certificate erased explicit authority key id")
  1237  	}
  1238  }
  1239  
  1240  func TestASN1BitLength(t *testing.T) {
  1241  	tests := []struct {
  1242  		bytes  []byte
  1243  		bitLen int
  1244  	}{
  1245  		{nil, 0},
  1246  		{[]byte{0x00}, 0},
  1247  		{[]byte{0x00, 0x00}, 0},
  1248  		{[]byte{0xf0}, 4},
  1249  		{[]byte{0x88}, 5},
  1250  		{[]byte{0xff}, 8},
  1251  		{[]byte{0xff, 0x80}, 9},
  1252  		{[]byte{0xff, 0x81}, 16},
  1253  	}
  1254  
  1255  	for i, test := range tests {
  1256  		if got := asn1BitLength(test.bytes); got != test.bitLen {
  1257  			t.Errorf("#%d: calculated bit-length of %d for %x, wanted %d", i, got, test.bytes, test.bitLen)
  1258  		}
  1259  	}
  1260  }
  1261  
  1262  func TestVerifyEmptyCertificate(t *testing.T) {
  1263  	if _, err := new(Certificate).Verify(VerifyOptions{}); err != errNotParsed {
  1264  		t.Errorf("Verifying empty certificate resulted in unexpected error: %q (wanted %q)", err, errNotParsed)
  1265  	}
  1266  }
  1267  
  1268  func TestInsecureAlgorithmErrorString(t *testing.T) {
  1269  	tests := []struct {
  1270  		sa   SignatureAlgorithm
  1271  		want string
  1272  	}{
  1273  		{MD2WithRSA, "x509: cannot verify signature: insecure algorithm MD2-RSA"},
  1274  		{-1, "x509: cannot verify signature: insecure algorithm -1"},
  1275  		{0, "x509: cannot verify signature: insecure algorithm 0"},
  1276  		{9999, "x509: cannot verify signature: insecure algorithm 9999"},
  1277  	}
  1278  	for i, tt := range tests {
  1279  		if got := fmt.Sprint(InsecureAlgorithmError(tt.sa)); got != tt.want {
  1280  			t.Errorf("%d. mismatch.\n got: %s\nwant: %s\n", i, got, tt.want)
  1281  		}
  1282  	}
  1283  }
  1284  
  1285  // These CSR was generated with OpenSSL:
  1286  //  openssl req -out CSR.csr -new -sha256 -nodes -keyout privateKey.key -config openssl.cnf
  1287  //
  1288  // With openssl.cnf containing the following sections:
  1289  //   [ v3_req ]
  1290  //   basicConstraints = CA:FALSE
  1291  //   keyUsage = nonRepudiation, digitalSignature, keyEncipherment
  1292  //   subjectAltName = email:gopher@golang.org,DNS:test.example.com
  1293  //   [ req_attributes ]
  1294  //   challengePassword = ignored challenge
  1295  //   unstructuredName  = ignored unstructured name
  1296  var csrBase64Array = [...]string{
  1297  	// Just [ v3_req ]
  1298  	"MIIDHDCCAgQCAQAwfjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEUMBIGA1UEAwwLQ29tbW9uIE5hbWUxITAfBgkqhkiG9w0BCQEWEnRlc3RAZW1haWwuYWRkcmVzczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK1GY4YFx2ujlZEOJxQVYmsjUnLsd5nFVnNpLE4cV+77sgv9NPNlB8uhn3MXt5leD34rm/2BisCHOifPucYlSrszo2beuKhvwn4+2FxDmWtBEMu/QA16L5IvoOfYZm/gJTsPwKDqvaR0tTU67a9OtxwNTBMI56YKtmwd/o8d3hYv9cg+9ZGAZ/gKONcg/OWYx/XRh6bd0g8DMbCikpWgXKDsvvK1Nk+VtkDO1JxuBaj4Lz/p/MifTfnHoqHxWOWl4EaTs4Ychxsv34/rSj1KD1tJqorIv5Xv2aqv4sjxfbrYzX4kvS5SC1goIovLnhj5UjmQ3Qy8u65eow/LLWw+YFcCAwEAAaBZMFcGCSqGS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+bRLV7FZ/iuvs
  1311  cfYyQQFTxan4TaJMd0x1HoNDbNbjHa02IyjjYE/r3mb/PIg+J2t5AZEh80lPAgMB
  1312  AAEwDQYJKoZIhvcNAQEEBQADgYEAjGzp3K3ey/YfKHohf33yHHWd695HQxDAP+wY
  1313  cs9/TAyLR+gJzJP7d18EcDDLJWVi7bhfa4EAD86di05azOh9kWSn4b3o9QYRGCSw
  1314  GNnI3Zk0cwNKA49hZntKKiy22DhRk7JAHF01d6Bu3KkHkmENrtJ+zj/+159WAnUa
  1315  qViorq4=
  1316  -----END CERTIFICATE-----
  1317  `
  1318  
  1319  func TestMD5(t *testing.T) {
  1320  	pemBlock, _ := pem.Decode([]byte(md5cert))
  1321  	cert, err := ParseCertificate(pemBlock.Bytes)
  1322  	if err != nil {
  1323  		t.Fatalf("failed to parse certificate: %s", err)
  1324  	}
  1325  	if sa := cert.SignatureAlgorithm; sa != MD5WithRSA {
  1326  		t.Errorf("signature algorithm is %v, want %v", sa, MD5WithRSA)
  1327  	}
  1328  	if err = cert.CheckSignatureFrom(cert); err == nil {
  1329  		t.Fatalf("certificate verification succeeded incorrectly")
  1330  	}
  1331  	if _, ok := err.(InsecureAlgorithmError); !ok {
  1332  		t.Fatalf("certificate verification returned %v (%T), wanted InsecureAlgorithmError", err, err)
  1333  	}
  1334  }
  1335  
  1336  // certMissingRSANULL contains an RSA public key where the AlgorithmIdentifer
  1337  // parameters are omitted rather than being an ASN.1 NULL.
  1338  const certMissingRSANULL = `
  1339  -----BEGIN CERTIFICATE-----
  1340  MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD
  1341  bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4
  1342  MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc
  1343  MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG
  1344  hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE
  1345  ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e
  1346  E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw
  1347  DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A
  1348  p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4
  1349  hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE
  1350  GFGNEH5PlGffo05wc46QkYU=
  1351  -----END CERTIFICATE-----`
  1352  
  1353  func TestRSAMissingNULLParameters(t *testing.T) {
  1354  	block, _ := pem.Decode([]byte(certMissingRSANULL))
  1355  	if _, err := ParseCertificate(block.Bytes); err == nil {
  1356  		t.Error("unexpected success when parsing certificate with missing RSA NULL parameter")
  1357  	} else if !strings.Contains(err.Error(), "missing NULL") {
  1358  		t.Errorf("unrecognised error when parsing certificate with missing RSA NULL parameter: %s", err)
  1359  	}
  1360  }
  1361  
  1362  const certISOOID = `
  1363  -----BEGIN CERTIFICATE-----
  1364  MIIB5TCCAVKgAwIBAgIQtwyL3RPWV7dJQp34HwZG9DAJBgUrDgMCHQUAMBExDzAN
  1365  BgNVBAMTBm15dGVzdDAeFw0xNjA4MDkyMjExMDVaFw0zOTEyMzEyMzU5NTlaMBEx
  1366  DzANBgNVBAMTBm15dGVzdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArzIH
  1367  GsyDB3ohIGkkvijF2PTRUX1bvOtY1eUUpjwHyu0twpAKSuaQv2Ha+/63+aHe8O86
  1368  BT+98wjXFX6RFSagtAujo80rIF2dSm33BGt18pDN8v6zp93dnAm0jRaSQrHJ75xw
  1369  5O+S1oEYR1LtUoFJy6qB104j6aINBAgOiLIKiMkCAwEAAaNGMEQwQgYDVR0BBDsw
  1370  OYAQVuYVQ/WDjdGSkZRlTtJDNKETMBExDzANBgNVBAMTBm15dGVzdIIQtwyL3RPW
  1371  V7dJQp34HwZG9DAJBgUrDgMCHQUAA4GBABngrSkH7vG5lY4sa4AZF59lAAXqBVJE
  1372  J4TBiKC62hCdZv18rBleP6ETfhbPg7pTs8p4ebQbpmtNxRS9Lw3MzQ8Ya5Ybwzj2
  1373  NwBSyCtCQl7mrEg4nJqJl4A2EUhnET/oVxU0oTV/SZ3ziGXcY1oG1s6vidV7TZTu
  1374  MCRtdSdaM7g3
  1375  -----END CERTIFICATE-----`
  1376  
  1377  func TestISOOIDInCertificate(t *testing.T) {
  1378  	block, _ := pem.Decode([]byte(certISOOID))
  1379  	if cert, err := ParseCertificate(block.Bytes); err != nil {
  1380  		t.Errorf("certificate with ISO OID failed to parse: %s", err)
  1381  	} else if cert.SignatureAlgorithm == UnknownSignatureAlgorithm {
  1382  		t.Errorf("ISO OID not recognised in certificate")
  1383  	}
  1384  }
  1385  
  1386  // certMultipleRDN contains a RelativeDistinguishedName with two elements (the
  1387  // common name and serial number). This particular certificate was the first
  1388  // such certificate in the “Pilot” Certificate Transparency log.
  1389  const certMultipleRDN = `
  1390  -----BEGIN CERTIFICATE-----
  1391  MIIFRzCCBC+gAwIBAgIEOl59NTANBgkqhkiG9w0BAQUFADA9MQswCQYDVQQGEwJz
  1392  aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMREwDwYDVQQLEwhzaWdvdi1j
  1393  YTAeFw0xMjExMTYxMDUyNTdaFw0xNzExMTYxMjQ5MDVaMIGLMQswCQYDVQQGEwJz
  1394  aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMRkwFwYDVQQLExB3ZWItY2Vy
  1395  dGlmaWNhdGVzMRAwDgY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YDVR0QBCQwIoAPMjAxMjExMTYxMDUyNTda
  1411  gQ8yMDE3MTExNjEyNDkwNVowHwYDVR0jBBgwFoAUHvjUU2uzgwbpBAZXAvmlv8ZY
  1412  PHIwHQYDVR0OBBYEFGI1Duuu+wTGDZka/xHNbwcbM69ZMAkGA1UdEwQCMAAwGQYJ
  1413  KoZIhvZ9B0EABAwwChsEVjcuMQMCA6gwDQYJKoZIhvcNAQEFBQADggEBAHny0K1y
  1414  BQznrzDu3DDpBcGYguKU0dvU9rqsV1ua4nxkriSMWjgsX6XJFDdDW60I3P4VWab5
  1415  ag5fZzbGqi8kva/CzGgZh+CES0aWCPy+4Gb8lwOTt+854/laaJvd6kgKTER7z7U9
  1416  9C86Ch2y4sXNwwwPJ1A9dmrZJZOcJjS/WYZgwaafY2Hdxub5jqPE5nehwYUPVu9R
  1417  uH6/skk4OEKcfOtN0hCnISOVuKYyS4ANARWRG5VGHIH06z3lGUVARFRJ61gtAprd
  1418  La+fgSS+LVZ+kU2TkeoWAKvGq8MAgDq4D4Xqwekg7WKFeuyusi/NI5rm40XgjBMF
  1419  DF72IUofoVt7wo0=
  1420  -----END CERTIFICATE-----`
  1421  
  1422  func TestMultipleRDN(t *testing.T) {
  1423  	block, _ := pem.Decode([]byte(certMultipleRDN))
  1424  	cert, err := ParseCertificate(block.Bytes)
  1425  	if err != nil {
  1426  		t.Fatalf("certificate with two elements in an RDN failed to parse: %v", err)
  1427  	}
  1428  
  1429  	if want := "eportal.mss.edus.si"; cert.Subject.CommonName != want {
  1430  		t.Errorf("got common name of %q, but want %q", cert.Subject.CommonName, want)
  1431  	}
  1432  
  1433  	if want := "1236484010010"; cert.Subject.SerialNumber != want {
  1434  		t.Errorf("got serial number of %q, but want %q", cert.Subject.SerialNumber, want)
  1435  	}
  1436  }
  1437  
  1438  func TestSystemCertPool(t *testing.T) {
  1439  	if runtime.GOOS == "windows" {
  1440  		t.Skip("not implemented on Windows; Issue 16736, 18609")
  1441  	}
  1442  	_, err := SystemCertPool()
  1443  	if err != nil {
  1444  		t.Fatal(err)
  1445  	}
  1446  }
  1447  
  1448  const emptyNameConstraintsPEM = `
  1449  -----BEGIN CERTIFICATE-----
  1450  MIIC1jCCAb6gAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w
  1451  dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw
  1452  NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB
  1453  IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD
  1454  F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx
  1455  f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq
  1456  Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0
  1457  LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD
  1458  blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID
  1459  AQABoxEwDzANBgNVHR4EBjAEoAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMH
  1460  QhP8uNCtgSHyim/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb
  1461  6L+iJa4ElREJOi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6H
  1462  v5SsvpYW+1XleYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6M
  1463  LYPmRhTioROA/drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOga
  1464  nCOSyFYfGhqOANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8
  1465  o+WoY6IsCKXV/g==
  1466  -----END CERTIFICATE-----`
  1467  
  1468  func TestEmptyNameConstraints(t *testing.T) {
  1469  	block, _ := pem.Decode([]byte(emptyNameConstraintsPEM))
  1470  	_, err := ParseCertificate(block.Bytes)
  1471  	if err == nil {
  1472  		t.Fatal("unexpected success")
  1473  	}
  1474  
  1475  	const expected = "empty name constraints"
  1476  	if str := err.Error(); !strings.Contains(str, expected) {
  1477  		t.Errorf("expected %q in error but got %q", expected, str)
  1478  	}
  1479  }
  1480  
  1481  func TestPKIXNameString(t *testing.T) {
  1482  	pem, err := hex.DecodeString(certBytes)
  1483  	if err != nil {
  1484  		t.Fatal(err)
  1485  	}
  1486  	certs, err := ParseCertificates(pem)
  1487  	if err != nil {
  1488  		t.Fatal(err)
  1489  	}
  1490  
  1491  	tests := []struct {
  1492  		dn   pkix.Name
  1493  		want string
  1494  	}{
  1495  		{pkix.Name{
  1496  			CommonName:         "Steve Kille",
  1497  			Organization:       []string{"Isode Limited"},
  1498  			OrganizationalUnit: []string{"RFCs"},
  1499  			Locality:           []string{"Richmond"},
  1500  			Province:           []string{"Surrey"},
  1501  			StreetAddress:      []string{"The Square"},
  1502  			PostalCode:         []string{"TW9 1DT"},
  1503  			SerialNumber:       "RFC 2253",
  1504  			Country:            []string{"GB"},
  1505  		}, "SERIALNUMBER=RFC 2253,CN=Steve Kille,OU=RFCs,O=Isode Limited,POSTALCODE=TW9 1DT,STREET=The Square,L=Richmond,ST=Surrey,C=GB"},
  1506  		{certs[0].Subject,
  1507  			"CN=mail.google.com,O=Google Inc,L=Mountain View,ST=California,C=US"},
  1508  		{pkix.Name{
  1509  			Organization: []string{"#Google, Inc. \n-> 'Alphabet\" "},
  1510  			Country:      []string{"US"},
  1511  		}, "O=\\#Google\\, Inc. \n-\\> 'Alphabet\\\"\\ ,C=US"},
  1512  		{pkix.Name{
  1513  			CommonName:   "foo.com",
  1514  			Organization: []string{"Gopher Industries"},
  1515  			ExtraNames: []pkix.AttributeTypeAndValue{
  1516  				{Type: asn1.ObjectIdentifier([]int{2, 5, 4, 3}), Value: "bar.com"}},
  1517  		}, "CN=bar.com,O=Gopher Industries"},
  1518  		{pkix.Name{
  1519  			Locality: []string{"Gophertown"},
  1520  			ExtraNames: []pkix.AttributeTypeAndValue{
  1521  				{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  1522  		}, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"},
  1523  	}
  1524  
  1525  	for i, test := range tests {
  1526  		if got := test.dn.String(); got != test.want {
  1527  			t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
  1528  		}
  1529  	}
  1530  }
  1531  
  1532  func TestRDNSequenceString(t *testing.T) {
  1533  	// Test some extra cases that get lost in pkix.Name conversions such as
  1534  	// multi-valued attributes.
  1535  
  1536  	var (
  1537  		oidCountry            = []int{2, 5, 4, 6}
  1538  		oidOrganization       = []int{2, 5, 4, 10}
  1539  		oidOrganizationalUnit = []int{2, 5, 4, 11}
  1540  		oidCommonName         = []int{2, 5, 4, 3}
  1541  	)
  1542  
  1543  	tests := []struct {
  1544  		seq  pkix.RDNSequence
  1545  		want string
  1546  	}{
  1547  		{seq: pkix.RDNSequence{
  1548  			pkix.RelativeDistinguishedNameSET{
  1549  				pkix.AttributeTypeAndValue{Type: oidCountry, Value: "US"},
  1550  			},
  1551  			pkix.RelativeDistinguishedNameSET{
  1552  				pkix.AttributeTypeAndValue{Type: oidOrganization, Value: "Widget Inc."},
  1553  			},
  1554  			pkix.RelativeDistinguishedNameSET{
  1555  				pkix.AttributeTypeAndValue{Type: oidOrganizationalUnit, Value: "Sales"},
  1556  				pkix.AttributeTypeAndValue{Type: oidCommonName, Value: "J. Smith"},
  1557  			},
  1558  		},
  1559  		want: "OU=Sales+CN=J. Smith,O=Widget Inc.,C=US"},
  1560  	}
  1561  
  1562  	for i, test := range tests {
  1563  		if got := test.seq.String(); got != test.want {
  1564  			t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
  1565  		}
  1566  	}
  1567  }