github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/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"
    10  	"crypto/ecdsa"
    11  	"crypto/ed25519"
    12  	"crypto/elliptic"
    13  	"crypto/rand"
    14  	"crypto/rsa"
    15  	_ "crypto/sha256"
    16  	_ "crypto/sha512"
    17  	"crypto/x509/pkix"
    18  	"encoding/asn1"
    19  	"encoding/base64"
    20  	"encoding/hex"
    21  	"encoding/pem"
    22  	"fmt"
    23  	"io"
    24  	"math/big"
    25  	"net"
    26  	"net/url"
    27  	"os/exec"
    28  	"reflect"
    29  	"runtime"
    30  	"strings"
    31  	"testing"
    32  	"time"
    33  
    34  	"github.com/hxx258456/ccgo/internal/testenv"
    35  	"github.com/hxx258456/ccgo/sm2"
    36  )
    37  
    38  func TestParsePKCS1PrivateKey(t *testing.T) {
    39  	block, _ := pem.Decode([]byte(pemPrivateKey))
    40  	priv, err := ParsePKCS1PrivateKey(block.Bytes)
    41  	if err != nil {
    42  		t.Errorf("Failed to parse private key: %s", err)
    43  		return
    44  	}
    45  	if priv.PublicKey.N.Cmp(rsaPrivateKey.PublicKey.N) != 0 ||
    46  		priv.PublicKey.E != rsaPrivateKey.PublicKey.E ||
    47  		priv.D.Cmp(rsaPrivateKey.D) != 0 ||
    48  		priv.Primes[0].Cmp(rsaPrivateKey.Primes[0]) != 0 ||
    49  		priv.Primes[1].Cmp(rsaPrivateKey.Primes[1]) != 0 {
    50  		t.Errorf("got:%+v want:%+v", priv, rsaPrivateKey)
    51  	}
    52  
    53  	// This private key includes an invalid prime that
    54  	// rsa.PrivateKey.Validate should reject.
    55  	data := []byte("0\x16\x02\x00\x02\x02\u007f\x00\x02\x0200\x02\x0200\x02\x02\x00\x01\x02\x02\u007f\x00")
    56  	if _, err := ParsePKCS1PrivateKey(data); err == nil {
    57  		t.Errorf("parsing invalid private key did not result in an error")
    58  	}
    59  }
    60  
    61  func TestPKCS1MismatchPublicKeyFormat(t *testing.T) {
    62  
    63  	const pkixPublicKey = "30820122300d06092a864886f70d01010105000382010f003082010a0282010100dd5a0f37d3ca5232852ccc0e81eebec270e2f2c6c44c6231d852971a0aad00aa7399e9b9de444611083c59ea919a9d76c20a7be131a99045ec19a7bb452d647a72429e66b87e28be9e8187ed1d2a2a01ef3eb2360706bd873b07f2d1f1a72337aab5ec94e983e39107f52c480d404915e84d75a3db2cfd601726a128cb1d7f11492d4bdb53272e652276667220795c709b8a9b4af6489cbf48bb8173b8fb607c834a71b6e8bf2d6aab82af3c8ad7ce16d8dcf58373a6edc427f7484d09744d4c08f4e19ed07adbf6cb31243bc5d0d1145e77a08a6fc5efd208eca67d6abf2d6f38f58b6fdd7c28774fb0cc03fc4935c6e074842d2e1479d3d8787249258719f90203010001"
    64  	const errorContains = "use ParsePKIXPublicKey instead"
    65  	derBytes, _ := hex.DecodeString(pkixPublicKey)
    66  	_, err := ParsePKCS1PublicKey(derBytes)
    67  	if !strings.Contains(err.Error(), errorContains) {
    68  		t.Errorf("expected error containing %q, got %s", errorContains, err)
    69  	}
    70  }
    71  
    72  func testParsePKIXPublicKey(t *testing.T, pemBytes string) (pub interface{}) {
    73  	block, _ := pem.Decode([]byte(pemBytes))
    74  	pub, err := ParsePKIXPublicKey(block.Bytes)
    75  	if err != nil {
    76  		t.Fatalf("Failed to parse public key: %s", err)
    77  	}
    78  
    79  	pubBytes2, err := MarshalPKIXPublicKey(pub)
    80  	if err != nil {
    81  		t.Errorf("Failed to marshal public key for the second time: %s", err)
    82  		return
    83  	}
    84  	if !bytes.Equal(pubBytes2, block.Bytes) {
    85  		t.Errorf("Reserialization of public key didn't match. got %x, want %x", pubBytes2, block.Bytes)
    86  	}
    87  	return
    88  }
    89  
    90  func TestParsePKIXPublicKey(t *testing.T) {
    91  	t.Run("RSA", func(t *testing.T) {
    92  		pub := testParsePKIXPublicKey(t, pemPublicKey)
    93  		_, ok := pub.(*rsa.PublicKey)
    94  		if !ok {
    95  			t.Errorf("Value returned from ParsePKIXPublicKey was not an RSA public key")
    96  		}
    97  	})
    98  	t.Run("Ed25519", func(t *testing.T) {
    99  		pub := testParsePKIXPublicKey(t, pemEd25519Key)
   100  		_, ok := pub.(ed25519.PublicKey)
   101  		if !ok {
   102  			t.Errorf("Value returned from ParsePKIXPublicKey was not an Ed25519 public key")
   103  		}
   104  	})
   105  }
   106  
   107  var pemPublicKey = `-----BEGIN PUBLIC KEY-----
   108  MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3VoPN9PKUjKFLMwOge6+
   109  wnDi8sbETGIx2FKXGgqtAKpzmem53kRGEQg8WeqRmp12wgp74TGpkEXsGae7RS1k
   110  enJCnma4fii+noGH7R0qKgHvPrI2Bwa9hzsH8tHxpyM3qrXslOmD45EH9SxIDUBJ
   111  FehNdaPbLP1gFyahKMsdfxFJLUvbUycuZSJ2ZnIgeVxwm4qbSvZInL9Iu4FzuPtg
   112  fINKcbbovy1qq4KvPIrXzhbY3PWDc6btxCf3SE0JdE1MCPThntB62/bLMSQ7xdDR
   113  FF53oIpvxe/SCOymfWq/LW849Ytv3Xwod0+wzAP8STXG4HSELS4UedPYeHJJJYcZ
   114  +QIDAQAB
   115  -----END PUBLIC KEY-----
   116  `
   117  
   118  var pemPrivateKey = testingKey(`
   119  -----BEGIN RSA TESTING KEY-----
   120  MIICXAIBAAKBgQCxoeCUW5KJxNPxMp+KmCxKLc1Zv9Ny+4CFqcUXVUYH69L3mQ7v
   121  IWrJ9GBfcaA7BPQqUlWxWM+OCEQZH1EZNIuqRMNQVuIGCbz5UQ8w6tS0gcgdeGX7
   122  J7jgCQ4RK3F/PuCM38QBLaHx988qG8NMc6VKErBjctCXFHQt14lerd5KpQIDAQAB
   123  AoGAYrf6Hbk+mT5AI33k2Jt1kcweodBP7UkExkPxeuQzRVe0KVJw0EkcFhywKpr1
   124  V5eLMrILWcJnpyHE5slWwtFHBG6a5fLaNtsBBtcAIfqTQ0Vfj5c6SzVaJv0Z5rOd
   125  7gQF6isy3t3w9IF3We9wXQKzT6q5ypPGdm6fciKQ8RnzREkCQQDZwppKATqQ41/R
   126  vhSj90fFifrGE6aVKC1hgSpxGQa4oIdsYYHwMzyhBmWW9Xv/R+fPyr8ZwPxp2c12
   127  33QwOLPLAkEA0NNUb+z4ebVVHyvSwF5jhfJxigim+s49KuzJ1+A2RaSApGyBZiwS
   128  rWvWkB471POAKUYt5ykIWVZ83zcceQiNTwJBAMJUFQZX5GDqWFc/zwGoKkeR49Yi
   129  MTXIvf7Wmv6E++eFcnT461FlGAUHRV+bQQXGsItR/opIG7mGogIkVXa3E1MCQARX
   130  AAA7eoZ9AEHflUeuLn9QJI/r0hyQQLEtrpwv6rDT1GCWaLII5HJ6NUFVf4TTcqxo
   131  6vdM4QGKTJoO+SaCyP0CQFdpcxSAuzpFcKv0IlJ8XzS/cy+mweCMwyJ1PFEc4FX6
   132  wg/HcAJWY60xZTJDFN+Qfx8ZQvBEin6c2/h+zZi5IVY=
   133  -----END RSA TESTING KEY-----
   134  `)
   135  
   136  // pemEd25519Key is the example from RFC 8410, Secrion 4.
   137  var pemEd25519Key = `
   138  -----BEGIN PUBLIC KEY-----
   139  MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE=
   140  -----END PUBLIC KEY-----
   141  `
   142  
   143  func TestPKIXMismatchPublicKeyFormat(t *testing.T) {
   144  
   145  	const pkcs1PublicKey = "308201080282010100817cfed98bcaa2e2a57087451c7674e0c675686dc33ff1268b0c2a6ee0202dec710858ee1c31bdf5e7783582e8ca800be45f3275c6576adc35d98e26e95bb88ca5beb186f853b8745d88bc9102c5f38753bcda519fb05948d5c77ac429255ff8aaf27d9f45d1586e95e2e9ba8a7cb771b8a09dd8c8fed3f933fd9b439bc9f30c475953418ef25f71a2b6496f53d94d39ce850aa0cc75d445b5f5b4f4ee4db78ab197a9a8d8a852f44529a007ac0ac23d895928d60ba538b16b0b087a7f903ed29770e215019b77eaecc360f35f7ab11b6d735978795b2c4a74e5bdea4dc6594cd67ed752a108e666729a753ab36d6c4f606f8760f507e1765be8cd744007e629020103"
   146  	const errorContains = "use ParsePKCS1PublicKey instead"
   147  	derBytes, _ := hex.DecodeString(pkcs1PublicKey)
   148  	_, err := ParsePKIXPublicKey(derBytes)
   149  	if !strings.Contains(err.Error(), errorContains) {
   150  		t.Errorf("expected error containing %q, got %s", errorContains, err)
   151  	}
   152  }
   153  
   154  var testPrivateKey *rsa.PrivateKey
   155  
   156  func init() {
   157  	block, _ := pem.Decode([]byte(pemPrivateKey))
   158  
   159  	var err error
   160  	if testPrivateKey, err = ParsePKCS1PrivateKey(block.Bytes); err != nil {
   161  		panic("Failed to parse private key: " + err.Error())
   162  	}
   163  }
   164  
   165  func bigFromString(s string) *big.Int {
   166  	ret := new(big.Int)
   167  	ret.SetString(s, 10)
   168  	return ret
   169  }
   170  
   171  func fromBase10(base10 string) *big.Int {
   172  	i := new(big.Int)
   173  	i.SetString(base10, 10)
   174  	return i
   175  }
   176  
   177  //goland:noinspection GoUnusedFunction
   178  func bigFromHexString(s string) *big.Int {
   179  	ret := new(big.Int)
   180  	ret.SetString(s, 16)
   181  	return ret
   182  }
   183  
   184  var rsaPrivateKey = &rsa.PrivateKey{
   185  	PublicKey: rsa.PublicKey{
   186  		N: bigFromString("124737666279038955318614287965056875799409043964547386061640914307192830334599556034328900586693254156136128122194531292927142396093148164407300419162827624945636708870992355233833321488652786796134504707628792159725681555822420087112284637501705261187690946267527866880072856272532711620639179596808018872997"),
   187  		E: 65537,
   188  	},
   189  	D: bigFromString("69322600686866301945688231018559005300304807960033948687567105312977055197015197977971637657636780793670599180105424702854759606794705928621125408040473426339714144598640466128488132656829419518221592374964225347786430566310906679585739468938549035854760501049443920822523780156843263434219450229353270690889"),
   190  	Primes: []*big.Int{
   191  		bigFromString("11405025354575369741595561190164746858706645478381139288033759331174478411254205003127028642766986913445391069745480057674348716675323735886284176682955723"),
   192  		bigFromString("10937079261204603443118731009201819560867324167189758120988909645641782263430128449826989846631183550578761324239709121189827307416350485191350050332642639"),
   193  	},
   194  }
   195  
   196  func TestMarshalRSAPrivateKey(t *testing.T) {
   197  	priv := &rsa.PrivateKey{
   198  		PublicKey: rsa.PublicKey{
   199  			N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"),
   200  			E: 3,
   201  		},
   202  		D: fromBase10("10897585948254795600358846499957366070880176878341177571733155050184921896034527397712889205732614568234385175145686545381899460748279607074689061600935843283397424506622998458510302603922766336783617368686090042765718290914099334449154829375179958369993407724946186243249568928237086215759259909861748642124071874879861299389874230489928271621259294894142840428407196932444474088857746123104978617098858619445675532587787023228852383149557470077802718705420275739737958953794088728369933811184572620857678792001136676902250566845618813972833750098806496641114644760255910789397593428910198080271317419213080834885003"),
   203  		Primes: []*big.Int{
   204  			fromBase10("1025363189502892836833747188838978207017355117492483312747347695538428729137306368764177201532277413433182799108299960196606011786562992097313508180436744488171474690412562218914213688661311117337381958560443"),
   205  			fromBase10("3467903426626310123395340254094941045497208049900750380025518552334536945536837294961497712862519984786362199788654739924501424784631315081391467293694361474867825728031147665777546570788493758372218019373"),
   206  			fromBase10("4597024781409332673052708605078359346966325141767460991205742124888960305710298765592730135879076084498363772408626791576005136245060321874472727132746643162385746062759369754202494417496879741537284589047"),
   207  		},
   208  	}
   209  
   210  	derBytes := MarshalPKCS1PrivateKey(priv)
   211  
   212  	priv2, err := ParsePKCS1PrivateKey(derBytes)
   213  	if err != nil {
   214  		t.Errorf("error parsing serialized key: %s", err)
   215  		return
   216  	}
   217  	if priv.PublicKey.N.Cmp(priv2.PublicKey.N) != 0 ||
   218  		priv.PublicKey.E != priv2.PublicKey.E ||
   219  		priv.D.Cmp(priv2.D) != 0 ||
   220  		len(priv2.Primes) != 3 ||
   221  		priv.Primes[0].Cmp(priv2.Primes[0]) != 0 ||
   222  		priv.Primes[1].Cmp(priv2.Primes[1]) != 0 ||
   223  		priv.Primes[2].Cmp(priv2.Primes[2]) != 0 {
   224  		t.Errorf("got:%+v want:%+v", priv, priv2)
   225  	}
   226  }
   227  
   228  func TestMarshalRSAPublicKey(t *testing.T) {
   229  	pub := &rsa.PublicKey{
   230  		N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"),
   231  		E: 3,
   232  	}
   233  	derBytes := MarshalPKCS1PublicKey(pub)
   234  	pub2, err := ParsePKCS1PublicKey(derBytes)
   235  	if err != nil {
   236  		t.Errorf("ParsePKCS1PublicKey: %s", err)
   237  	}
   238  	if pub.N.Cmp(pub2.N) != 0 || pub.E != pub2.E {
   239  		t.Errorf("ParsePKCS1PublicKey = %+v, want %+v", pub, pub2)
   240  	}
   241  
   242  	// It's never been documented that asn1.Marshal/Unmarshal on rsa.PublicKey works,
   243  	// but it does, and we know of code that depends on it.
   244  	// Lock that in, even though we'd prefer that people use MarshalPKCS1PublicKey and ParsePKCS1PublicKey.
   245  	derBytes2, err := asn1.Marshal(*pub)
   246  	if err != nil {
   247  		t.Errorf("Marshal(rsa.PublicKey): %v", err)
   248  	} else if !bytes.Equal(derBytes, derBytes2) {
   249  		t.Errorf("Marshal(rsa.PublicKey) = %x, want %x", derBytes2, derBytes)
   250  	}
   251  	pub3 := new(rsa.PublicKey)
   252  	rest, err := asn1.Unmarshal(derBytes, pub3)
   253  	if err != nil {
   254  		t.Errorf("Unmarshal(rsa.PublicKey): %v", err)
   255  	}
   256  	if len(rest) != 0 || pub.N.Cmp(pub3.N) != 0 || pub.E != pub3.E {
   257  		t.Errorf("Unmarshal(rsa.PublicKey) = %+v, %q want %+v, %q", pub, rest, pub2, []byte(nil))
   258  	}
   259  
   260  	publicKeys := []struct {
   261  		derBytes          []byte
   262  		expectedErrSubstr string
   263  	}{
   264  		{
   265  			derBytes: []byte{
   266  				0x30, 6, // SEQUENCE, 6 bytes
   267  				0x02, 1, // INTEGER, 1 byte
   268  				17,
   269  				0x02, 1, // INTEGER, 1 byte
   270  				3, // 3
   271  			},
   272  		}, {
   273  			derBytes: []byte{
   274  				0x30, 6, // SEQUENCE
   275  				0x02, 1, // INTEGER, 1 byte
   276  				0xff,    // -1
   277  				0x02, 1, // INTEGER, 1 byte
   278  				3,
   279  			},
   280  			expectedErrSubstr: "zero or negative",
   281  		}, {
   282  			derBytes: []byte{
   283  				0x30, 6, // SEQUENCE
   284  				0x02, 1, // INTEGER, 1 byte
   285  				17,
   286  				0x02, 1, // INTEGER, 1 byte
   287  				0xff, // -1
   288  			},
   289  			expectedErrSubstr: "zero or negative",
   290  		}, {
   291  			derBytes: []byte{
   292  				0x30, 6, // SEQUENCE
   293  				0x02, 1, // INTEGER, 1 byte
   294  				17,
   295  				0x02, 1, // INTEGER, 1 byte
   296  				3,
   297  				1,
   298  			},
   299  			expectedErrSubstr: "trailing data",
   300  		}, {
   301  			derBytes: []byte{
   302  				0x30, 9, // SEQUENCE
   303  				0x02, 1, // INTEGER, 1 byte
   304  				17,
   305  				0x02, 4, // INTEGER, 4 bytes
   306  				0x7f, 0xff, 0xff, 0xff,
   307  			},
   308  		}, {
   309  			derBytes: []byte{
   310  				0x30, 10, // SEQUENCE
   311  				0x02, 1, // INTEGER, 1 byte
   312  				17,
   313  				0x02, 5, // INTEGER, 5 bytes
   314  				0x00, 0x80, 0x00, 0x00, 0x00,
   315  			},
   316  			// On 64-bit systems, encoding/asn1 will accept the
   317  			// public exponent, but ParsePKCS1PublicKey will return
   318  			// an error. On 32-bit systems, encoding/asn1 will
   319  			// return the error. The common substring of both error
   320  			// is the word “large”.
   321  			expectedErrSubstr: "large",
   322  		},
   323  	}
   324  
   325  	for i, test := range publicKeys {
   326  		shouldFail := len(test.expectedErrSubstr) > 0
   327  		pub, err := ParsePKCS1PublicKey(test.derBytes)
   328  		if shouldFail {
   329  			if err == nil {
   330  				t.Errorf("#%d: unexpected success, got %#v", i, pub)
   331  			} else if !strings.Contains(err.Error(), test.expectedErrSubstr) {
   332  				t.Errorf("#%d: expected error containing %q, got %s", i, test.expectedErrSubstr, err)
   333  			}
   334  		} else {
   335  			if err != nil {
   336  				t.Errorf("#%d: unexpected failure: %s", i, err)
   337  				continue
   338  			}
   339  			reserialized := MarshalPKCS1PublicKey(pub)
   340  			if !bytes.Equal(reserialized, test.derBytes) {
   341  				t.Errorf("#%d: failed to reserialize: got %x, expected %x", i, reserialized, test.derBytes)
   342  			}
   343  		}
   344  	}
   345  }
   346  
   347  type matchHostnamesTest struct {
   348  	pattern, host string
   349  	ok            bool
   350  }
   351  
   352  var matchHostnamesTests = []matchHostnamesTest{
   353  	{"a.b.c", "a.b.c", true},
   354  	{"a.b.c", "b.b.c", false},
   355  	{"", "b.b.c", false},
   356  	{"a.b.c", "", false},
   357  	{"example.com", "example.com", true},
   358  	{"example.com", "www.example.com", false},
   359  	{"*.example.com", "example.com", false},
   360  	{"*.example.com", "www.example.com", true},
   361  	{"*.example.com", "www.example.com.", true},
   362  	{"*.example.com", "xyz.www.example.com", false},
   363  	{"*.example.com", "https://www.example.com", false}, // Issue 27591
   364  	{"*.example..com", "www.example..com", false},
   365  	{"www.example..com", "www.example..com", true},
   366  	{"*.*.example.com", "xyz.www.example.com", false},
   367  	{"*.www.*.com", "xyz.www.example.com", false},
   368  	{"*bar.example.com", "foobar.example.com", false},
   369  	{"f*.example.com", "foobar.example.com", false},
   370  	{"www.example.com", "*.example.com", false},
   371  	{"", ".", false},
   372  	{".", "", false},
   373  	{".", ".", false},
   374  	{"example.com", "example.com.", true},
   375  	{"example.com.", "example.com", false},
   376  	{"example.com.", "example.com.", true}, // perfect matches allow trailing dots in patterns
   377  	{"*.com.", "example.com.", false},
   378  	{"*.com.", "example.com", false},
   379  	{"*.com", "example.com", true},
   380  	{"*.com", "example.com.", true},
   381  	{"foo:bar", "foo:bar", true},
   382  	{"*.foo:bar", "xxx.foo:bar", false},
   383  	{"*.2.3.4", "1.2.3.4", false},
   384  	{"*.2.3.4", "[1.2.3.4]", false},
   385  	{"*:4860:4860::8888", "2001:4860:4860::8888", false},
   386  	{"*:4860:4860::8888", "[2001:4860:4860::8888]", false},
   387  	{"2001:4860:4860::8888", "2001:4860:4860::8888", false},
   388  	{"2001:4860:4860::8888", "[2001:4860:4860::8888]", false},
   389  	{"[2001:4860:4860::8888]", "2001:4860:4860::8888", false},
   390  	{"[2001:4860:4860::8888]", "[2001:4860:4860::8888]", false},
   391  }
   392  
   393  func TestMatchHostnames(t *testing.T) {
   394  	for i, test := range matchHostnamesTests {
   395  		c := &Certificate{DNSNames: []string{test.pattern}}
   396  		r := c.VerifyHostname(test.host) == nil
   397  		if r != test.ok {
   398  			t.Errorf("#%d mismatch got: %t want: %t when matching '%s' against '%s'", i, r, test.ok, test.host, test.pattern)
   399  		}
   400  	}
   401  }
   402  
   403  func TestMatchIP(t *testing.T) {
   404  	// Check that pattern matching is working.
   405  	c := &Certificate{
   406  		DNSNames: []string{"*.foo.bar.baz"},
   407  		Subject: pkix.Name{
   408  			CommonName: "*.foo.bar.baz",
   409  		},
   410  	}
   411  	err := c.VerifyHostname("quux.foo.bar.baz")
   412  	if err != nil {
   413  		t.Fatalf("VerifyHostname(quux.foo.bar.baz): %v", err)
   414  	}
   415  
   416  	// But check that if we change it to be matching against an IP address,
   417  	// it is rejected.
   418  	c = &Certificate{
   419  		DNSNames: []string{"*.2.3.4"},
   420  		Subject: pkix.Name{
   421  			CommonName: "*.2.3.4",
   422  		},
   423  	}
   424  	err = c.VerifyHostname("1.2.3.4")
   425  	if err == nil {
   426  		t.Fatalf("VerifyHostname(1.2.3.4) should have failed, did not")
   427  	}
   428  
   429  	c = &Certificate{
   430  		IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
   431  	}
   432  	err = c.VerifyHostname("127.0.0.1")
   433  	if err != nil {
   434  		t.Fatalf("VerifyHostname(127.0.0.1): %v", err)
   435  	}
   436  	err = c.VerifyHostname("::1")
   437  	if err != nil {
   438  		t.Fatalf("VerifyHostname(::1): %v", err)
   439  	}
   440  	err = c.VerifyHostname("[::1]")
   441  	if err != nil {
   442  		t.Fatalf("VerifyHostname([::1]): %v", err)
   443  	}
   444  }
   445  
   446  func TestCertificateParse(t *testing.T) {
   447  	s, _ := base64.StdEncoding.DecodeString(certBytes)
   448  	certs, err := ParseCertificates(s)
   449  	if err != nil {
   450  		t.Error(err)
   451  	}
   452  	if len(certs) != 2 {
   453  		t.Errorf("Wrong number of certs: got %d want 2", len(certs))
   454  		return
   455  	}
   456  
   457  	err = certs[0].CheckSignatureFrom(certs[1])
   458  	if err != nil {
   459  		t.Error(err)
   460  	}
   461  
   462  	if err := certs[0].VerifyHostname("mail.google.com"); err != nil {
   463  		t.Error(err)
   464  	}
   465  
   466  	const expectedExtensions = 10
   467  	if n := len(certs[0].Extensions); n != expectedExtensions {
   468  		t.Errorf("want %d extensions, got %d", expectedExtensions, n)
   469  	}
   470  }
   471  
   472  func TestCertificateEqualOnNil(t *testing.T) {
   473  	cNonNil := new(Certificate)
   474  	var cNil1, cNil2 *Certificate
   475  	if !cNil1.Equal(cNil2) {
   476  		t.Error("Nil certificates: cNil1 is not equal to cNil2")
   477  	}
   478  	if !cNil2.Equal(cNil1) {
   479  		t.Error("Nil certificates: cNil2 is not equal to cNil1")
   480  	}
   481  	if cNil1.Equal(cNonNil) {
   482  		t.Error("Unexpectedly cNil1 is equal to cNonNil")
   483  	}
   484  	if cNonNil.Equal(cNil1) {
   485  		t.Error("Unexpectedly cNonNil is equal to cNil1")
   486  	}
   487  }
   488  
   489  func TestMismatchedSignatureAlgorithm(t *testing.T) {
   490  	der, _ := pem.Decode([]byte(rsaPSSSelfSignedPEM))
   491  	if der == nil {
   492  		t.Fatal("Failed to find PEM block")
   493  	}
   494  
   495  	cert, err := ParseCertificate(der.Bytes)
   496  	if err != nil {
   497  		t.Fatal(err)
   498  	}
   499  
   500  	if err = cert.CheckSignature(ECDSAWithSHA256, nil, nil); err == nil {
   501  		t.Fatal("CheckSignature unexpectedly return no error")
   502  	}
   503  
   504  	const expectedSubstring = " but have public key of type "
   505  	if !strings.Contains(err.Error(), expectedSubstring) {
   506  		t.Errorf("Expected error containing %q, but got %q", expectedSubstring, err)
   507  	}
   508  }
   509  
   510  var certBytes = "MIIE0jCCA7qgAwIBAgIQWcvS+TTB3GwCAAAAAGEAWzANBgkqhkiG9w0BAQsFADBCMQswCQYD" +
   511  	"VQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZpY2VzMRMwEQYDVQQDEwpHVFMg" +
   512  	"Q0EgMU8xMB4XDTIwMDQwMTEyNTg1NloXDTIwMDYyNDEyNTg1NlowaTELMAkGA1UEBhMCVVMx" +
   513  	"EzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDU1vdW50YWluIFZpZXcxEzARBgNVBAoT" +
   514  	"Ckdvb2dsZSBMTEMxGDAWBgNVBAMTD21haWwuZ29vZ2xlLmNvbTBZMBMGByqGSM49AgEGCCqG" +
   515  	"SM49AwEHA0IABO+dYiPnkFl+cZVf6mrWeNp0RhQcJSBGH+sEJxjvc+cYlW3QJCnm57qlpFdd" +
   516  	"pz3MPyVejvXQdM6iI1mEWP4C2OujggJmMIICYjAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAww" +
   517  	"CgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUI6pZhnQ/lQgmPDwSKR2A54G7" +
   518  	"AS4wHwYDVR0jBBgwFoAUmNH4bhDrz5vsYJ8YkBug630J/SswZAYIKwYBBQUHAQEEWDBWMCcG" +
   519  	"CCsGAQUFBzABhhtodHRwOi8vb2NzcC5wa2kuZ29vZy9ndHMxbzEwKwYIKwYBBQUHMAKGH2h0" +
   520  	"dHA6Ly9wa2kuZ29vZy9nc3IyL0dUUzFPMS5jcnQwLAYDVR0RBCUwI4IPbWFpbC5nb29nbGUu" +
   521  	"Y29tghBpbmJveC5nb29nbGUuY29tMCEGA1UdIAQaMBgwCAYGZ4EMAQICMAwGCisGAQQB1nkC" +
   522  	"BQMwLwYDVR0fBCgwJjAkoCKgIIYeaHR0cDovL2NybC5wa2kuZ29vZy9HVFMxTzEuY3JsMIIB" +
   523  	"AwYKKwYBBAHWeQIEAgSB9ASB8QDvAHYAsh4FzIuizYogTodm+Su5iiUgZ2va+nDnsklTLe+L" +
   524  	"kF4AAAFxNgmxKgAABAMARzBFAiEA12/OHdTGXQ3qHHC3NvYCyB8aEz/+ZFOLCAI7lhqj28sC" +
   525  	"IG2/7Yz2zK6S6ai+dH7cTMZmoFGo39gtaTqtZAqEQX7nAHUAXqdz+d9WwOe1Nkh90EngMnqR" +
   526  	"mgyEoRIShBh1loFxRVgAAAFxNgmxTAAABAMARjBEAiA7PNq+MFfv6O9mBkxFViS2TfU66yRB" +
   527  	"/njcebWglLQjZQIgOyRKhxlEizncFRml7yn4Bg48ktXKGjo+uiw6zXEINb0wDQYJKoZIhvcN" +
   528  	"AQELBQADggEBADM2Rh306Q10PScsolYMxH1B/K4Nb2WICvpY0yDPJFdnGjqCYym196TjiEvs" +
   529  	"R6etfeHdyzlZj6nh82B4TVyHjiWM02dQgPalOuWQcuSy0OvLh7F1E7CeHzKlczdFPBTOTdM1" +
   530  	"RDTxlvw1bAqc0zueM8QIAyEy3opd7FxAcGQd5WRIJhzLBL+dbbMOW/LTeW7cm/Xzq8cgCybN" +
   531  	"BSZAvhjseJ1L29OlCTZL97IfnX0IlFQzWuvvHy7V2B0E3DHlzM0kjwkkCKDUUp/wajv2NZKC" +
   532  	"TkhEyERacZRKc9U0ADxwsAzHrdz5+5zfD2usEV/MQ5V6d8swLXs+ko0X6swrd4YCiB8wggRK" +
   533  	"MIIDMqADAgECAg0B47SaoY2KqYElaVC4MA0GCSqGSIb3DQEBCwUAMEwxIDAeBgNVBAsTF0ds" +
   534  	"b2JhbFNpZ24gUm9vdCBDQSAtIFIyMRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpH" +
   535  	"bG9iYWxTaWduMB4XDTE3MDYxNTAwMDA0MloXDTIxMTIxNTAwMDA0MlowQjELMAkGA1UEBhMC" +
   536  	"VVMxHjAcBgNVBAoTFUdvb2dsZSBUcnVzdCBTZXJ2aWNlczETMBEGA1UEAxMKR1RTIENBIDFP" +
   537  	"MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAYz0XUi83TnORA73603WkhG8nP" +
   538  	"PI5MdbkPMRmEPZ48Ke9QDRCTbwWAgJ8qoL0SSwLhPZ9YFiT+MJ8LdHdVkx1L903hkoIQ9lGs" +
   539  	"DMOyIpQPNGuYEEnnC52DOd0gxhwt79EYYWXnI4MgqCMS/9Ikf9Qv50RqW03XUGawr55CYwX7" +
   540  	"4BzEY2Gvn2oz/2KXvUjZ03wUZ9x13C5p6PhteGnQtxAFuPExwjsk/RozdPgj4OxrGYoWxuPN" +
   541  	"pM0L27OkWWA4iDutHbnGjKdTG/y82aSrvN08YdeTFZjugb2P4mRHIEAGTtesl+i5wFkSoUkl" +
   542  	"I+TtcDQspbRjfPmjPYPRzW0krAcCAwEAAaOCATMwggEvMA4GA1UdDwEB/wQEAwIBhjAdBgNV" +
   543  	"HSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4E" +
   544  	"FgQUmNH4bhDrz5vsYJ8YkBug630J/SswHwYDVR0jBBgwFoAUm+IHV2ccHsBqBt5ZtJot39wZ" +
   545  	"hi4wNQYIKwYBBQUHAQEEKTAnMCUGCCsGAQUFBzABhhlodHRwOi8vb2NzcC5wa2kuZ29vZy9n" +
   546  	"c3IyMDIGA1UdHwQrMCkwJ6AloCOGIWh0dHA6Ly9jcmwucGtpLmdvb2cvZ3NyMi9nc3IyLmNy" +
   547  	"bDA/BgNVHSAEODA2MDQGBmeBDAECAjAqMCgGCCsGAQUFBwIBFhxodHRwczovL3BraS5nb29n" +
   548  	"L3JlcG9zaXRvcnkvMA0GCSqGSIb3DQEBCwUAA4IBAQAagD42efvzLqlGN31eVBY1rsdOCJn+" +
   549  	"vdE0aSZSZgc9CrpJy2L08RqO/BFPaJZMdCvTZ96yo6oFjYRNTCBlD6WW2g0W+Gw7228EI4hr" +
   550  	"OmzBYL1on3GO7i1YNAfw1VTphln9e14NIZT1jMmo+NjyrcwPGvOap6kEJ/mjybD/AnhrYbrH" +
   551  	"NSvoVvpPwxwM7bY8tEvq7czhPOzcDYzWPpvKQliLzBYhF0C8otZm79rEFVvNiaqbCSbnMtIN" +
   552  	"bmcgAlsQsJAJnAwfnq3YO+qh/GzoEFwIUhlRKnG7rHq13RXtK8kIKiyKtKYhq2P/11JJUNCJ" +
   553  	"t63yr/tQri/hlQ3zRq2dnPXK"
   554  
   555  func parseCIDR(s string) *net.IPNet {
   556  	_, net, err := net.ParseCIDR(s)
   557  	if err != nil {
   558  		panic(err)
   559  	}
   560  	return net
   561  }
   562  
   563  func parseURI(s string) *url.URL {
   564  	uri, err := url.Parse(s)
   565  	if err != nil {
   566  		panic(err)
   567  	}
   568  	return uri
   569  }
   570  
   571  func TestCreateSelfSignedCertificate(t *testing.T) {
   572  	random := rand.Reader
   573  
   574  	ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   575  	if err != nil {
   576  		t.Fatalf("Failed to generate ECDSA key: %s", err)
   577  	}
   578  
   579  	ed25519Pub, ed25519Priv, err := ed25519.GenerateKey(random)
   580  	if err != nil {
   581  		t.Fatalf("Failed to generate Ed25519 key: %s", err)
   582  	}
   583  
   584  	tests := []struct {
   585  		name      string
   586  		pub, priv interface{}
   587  		checkSig  bool
   588  		sigAlgo   SignatureAlgorithm
   589  	}{
   590  		{"RSA/RSA", &testPrivateKey.PublicKey, testPrivateKey, true, SHA1WithRSA},
   591  		{"RSA/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
   592  		{"ECDSA/RSA", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSA},
   593  		{"ECDSA/ECDSA", &ecdsaPriv.PublicKey, ecdsaPriv, true, ECDSAWithSHA1},
   594  		{"RSAPSS/RSAPSS", &testPrivateKey.PublicKey, testPrivateKey, true, SHA256WithRSAPSS},
   595  		{"ECDSA/RSAPSS", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSAPSS},
   596  		{"RSAPSS/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
   597  		{"Ed25519", ed25519Pub, ed25519Priv, true, PureEd25519},
   598  	}
   599  
   600  	testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth}
   601  	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
   602  	extraExtensionData := []byte("extra extension")
   603  
   604  	for _, test := range tests {
   605  		commonName := "test.example.com"
   606  		//goland:noinspection HttpUrlsUsage
   607  		template := Certificate{
   608  			// SerialNumber is negative to ensure that negative
   609  			// values are parsed. This is due to the prevalence of
   610  			// buggy code that produces certificates with negative
   611  			// serial numbers.
   612  			SerialNumber: big.NewInt(-1),
   613  			Subject: pkix.Name{
   614  				CommonName:   commonName,
   615  				Organization: []string{"Σ Acme Co"},
   616  				Country:      []string{"US"},
   617  				ExtraNames: []pkix.AttributeTypeAndValue{
   618  					{
   619  						Type:  []int{2, 5, 4, 42},
   620  						Value: "Gopher",
   621  					},
   622  					// This should override the Country, above.
   623  					{
   624  						Type:  []int{2, 5, 4, 6},
   625  						Value: "NL",
   626  					},
   627  				},
   628  			},
   629  			NotBefore: time.Unix(1000, 0),
   630  			NotAfter:  time.Unix(100000, 0),
   631  
   632  			SignatureAlgorithm: test.sigAlgo,
   633  
   634  			SubjectKeyId: []byte{1, 2, 3, 4},
   635  			KeyUsage:     KeyUsageCertSign,
   636  
   637  			ExtKeyUsage:        testExtKeyUsage,
   638  			UnknownExtKeyUsage: testUnknownExtKeyUsage,
   639  
   640  			BasicConstraintsValid: true,
   641  			IsCA:                  true,
   642  
   643  			OCSPServer:            []string{"http://ocsp.example.com"},
   644  			IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
   645  
   646  			DNSNames:       []string{"test.example.com"},
   647  			EmailAddresses: []string{"gopher@golang.org"},
   648  			IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
   649  			URIs:           []*url.URL{parseURI("https://foo.com/wibble#foo")},
   650  
   651  			PolicyIdentifiers:       []asn1.ObjectIdentifier{[]int{1, 2, 3}},
   652  			PermittedDNSDomains:     []string{".example.com", "example.com"},
   653  			ExcludedDNSDomains:      []string{"bar.example.com"},
   654  			PermittedIPRanges:       []*net.IPNet{parseCIDR("192.168.1.1/16"), parseCIDR("1.2.3.4/8")},
   655  			ExcludedIPRanges:        []*net.IPNet{parseCIDR("2001:db8::/48")},
   656  			PermittedEmailAddresses: []string{"foo@example.com"},
   657  			ExcludedEmailAddresses:  []string{".example.com", "example.com"},
   658  			PermittedURIDomains:     []string{".bar.com", "bar.com"},
   659  			ExcludedURIDomains:      []string{".bar2.com", "bar2.com"},
   660  
   661  			CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
   662  
   663  			ExtraExtensions: []pkix.Extension{
   664  				{
   665  					Id:    []int{1, 2, 3, 4},
   666  					Value: extraExtensionData,
   667  				},
   668  				// This extension should override the SubjectKeyId, above.
   669  				{
   670  					Id:       oidExtensionSubjectKeyId,
   671  					Critical: false,
   672  					Value:    []byte{0x04, 0x04, 4, 3, 2, 1},
   673  				},
   674  			},
   675  		}
   676  
   677  		derBytes, err := CreateCertificate(random, &template, &template, test.pub, test.priv)
   678  		if err != nil {
   679  			t.Errorf("%s: failed to create certificate: %s", test.name, err)
   680  			continue
   681  		}
   682  
   683  		cert, err := ParseCertificate(derBytes)
   684  		if err != nil {
   685  			t.Errorf("%s: failed to parse certificate: %s", test.name, err)
   686  			continue
   687  		}
   688  
   689  		if len(cert.PolicyIdentifiers) != 1 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) {
   690  			t.Errorf("%s: failed to parse policy identifiers: got:%#v want:%#v", test.name, cert.PolicyIdentifiers, template.PolicyIdentifiers)
   691  		}
   692  
   693  		if len(cert.PermittedDNSDomains) != 2 || cert.PermittedDNSDomains[0] != ".example.com" || cert.PermittedDNSDomains[1] != "example.com" {
   694  			t.Errorf("%s: failed to parse name constraints: %#v", test.name, cert.PermittedDNSDomains)
   695  		}
   696  
   697  		if len(cert.ExcludedDNSDomains) != 1 || cert.ExcludedDNSDomains[0] != "bar.example.com" {
   698  			t.Errorf("%s: failed to parse name constraint exclusions: %#v", test.name, cert.ExcludedDNSDomains)
   699  		}
   700  
   701  		if len(cert.PermittedIPRanges) != 2 || cert.PermittedIPRanges[0].String() != "192.168.0.0/16" || cert.PermittedIPRanges[1].String() != "1.0.0.0/8" {
   702  			t.Errorf("%s: failed to parse IP constraints: %#v", test.name, cert.PermittedIPRanges)
   703  		}
   704  
   705  		if len(cert.ExcludedIPRanges) != 1 || cert.ExcludedIPRanges[0].String() != "2001:db8::/48" {
   706  			t.Errorf("%s: failed to parse IP constraint exclusions: %#v", test.name, cert.ExcludedIPRanges)
   707  		}
   708  
   709  		if len(cert.PermittedEmailAddresses) != 1 || cert.PermittedEmailAddresses[0] != "foo@example.com" {
   710  			t.Errorf("%s: failed to parse permitted email addreses: %#v", test.name, cert.PermittedEmailAddresses)
   711  		}
   712  
   713  		if len(cert.ExcludedEmailAddresses) != 2 || cert.ExcludedEmailAddresses[0] != ".example.com" || cert.ExcludedEmailAddresses[1] != "example.com" {
   714  			t.Errorf("%s: failed to parse excluded email addreses: %#v", test.name, cert.ExcludedEmailAddresses)
   715  		}
   716  
   717  		if len(cert.PermittedURIDomains) != 2 || cert.PermittedURIDomains[0] != ".bar.com" || cert.PermittedURIDomains[1] != "bar.com" {
   718  			t.Errorf("%s: failed to parse permitted URIs: %#v", test.name, cert.PermittedURIDomains)
   719  		}
   720  
   721  		if len(cert.ExcludedURIDomains) != 2 || cert.ExcludedURIDomains[0] != ".bar2.com" || cert.ExcludedURIDomains[1] != "bar2.com" {
   722  			t.Errorf("%s: failed to parse excluded URIs: %#v", test.name, cert.ExcludedURIDomains)
   723  		}
   724  
   725  		if cert.Subject.CommonName != commonName {
   726  			t.Errorf("%s: subject wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Subject.CommonName, commonName)
   727  		}
   728  
   729  		if len(cert.Subject.Country) != 1 || cert.Subject.Country[0] != "NL" {
   730  			t.Errorf("%s: ExtraNames didn't override Country", test.name)
   731  		}
   732  
   733  		for _, ext := range cert.Extensions {
   734  			if ext.Id.Equal(oidExtensionSubjectAltName) {
   735  				if ext.Critical {
   736  					t.Fatal("SAN extension is marked critical")
   737  				}
   738  			}
   739  		}
   740  
   741  		found := false
   742  		for _, atv := range cert.Subject.Names {
   743  			if atv.Type.Equal([]int{2, 5, 4, 42}) {
   744  				found = true
   745  				break
   746  			}
   747  		}
   748  		if !found {
   749  			t.Errorf("%s: Names didn't contain oid 2.5.4.42 from ExtraNames", test.name)
   750  		}
   751  
   752  		if cert.Issuer.CommonName != commonName {
   753  			t.Errorf("%s: issuer wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Issuer.CommonName, commonName)
   754  		}
   755  
   756  		if cert.SignatureAlgorithm != test.sigAlgo {
   757  			t.Errorf("%s: SignatureAlgorithm wasn't copied from template. Got %v, want %v", test.name, cert.SignatureAlgorithm, test.sigAlgo)
   758  		}
   759  
   760  		if !reflect.DeepEqual(cert.ExtKeyUsage, testExtKeyUsage) {
   761  			t.Errorf("%s: extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.ExtKeyUsage, testExtKeyUsage)
   762  		}
   763  
   764  		if !reflect.DeepEqual(cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) {
   765  			t.Errorf("%s: unknown extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.UnknownExtKeyUsage, testUnknownExtKeyUsage)
   766  		}
   767  
   768  		if !reflect.DeepEqual(cert.OCSPServer, template.OCSPServer) {
   769  			t.Errorf("%s: OCSP servers differ from template. Got %v, want %v", test.name, cert.OCSPServer, template.OCSPServer)
   770  		}
   771  
   772  		if !reflect.DeepEqual(cert.IssuingCertificateURL, template.IssuingCertificateURL) {
   773  			t.Errorf("%s: Issuing certificate URLs differ from template. Got %v, want %v", test.name, cert.IssuingCertificateURL, template.IssuingCertificateURL)
   774  		}
   775  
   776  		if !reflect.DeepEqual(cert.DNSNames, template.DNSNames) {
   777  			t.Errorf("%s: SAN DNS names differ from template. Got %v, want %v", test.name, cert.DNSNames, template.DNSNames)
   778  		}
   779  
   780  		if !reflect.DeepEqual(cert.EmailAddresses, template.EmailAddresses) {
   781  			t.Errorf("%s: SAN emails differ from template. Got %v, want %v", test.name, cert.EmailAddresses, template.EmailAddresses)
   782  		}
   783  
   784  		if len(cert.URIs) != 1 || cert.URIs[0].String() != "https://foo.com/wibble#foo" {
   785  			t.Errorf("%s: URIs differ from template. Got %v, want %v", test.name, cert.URIs, template.URIs)
   786  		}
   787  
   788  		if !reflect.DeepEqual(cert.IPAddresses, template.IPAddresses) {
   789  			t.Errorf("%s: SAN IPs differ from template. Got %v, want %v", test.name, cert.IPAddresses, template.IPAddresses)
   790  		}
   791  
   792  		if !reflect.DeepEqual(cert.CRLDistributionPoints, template.CRLDistributionPoints) {
   793  			t.Errorf("%s: CRL distribution points differ from template. Got %v, want %v", test.name, cert.CRLDistributionPoints, template.CRLDistributionPoints)
   794  		}
   795  
   796  		if !bytes.Equal(cert.SubjectKeyId, []byte{4, 3, 2, 1}) {
   797  			t.Errorf("%s: ExtraExtensions didn't override SubjectKeyId", test.name)
   798  		}
   799  
   800  		if !bytes.Contains(derBytes, extraExtensionData) {
   801  			t.Errorf("%s: didn't find extra extension in DER output", test.name)
   802  		}
   803  
   804  		if test.checkSig {
   805  			err = cert.CheckSignatureFrom(cert)
   806  			if err != nil {
   807  				t.Errorf("%s: signature verification failed: %s", test.name, err)
   808  			}
   809  		}
   810  	}
   811  }
   812  
   813  // Self-signed certificate using ECDSA with SHA1 & secp256r1
   814  var ecdsaSHA1CertPem = `
   815  -----BEGIN CERTIFICATE-----
   816  MIICDjCCAbUCCQDF6SfN0nsnrjAJBgcqhkjOPQQBMIGPMQswCQYDVQQGEwJVUzET
   817  MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEVMBMG
   818  A1UECgwMR29vZ2xlLCBJbmMuMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   819  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIwMjAyMDUw
   820  WhcNMjIwNTE4MjAyMDUwWjCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   821  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTATBgNVBAoMDEdvb2dsZSwg
   822  SW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAhBgkqhkiG9w0BCQEWFGdv
   823  bGFuZy1kZXZAZ21haWwuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/Wgn
   824  WQDo5+bz71T0327ERgd5SDDXFbXLpzIZDXTkjpe8QTEbsF+ezsQfrekrpDPC4Cd3
   825  P9LY0tG+aI8IyVKdUjAJBgcqhkjOPQQBA0gAMEUCIGlsqMcRqWVIWTD6wXwe6Jk2
   826  DKxL46r/FLgJYnzBEH99AiEA3fBouObsvV1R3oVkb4BQYnD4/4LeId6lAT43YvyV
   827  a/A=
   828  -----END CERTIFICATE-----
   829  `
   830  
   831  // Self-signed certificate using ECDSA with SHA256 & secp256r1
   832  var ecdsaSHA256p256CertPem = `
   833  -----BEGIN CERTIFICATE-----
   834  MIICDzCCAbYCCQDlsuMWvgQzhTAKBggqhkjOPQQDAjCBjzELMAkGA1UEBhMCVVMx
   835  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTAT
   836  BgNVBAoMDEdvb2dsZSwgSW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAh
   837  BgkqhkiG9w0BCQEWFGdvbGFuZy1kZXZAZ21haWwuY29tMB4XDTEyMDUyMTAwMTkx
   838  NloXDTIyMDUxOTAwMTkxNlowgY8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp
   839  Zm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRUwEwYDVQQKDAxHb29nbGUs
   840  IEluYy4xFzAVBgNVBAMMDnd3dy5nb29nbGUuY29tMSMwIQYJKoZIhvcNAQkBFhRn
   841  b2xhbmctZGV2QGdtYWlsLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPMt
   842  2ErhxAty5EJRu9yM+MTy+hUXm3pdW1ensAv382KoGExSXAFWP7pjJnNtHO+XSwVm
   843  YNtqjcAGFKpweoN//kQwCgYIKoZIzj0EAwIDRwAwRAIgIYSaUA/IB81gjbIw/hUV
   844  70twxJr5EcgOo0hLp3Jm+EYCIFDO3NNcgmURbJ1kfoS3N/0O+irUtoPw38YoNkqJ
   845  h5wi
   846  -----END CERTIFICATE-----
   847  `
   848  
   849  // Self-signed certificate using ECDSA with SHA256 & secp384r1
   850  var ecdsaSHA256p384CertPem = `
   851  -----BEGIN CERTIFICATE-----
   852  MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx
   853  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
   854  BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   855  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0
   856  WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   857  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
   858  SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
   859  YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK
   860  jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze
   861  qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI
   862  zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr
   863  PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh
   864  3yILeYQzllt/g0rKVRk=
   865  -----END CERTIFICATE-----
   866  `
   867  
   868  // Self-signed certificate using ECDSA with SHA384 & secp521r1
   869  var ecdsaSHA384p521CertPem = `
   870  -----BEGIN CERTIFICATE-----
   871  MIICljCCAfcCCQDhp1AFD/ahKjAKBggqhkjOPQQDAzCBjjELMAkGA1UEBhMCVVMx
   872  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
   873  BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   874  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMTUwNDI5
   875  WhcNMjIwNTE5MTUwNDI5WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   876  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
   877  SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
   878  YW5nLWRldkBnbWFpbC5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACqx9Rv
   879  IssRs1LWYcNN+WffwlHw4Tv3y8/LIAA9MF1ZScIonU9nRMxt4a2uGJVCPDw6JHpz
   880  PaYc0E9puLoE9AfKpwFr59Jkot7dBg55SKPEFkddoip/rvmN7NPAWjMBirOwjOkm
   881  8FPthvPhGPqsu9AvgVuHu3PosWiHGNrhh379pva8MzAKBggqhkjOPQQDAwOBjAAw
   882  gYgCQgEHNmswkUdPpHqrVxp9PvLVl+xxPuHBkT+75z9JizyxtqykHQo9Uh6SWCYH
   883  BF9KLolo01wMt8DjoYP5Fb3j5MH7xwJCAbWZzTOp4l4DPkIvAh4LeC4VWbwPPyqh
   884  kBg71w/iEcSY3wUKgHGcJJrObZw7wys91I5kENljqw/Samdr3ka+jBJa
   885  -----END CERTIFICATE-----
   886  `
   887  
   888  var ecdsaTests = []struct {
   889  	sigAlgo SignatureAlgorithm
   890  	pemCert string
   891  }{
   892  	{ECDSAWithSHA1, ecdsaSHA1CertPem},
   893  	{ECDSAWithSHA256, ecdsaSHA256p256CertPem},
   894  	{ECDSAWithSHA256, ecdsaSHA256p384CertPem},
   895  	{ECDSAWithSHA384, ecdsaSHA384p521CertPem},
   896  }
   897  
   898  func TestECDSA(t *testing.T) {
   899  	for i, test := range ecdsaTests {
   900  		pemBlock, _ := pem.Decode([]byte(test.pemCert))
   901  		cert, err := ParseCertificate(pemBlock.Bytes)
   902  		if err != nil {
   903  			t.Errorf("%d: failed to parse certificate: %s", i, err)
   904  			continue
   905  		}
   906  		if sa := cert.SignatureAlgorithm; sa != test.sigAlgo {
   907  			t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo)
   908  		}
   909  		if parsedKey, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok {
   910  			t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey)
   911  		}
   912  		if pka := cert.PublicKeyAlgorithm; pka != ECDSA {
   913  			t.Errorf("%d: public key algorithm is %v, want ECDSA", i, pka)
   914  		}
   915  		if err = cert.CheckSignatureFrom(cert); err != nil {
   916  			t.Errorf("%d: certificate verification failed: %s", i, err)
   917  		}
   918  	}
   919  }
   920  
   921  // Self-signed certificate using DSA with SHA1
   922  var dsaCertPem = `-----BEGIN CERTIFICATE-----
   923  MIIEDTCCA82gAwIBAgIJALHPghaoxeDhMAkGByqGSM44BAMweTELMAkGA1UEBhMC
   924  VVMxCzAJBgNVBAgTAk5DMQ8wDQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2ds
   925  ZSwgSW5jMRIwEAYDVQQDEwlKb24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFs
   926  bGllQGdvb2dsZS5jb20wHhcNMTEwNTE0MDMwMTQ1WhcNMTEwNjEzMDMwMTQ1WjB5
   927  MQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkMxDzANBgNVBAcTBk5ld3RvbjEUMBIG
   928  A1UEChMLR29vZ2xlLCBJbmMxEjAQBgNVBAMTCUpvbiBBbGxpZTEiMCAGCSqGSIb3
   929  DQEJARYTam9uYWxsaWVAZ29vZ2xlLmNvbTCCAbcwggEsBgcqhkjOOAQBMIIBHwKB
   930  gQC8hLUnQ7FpFYu4WXTj6DKvXvz8QrJkNJCVMTpKAT7uBpobk32S5RrPKXocd4gN
   931  8lyGB9ggS03EVlEwXvSmO0DH2MQtke2jl9j1HLydClMf4sbx5V6TV9IFw505U1iW
   932  jL7awRMgxge+FsudtJK254FjMFo03ZnOQ8ZJJ9E6AEDrlwIVAJpnBn9moyP11Ox5
   933  Asc/5dnjb6dPAoGBAJFHd4KVv1iTVCvEG6gGiYop5DJh28hUQcN9kul+2A0yPUSC
   934  X93oN00P8Vh3eYgSaCWZsha7zDG53MrVJ0Zf6v/X/CoZNhLldeNOepivTRAzn+Rz
   935  kKUYy5l1sxYLHQKF0UGNCXfFKZT0PCmgU+PWhYNBBMn6/cIh44vp85ideo5CA4GE
   936  AAKBgFmifCafzeRaohYKXJgMGSEaggCVCRq5xdyDCat+wbOkjC4mfG01/um3G8u5
   937  LxasjlWRKTR/tcAL7t0QuokVyQaYdVypZXNaMtx1db7YBuHjj3aP+8JOQRI9xz8c
   938  bp5NDJ5pISiFOv4p3GZfqZPcqckDt78AtkQrmnal2txhhjF6o4HeMIHbMB0GA1Ud
   939  DgQWBBQVyyr7hO11ZFFpWX50298Sa3V+rzCBqwYDVR0jBIGjMIGggBQVyyr7hO11
   940  ZFFpWX50298Sa3V+r6F9pHsweTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAk5DMQ8w
   941  DQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2dsZSwgSW5jMRIwEAYDVQQDEwlK
   942  b24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFsbGllQGdvb2dsZS5jb22CCQCx
   943  z4IWqMXg4TAMBgNVHRMEBTADAQH/MAkGByqGSM44BAMDLwAwLAIUPtn/5j8Q1jJI
   944  7ggOIsgrhgUdjGQCFCsmDq1H11q9+9Wp9IMeGrTSKHIM
   945  -----END CERTIFICATE-----
   946  `
   947  
   948  // func TestParseCertificateWithDsaPublicKey(t *testing.T) {
   949  // 	expectedKey := &dsa.PublicKey{
   950  // 		Parameters: dsa.Parameters{
   951  // 			P: bigFromHexString("00BC84B52743B169158BB85974E3E832AF5EFCFC42B264349095313A4A013EEE069A1B937D92E51ACF297A1C77880DF25C8607D8204B4DC45651305EF4A63B40C7D8C42D91EDA397D8F51CBC9D0A531FE2C6F1E55E9357D205C39D395358968CBEDAC11320C607BE16CB9DB492B6E78163305A34DD99CE43C64927D13A0040EB97"),
   952  // 			Q: bigFromHexString("009A67067F66A323F5D4EC7902C73FE5D9E36FA74F"),
   953  // 			G: bigFromHexString("009147778295BF5893542BC41BA806898A29E43261DBC85441C37D92E97ED80D323D44825FDDE8374D0FF15877798812682599B216BBCC31B9DCCAD527465FEAFFD7FC2A193612E575E34E7A98AF4D10339FE47390A518CB9975B3160B1D0285D1418D0977C52994F43C29A053E3D685834104C9FAFDC221E38BE9F3989D7A8E42"),
   954  // 		},
   955  // 		Y: bigFromHexString("59A27C269FCDE45AA2160A5C980C19211A820095091AB9C5DC8309AB7EC1B3A48C2E267C6D35FEE9B71BCBB92F16AC8E559129347FB5C00BEEDD10BA8915C90698755CA965735A32DC7575BED806E1E38F768FFBC24E41123DC73F1C6E9E4D0C9E692128853AFE29DC665FA993DCA9C903B7BF00B6442B9A76A5DADC6186317A"),
   956  // 	}
   957  // 	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   958  // 	cert, err := ParseCertificate(pemBlock.Bytes)
   959  // 	if err != nil {
   960  // 		t.Fatalf("Failed to parse certificate: %s", err)
   961  // 	}
   962  // 	if cert.PublicKeyAlgorithm != DSA {
   963  // 		t.Errorf("Parsed key algorithm was not DSA")
   964  // 	}
   965  // 	parsedKey, ok := cert.PublicKey.(*dsa.PublicKey)
   966  // 	if !ok {
   967  // 		t.Fatalf("Parsed key was not a DSA key: %s", err)
   968  // 	}
   969  // 	if expectedKey.Y.Cmp(parsedKey.Y) != 0 ||
   970  // 		expectedKey.P.Cmp(parsedKey.P) != 0 ||
   971  // 		expectedKey.Q.Cmp(parsedKey.Q) != 0 ||
   972  // 		expectedKey.G.Cmp(parsedKey.G) != 0 {
   973  // 		t.Fatal("Parsed key differs from expected key")
   974  // 	}
   975  // }
   976  
   977  func TestParseCertificateWithDSASignatureAlgorithm(t *testing.T) {
   978  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   979  	cert, err := ParseCertificate(pemBlock.Bytes)
   980  	if err != nil {
   981  		t.Fatalf("Failed to parse certificate: %s", err)
   982  	}
   983  	if cert.SignatureAlgorithm != DSAWithSHA1 {
   984  		t.Errorf("Parsed signature algorithm was not DSAWithSHA1")
   985  	}
   986  }
   987  
   988  func TestVerifyCertificateWithDSASignature(t *testing.T) {
   989  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   990  	cert, err := ParseCertificate(pemBlock.Bytes)
   991  	if err != nil {
   992  		t.Fatalf("Failed to parse certificate: %s", err)
   993  	}
   994  	// test cert is self-signed
   995  	if err = cert.CheckSignatureFrom(cert); err == nil {
   996  		t.Fatalf("Expected error verifying DSA certificate")
   997  	}
   998  }
   999  
  1000  var rsaPSSSelfSignedPEM = `-----BEGIN CERTIFICATE-----
  1001  MIIGHjCCA9KgAwIBAgIBdjBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA
  1002  oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCASAwbjELMAkGA1UEBhMC
  1003  SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
  1004  aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
  1005  U0NBMB4XDTEzMDUxNDA1MDczMFoXDTI5MDUxNDA1MDczMFowbjELMAkGA1UEBhMC
  1006  SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
  1007  aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
  1008  U0NBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAx/E3WRVxcCDXhoST
  1009  8nVSLjW6hwM4Ni99AegWzcGtfGFo0zjFA1Cl5URqxauvYu3gQgQHBGA1CovWeGrl
  1010  yVSRzOL1imcYsSgLOcnhVYB3Xcrof4ebv9+W+TwNdc9YzAwcj8rNd5nP6PKXIQ+W
  1011  PCkEOXdyb80YEnxuT+NPjkVfFSPBS7QYZpvT2fwy4fZ0eh48253+7VleSmTO0mqj
  1012  7TlzaG56q150SLZbhpOd8jD8bM/wACnLCPR88wj4hCcDLEwoLyY85HJCTIQQMnoT
  1013  UpqyzEeupPREIm6yi4d8C9YqIWFn2YTnRcWcmMaJLzq+kYwKoudfnoC6RW2vzZXn
  1014  defQs68IZuK+uALu9G3JWGPgu0CQGj0JNDT8zkiDV++4eNrZczWKjr1YnAL+VbLK
  1015  bApwL2u19l2WDpfUklimhWfraqHNIUKU6CjZOG31RzXcplIj0mtqs0E1r7r357Es
  1016  yFoB28iNo4cz1lCulh0E4WJzWzLZcT4ZspHHRCFyvYnXoibXEV1nULq8ByKKG0FS
  1017  7nn4SseoV+8PvjHLPhmHGMvi4mxkbcXdV3wthHT1/HXdqY84A4xHWt1+sB/TpTek
  1018  tDhFlEfcUygvTu58UtOnysomOVVeERmi7WSujfzKsGJAJYeetiA5R+zX7BxeyFVE
  1019  qW0zh1Tkwh0S8LRe5diJh4+6FG0CAwEAAaNfMF0wHQYDVR0OBBYEFD+oahaikBTV
  1020  Urk81Uz7kRS2sx0aMA4GA1UdDwEB/wQEAwIBBjAYBgNVHSAEETAPMA0GCyqDCIaP
  1021  fgYFAQEBMBIGA1UdEwEB/wQIMAYBAf8CAQAwQQYJKoZIhvcNAQEKMDSgDzANBglg
  1022  hkgBZQMEAgEFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgEFAKIDAgEgA4IC
  1023  AQAaxWBQn5CZuNBfyzL57mn31ukHUFd61OMROSX3PT7oCv1Dy+C2AdRlxOcbN3/n
  1024  li0yfXUUqiY3COlLAHKRlkr97mLtxEFoJ0R8nVN2IQdChNQM/XSCzSGyY8NVa1OR
  1025  TTpEWLnexJ9kvIdbFXwUqdTnAkOI0m7Rg8j+E+lRRHg1xDAA1qKttrtUj3HRQWf3
  1026  kNTu628SiMvap6aIdncburaK56MP7gkR1Wr/ichOfjIA3Jgw2PapI31i0GqeMd66
  1027  U1+lC9FeyMAJpuSVp/SoiYzYo+79SFcVoM2yw3yAnIKg7q9GLYYqzncdykT6C06c
  1028  15gWFI6igmReAsD9ITSvYh0jLrLHfEYcPTOD3ZXJ4EwwHtWSoO3gq1EAtOYKu/Lv
  1029  C8zfBsZcFdsHvsSiYeBU8Oioe42mguky3Ax9O7D805Ek6R68ra07MW/G4YxvV7IN
  1030  2BfSaYy8MX9IG0ZMIOcoc0FeF5xkFmJ7kdrlTaJzC0IE9PNxNaH5QnOAFB8vxHcO
  1031  FioUxb6UKdHcPLR1VZtAdTdTMjSJxUqD/35Cdfqs7oDJXz8f6TXO2Tdy6G++YUs9
  1032  qsGZWxzFvvkXUkQSl0dQQ5jO/FtUJcAVXVVp20LxPemfatAHpW31WdJYeWSQWky2
  1033  +f9b5TXKXVyjlUL7uHxowWrT2AtTchDH22wTEtqLEF9Z3Q==
  1034  -----END CERTIFICATE-----`
  1035  
  1036  // openssl req -newkey rsa:2048 -keyout test.key -sha256 -sigopt \
  1037  // rsa_padding_mode:pss -sigopt rsa_pss_saltlen:32 -sigopt rsa_mgf1_md:sha256 \
  1038  // -x509 -days 3650 -nodes -subj '/C=US/ST=CA/L=SF/O=Test/CN=Test' -out \
  1039  // test.pem
  1040  var rsaPSSSelfSignedOpenSSL110PEM = `-----BEGIN CERTIFICATE-----
  1041  MIIDwDCCAnigAwIBAgIJAM9LAMHTE5xpMD0GCSqGSIb3DQEBCjAwoA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o2kmlR0qZOXAg5augmCQ1xS0WHFoF6B52anNzHkZQbAIYJ3kGoFsUHzs7Sz7F/
  1058  656FsRpHA9UzJQ3avPPMrA4Y4aoJ7ANJ6XIwTrdWrhULOVuvYRLCl4CdTVztVFX6
  1059  wxX8nS1ISYd8jXPUMgsBKVbWufvLoIymMJW8CZbpprVZel5zFn0bmPrON8IHS30w
  1060  Gs+ITJjKEnZgXmAQ25SLKVzkZkBcGANs2GsdHNJ370Puisy0FIPD2NXR5uASAf7J
  1061  +w9fjQ==
  1062  -----END CERTIFICATE-----`
  1063  
  1064  func TestRSAPSSSelfSigned(t *testing.T) {
  1065  	for i, pemBlock := range []string{rsaPSSSelfSignedPEM, rsaPSSSelfSignedOpenSSL110PEM} {
  1066  		der, _ := pem.Decode([]byte(pemBlock))
  1067  		if der == nil {
  1068  			t.Errorf("#%d: failed to find PEM block", i)
  1069  			continue
  1070  		}
  1071  
  1072  		cert, err := ParseCertificate(der.Bytes)
  1073  		if err != nil {
  1074  			t.Errorf("#%d: failed to parse: %s", i, err)
  1075  			continue
  1076  		}
  1077  
  1078  		if err = cert.CheckSignatureFrom(cert); err != nil {
  1079  			t.Errorf("#%d: signature check failed: %s", i, err)
  1080  			continue
  1081  		}
  1082  	}
  1083  }
  1084  
  1085  const ed25519Certificate = `
  1086  Certificate:
  1087      Data:
  1088          Version: 3 (0x2)
  1089          Serial Number:
  1090              0c:83:d8:21:2b:82:cb:23:98:23:63:e2:f7:97:8a:43:5b:f3:bd:92
  1091          Signature Algorithm: ED25519
  1092          Issuer: CN = Ed25519 test certificate
  1093          Validity
  1094              Not Before: May  6 17:27:16 2019 GMT
  1095              Not After : Jun  5 17:27:16 2019 GMT
  1096          Subject: CN = Ed25519 test certificate
  1097          Subject Public Key Info:
  1098              Public Key Algorithm: ED25519
  1099                  ED25519 Public-Key:
  1100                  pub:
  1101                      36:29:c5:6c:0d:4f:14:6c:81:d0:ff:75:d3:6a:70:
  1102                      5f:69:cd:0f:4d:66:d5:da:98:7e:82:49:89:a3:8a:
  1103                      3c:fa
  1104          X509v3 extensions:
  1105              X509v3 Subject Key Identifier:
  1106                  09:3B:3A:9D:4A:29:D8:95:FF:68:BE:7B:43:54:72:E0:AD:A2:E3:AE
  1107              X509v3 Authority Key Identifier:
  1108                  keyid:09:3B:3A:9D:4A:29:D8:95:FF:68:BE:7B:43:54:72:E0:AD:A2:E3:AE
  1109  
  1110              X509v3 Basic Constraints: critical
  1111                  CA:TRUE
  1112      Signature Algorithm: ED25519
  1113           53:a5:58:1c:2c:3b:2a:9e:ac:9d:4e:a5:1d:5f:5d:6d:a6:b5:
  1114           08:de:12:82:f3:97:20:ae:fa:d8:98:f4:1a:83:32:6b:91:f5:
  1115           24:1d:c4:20:7f:2c:e2:4d:da:13:3b:6d:54:1a:d2:a8:28:dc:
  1116           60:b9:d4:f4:78:4b:3c:1c:91:00
  1117  -----BEGIN CERTIFICATE-----
  1118  MIIBWzCCAQ2gAwIBAgIUDIPYISuCyyOYI2Pi95eKQ1vzvZIwBQYDK2VwMCMxITAf
  1119  BgNVBAMMGEVkMjU1MTkgdGVzdCBjZXJ0aWZpY2F0ZTAeFw0xOTA1MDYxNzI3MTZa
  1120  Fw0xOTA2MDUxNzI3MTZaMCMxITAfBgNVBAMMGEVkMjU1MTkgdGVzdCBjZXJ0aWZp
  1121  Y2F0ZTAqMAUGAytlcAMhADYpxWwNTxRsgdD/ddNqcF9pzQ9NZtXamH6CSYmjijz6
  1122  o1MwUTAdBgNVHQ4EFgQUCTs6nUop2JX/aL57Q1Ry4K2i464wHwYDVR0jBBgwFoAU
  1123  CTs6nUop2JX/aL57Q1Ry4K2i464wDwYDVR0TAQH/BAUwAwEB/zAFBgMrZXADQQBT
  1124  pVgcLDsqnqydTqUdX11tprUI3hKC85cgrvrYmPQagzJrkfUkHcQgfyziTdoTO21U
  1125  GtKoKNxgudT0eEs8HJEA
  1126  -----END CERTIFICATE-----`
  1127  
  1128  func TestEd25519SelfSigned(t *testing.T) {
  1129  	der, _ := pem.Decode([]byte(ed25519Certificate))
  1130  	if der == nil {
  1131  		t.Fatalf("Failed to find PEM block")
  1132  	}
  1133  
  1134  	cert, err := ParseCertificate(der.Bytes)
  1135  	if err != nil {
  1136  		t.Fatalf("Failed to parse: %s", err)
  1137  	}
  1138  
  1139  	if cert.PublicKeyAlgorithm != Ed25519 {
  1140  		t.Fatalf("Parsed key algorithm was not Ed25519")
  1141  	}
  1142  	parsedKey, ok := cert.PublicKey.(ed25519.PublicKey)
  1143  	if !ok {
  1144  		t.Fatalf("Parsed key was not an Ed25519 key: %s", err)
  1145  	}
  1146  	if len(parsedKey) != ed25519.PublicKeySize {
  1147  		t.Fatalf("Invalid Ed25519 key")
  1148  	}
  1149  
  1150  	if err = cert.CheckSignatureFrom(cert); err != nil {
  1151  		t.Fatalf("Signature check failed: %s", err)
  1152  	}
  1153  }
  1154  
  1155  const pemCertificate = `-----BEGIN CERTIFICATE-----
  1156  MIIDATCCAemgAwIBAgIRAKQkkrFx1T/dgB/Go/xBM5swDQYJKoZIhvcNAQELBQAw
  1157  EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xNjA4MTcyMDM2MDdaFw0xNzA4MTcyMDM2
  1158  MDdaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
  1159  ggEKAoIBAQDAoJtjG7M6InsWwIo+l3qq9u+g2rKFXNu9/mZ24XQ8XhV6PUR+5HQ4
  1160  jUFWC58ExYhottqK5zQtKGkw5NuhjowFUgWB/VlNGAUBHtJcWR/062wYrHBYRxJH
  1161  qVXOpYKbIWwFKoXu3hcpg/CkdOlDWGKoZKBCwQwUBhWE7MDhpVdQ+ZljUJWL+FlK
  1162  yQK5iRsJd5TGJ6VUzLzdT4fmN2DzeK6GLeyMpVpU3sWV90JJbxWQ4YrzkKzYhMmB
  1163  EcpXTG2wm+ujiHU/k2p8zlf8Sm7VBM/scmnMFt0ynNXop4FWvJzEm1G0xD2t+e2I
  1164  5Utr04dOZPCgkm++QJgYhtZvgW7ZZiGTAgMBAAGjUjBQMA4GA1UdDwEB/wQEAwIF
  1165  oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBsGA1UdEQQUMBKC
  1166  EHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEBADpqKQxrthH5InC7
  1167  X96UP0OJCu/lLEMkrjoEWYIQaFl7uLPxKH5AmQPH4lYwF7u7gksR7owVG9QU9fs6
  1168  1fK7II9CVgCd/4tZ0zm98FmU4D0lHGtPARrrzoZaqVZcAvRnFTlPX5pFkPhVjjai
  1169  /mkxX9LpD8oK1445DFHxK5UjLMmPIIWd8EOi+v5a+hgGwnJpoW7hntSl8kHMtTmy
  1170  fnnktsblSUV4lRCit0ymC7Ojhe+gzCCwkgs5kDzVVag+tnl/0e2DloIjASwOhpbH
  1171  KVcg7fBd484ht/sS+l0dsB4KDOSpd8JzVDMF8OZqlaydizoJO0yWr9GbCN1+OKq5
  1172  EhLrEqU=
  1173  -----END CERTIFICATE-----`
  1174  
  1175  const ed25519CRLCertificate = `
  1176  Certificate:
  1177  Data:
  1178  	Version: 3 (0x2)
  1179  	Serial Number:
  1180  		7a:07:a0:9d:14:04:16:fc:1f:d8:e5:fe:d1:1d:1f:8d
  1181  	Signature Algorithm: ED25519
  1182  	Issuer: CN = Ed25519 CRL Test CA
  1183  	Validity
  1184  		Not Before: Oct 30 01:20:20 2019 GMT
  1185  		Not After : Dec 31 23:59:59 9999 GMT
  1186  	Subject: CN = Ed25519 CRL Test CA
  1187  	Subject Public Key Info:
  1188  		Public Key Algorithm: ED25519
  1189  			ED25519 Public-Key:
  1190  			pub:
  1191  				95:73:3b:b0:06:2a:31:5a:b6:a7:a6:6e:ef:71:df:
  1192  				ac:6f:6b:39:03:85:5e:63:4b:f8:a6:0f:68:c6:6f:
  1193  				75:21
  1194  	X509v3 extensions:
  1195  		X509v3 Key Usage: critical
  1196  			Digital Signature, Certificate Sign, CRL Sign
  1197  		X509v3 Extended Key Usage: 
  1198  			TLS Web Client Authentication, TLS Web Server Authentication, OCSP Signing
  1199  		X509v3 Basic Constraints: critical
  1200  			CA:TRUE
  1201  		X509v3 Subject Key Identifier: 
  1202  			B7:17:DA:16:EA:C5:ED:1F:18:49:44:D3:D2:E3:A0:35:0A:81:93:60
  1203  		X509v3 Authority Key Identifier: 
  1204  			keyid:B7:17:DA:16:EA:C5:ED:1F:18:49:44:D3:D2:E3:A0:35:0A:81:93:60
  1205  
  1206  Signature Algorithm: ED25519
  1207  	 fc:3e:14:ea:bb:70:c2:6f:38:34:70:bc:c8:a7:f4:7c:0d:1e:
  1208  	 28:d7:2a:9f:22:8a:45:e8:02:76:84:1e:2d:64:2d:1e:09:b5:
  1209  	 29:71:1f:95:8a:4e:79:87:51:60:9a:e7:86:40:f6:60:c7:d1:
  1210  	 ee:68:76:17:1d:90:cc:92:93:07
  1211  -----BEGIN CERTIFICATE-----
  1212  MIIBijCCATygAwIBAgIQegegnRQEFvwf2OX+0R0fjTAFBgMrZXAwHjEcMBoGA1UE
  1213  AxMTRWQyNTUxOSBDUkwgVGVzdCBDQTAgFw0xOTEwMzAwMTIwMjBaGA85OTk5MTIz
  1214  MTIzNTk1OVowHjEcMBoGA1UEAxMTRWQyNTUxOSBDUkwgVGVzdCBDQTAqMAUGAytl
  1215  cAMhAJVzO7AGKjFatqembu9x36xvazkDhV5jS/imD2jGb3Uho4GNMIGKMA4GA1Ud
  1216  DwEB/wQEAwIBhjAnBgNVHSUEIDAeBggrBgEFBQcDAgYIKwYBBQUHAwEGCCsGAQUF
  1217  BwMJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFLcX2hbqxe0fGElE09LjoDUK
  1218  gZNgMB8GA1UdIwQYMBaAFLcX2hbqxe0fGElE09LjoDUKgZNgMAUGAytlcANBAPw+
  1219  FOq7cMJvODRwvMin9HwNHijXKp8iikXoAnaEHi1kLR4JtSlxH5WKTnmHUWCa54ZA
  1220  9mDH0e5odhcdkMySkwc=
  1221  -----END CERTIFICATE-----`
  1222  
  1223  var ed25519CRLKey = testingKey(`-----BEGIN TEST KEY-----
  1224  MC4CAQAwBQYDK2VwBCIEINdKh2096vUBYu4EIFpjShsUSh3vimKya1sQ1YTT4RZG
  1225  -----END TEST KEY-----`)
  1226  
  1227  func TestCRLCreation(t *testing.T) {
  1228  	block, _ := pem.Decode([]byte(pemPrivateKey))
  1229  	privRSA, _ := ParsePKCS1PrivateKey(block.Bytes)
  1230  	block, _ = pem.Decode([]byte(pemCertificate))
  1231  	certRSA, _ := ParseCertificate(block.Bytes)
  1232  
  1233  	block, _ = pem.Decode([]byte(ed25519CRLKey))
  1234  	privEd25519, _ := ParsePKCS8PrivateKey(block.Bytes)
  1235  	block, _ = pem.Decode([]byte(ed25519CRLCertificate))
  1236  	certEd25519, _ := ParseCertificate(block.Bytes)
  1237  
  1238  	tests := []struct {
  1239  		name string
  1240  		priv interface{}
  1241  		cert *Certificate
  1242  	}{
  1243  		{"RSA CA", privRSA, certRSA},
  1244  		{"Ed25519 CA", privEd25519, certEd25519},
  1245  	}
  1246  
  1247  	loc := time.FixedZone("Oz/Atlantis", int((2 * time.Hour).Seconds()))
  1248  
  1249  	now := time.Unix(1000, 0).In(loc)
  1250  	nowUTC := now.UTC()
  1251  	expiry := time.Unix(10000, 0)
  1252  
  1253  	revokedCerts := []pkix.RevokedCertificate{
  1254  		{
  1255  			SerialNumber:   big.NewInt(1),
  1256  			RevocationTime: nowUTC,
  1257  		},
  1258  		{
  1259  			SerialNumber: big.NewInt(42),
  1260  			// RevocationTime should be converted to UTC before marshaling.
  1261  			RevocationTime: now,
  1262  		},
  1263  	}
  1264  	expectedCerts := []pkix.RevokedCertificate{
  1265  		{
  1266  			SerialNumber:   big.NewInt(1),
  1267  			RevocationTime: nowUTC,
  1268  		},
  1269  		{
  1270  			SerialNumber:   big.NewInt(42),
  1271  			RevocationTime: nowUTC,
  1272  		},
  1273  	}
  1274  
  1275  	for _, test := range tests {
  1276  		crlBytes, err := test.cert.CreateCRL(rand.Reader, test.priv, revokedCerts, now, expiry)
  1277  		if err != nil {
  1278  			t.Errorf("%s: error creating CRL: %s", test.name, err)
  1279  		}
  1280  
  1281  		parsedCRL, err := ParseDERCRL(crlBytes)
  1282  		if err != nil {
  1283  			t.Errorf("%s: error reparsing CRL: %s", test.name, err)
  1284  		}
  1285  		if !reflect.DeepEqual(parsedCRL.TBSCertList.RevokedCertificates, expectedCerts) {
  1286  			t.Errorf("%s: RevokedCertificates mismatch: got %v; want %v.", test.name,
  1287  				parsedCRL.TBSCertList.RevokedCertificates, expectedCerts)
  1288  		}
  1289  	}
  1290  }
  1291  
  1292  func fromBase64(in string) []byte {
  1293  	out := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
  1294  	n, err := base64.StdEncoding.Decode(out, []byte(in))
  1295  	if err != nil {
  1296  		panic("failed to base64 decode")
  1297  	}
  1298  	return out[:n]
  1299  }
  1300  
  1301  func TestParseDERCRL(t *testing.T) {
  1302  	derBytes := fromBase64(derCRLBase64)
  1303  	certList, err := ParseDERCRL(derBytes)
  1304  	if err != nil {
  1305  		t.Errorf("error parsing: %s", err)
  1306  		return
  1307  	}
  1308  	numCerts := len(certList.TBSCertList.RevokedCertificates)
  1309  	expected := 88
  1310  	if numCerts != expected {
  1311  		t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
  1312  	}
  1313  
  1314  	if certList.HasExpired(time.Unix(1302517272, 0)) {
  1315  		t.Errorf("CRL has expired (but shouldn't have)")
  1316  	}
  1317  
  1318  	// Can't check the signature here without a package cycle.
  1319  }
  1320  
  1321  func TestCRLWithoutExpiry(t *testing.T) {
  1322  	derBytes := fromBase64("MIHYMIGZMAkGByqGSM44BAMwEjEQMA4GA1UEAxMHQ2FybERTUxcNOTkwODI3MDcwMDAwWjBpMBMCAgDIFw05OTA4MjIwNzAwMDBaMBMCAgDJFw05OTA4MjIwNzAwMDBaMBMCAgDTFw05OTA4MjIwNzAwMDBaMBMCAgDSFw05OTA4MjIwNzAwMDBaMBMCAgDUFw05OTA4MjQwNzAwMDBaMAkGByqGSM44BAMDLwAwLAIUfmVSdjP+NHMX0feW+aDU2G1cfT0CFAJ6W7fVWxjBz4fvftok8yqDnDWh")
  1323  	certList, err := ParseDERCRL(derBytes)
  1324  	if err != nil {
  1325  		t.Fatal(err)
  1326  	}
  1327  	if !certList.TBSCertList.NextUpdate.IsZero() {
  1328  		t.Errorf("NextUpdate is not the zero value")
  1329  	}
  1330  }
  1331  
  1332  func TestParsePEMCRL(t *testing.T) {
  1333  	pemBytes := fromBase64(pemCRLBase64)
  1334  	certList, err := ParseCRL(pemBytes)
  1335  	if err != nil {
  1336  		t.Errorf("error parsing: %s", err)
  1337  		return
  1338  	}
  1339  	numCerts := len(certList.TBSCertList.RevokedCertificates)
  1340  	expected := 2
  1341  	if numCerts != expected {
  1342  		t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
  1343  	}
  1344  
  1345  	if certList.HasExpired(time.Unix(1302517272, 0)) {
  1346  		t.Errorf("CRL has expired (but shouldn't have)")
  1347  	}
  1348  
  1349  	// Can't check the signature here without a package cycle.
  1350  }
  1351  
  1352  func TestImports(t *testing.T) {
  1353  	if testing.Short() {
  1354  		t.Skip("skipping in -short mode")
  1355  	}
  1356  	testenv.MustHaveGoRun(t)
  1357  
  1358  	if out, err := exec.Command(testenv.GoToolPath(t), "run", "x509_test_import.go").CombinedOutput(); err != nil {
  1359  		t.Errorf("failed to run x509_test_import.go: %s\n%s", err, out)
  1360  	}
  1361  }
  1362  
  1363  const derCRLBase64 = "MIINqzCCDJMCAQEwDQYJKoZIhvcNAQEFBQAwVjEZMBcGA1UEAxMQUEtJIEZJTk1FQ0NBTklDQTEVMBMGA1UEChMMRklOTUVDQ0FOSUNBMRUwEwYDVQQLEwxGSU5NRUNDQU5JQ0ExCzAJBgNVBAYTAklUFw0xMTA1MDQxNjU3NDJaFw0xMTA1MDQyMDU3NDJaMI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K2k2N0x6dmhJNmMyOUVlNks5cFNZd2ppLzdSVWhtbW5Qclh0VHhsTDBsckxyDQptUVFKNnhoRFJhNUczUUE0Q21VZHNITnZicnpnbUNZcHZWRT0NCi0tLS0tRU5EIFg1MDkgQ1JMLS0tLS0NCg0K"
  1366  
  1367  func TestCreateCertificateRequest(t *testing.T) {
  1368  	random := rand.Reader
  1369  
  1370  	ecdsa256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1371  	if err != nil {
  1372  		t.Fatalf("Failed to generate ECDSA key: %s", err)
  1373  	}
  1374  
  1375  	ecdsa384Priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  1376  	if err != nil {
  1377  		t.Fatalf("Failed to generate ECDSA key: %s", err)
  1378  	}
  1379  
  1380  	ecdsa521Priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
  1381  	if err != nil {
  1382  		t.Fatalf("Failed to generate ECDSA key: %s", err)
  1383  	}
  1384  
  1385  	_, ed25519Priv, err := ed25519.GenerateKey(random)
  1386  	if err != nil {
  1387  		t.Fatalf("Failed to generate Ed25519 key: %s", err)
  1388  	}
  1389  
  1390  	tests := []struct {
  1391  		name    string
  1392  		priv    interface{}
  1393  		sigAlgo SignatureAlgorithm
  1394  	}{
  1395  		{"RSA", testPrivateKey, SHA1WithRSA},
  1396  		{"ECDSA-256", ecdsa256Priv, ECDSAWithSHA1},
  1397  		{"ECDSA-384", ecdsa384Priv, ECDSAWithSHA1},
  1398  		{"ECDSA-521", ecdsa521Priv, ECDSAWithSHA1},
  1399  		{"Ed25519", ed25519Priv, PureEd25519},
  1400  	}
  1401  
  1402  	for _, test := range tests {
  1403  		template := CertificateRequest{
  1404  			Subject: pkix.Name{
  1405  				CommonName:   "test.example.com",
  1406  				Organization: []string{"Σ Acme Co"},
  1407  			},
  1408  			SignatureAlgorithm: test.sigAlgo,
  1409  			DNSNames:           []string{"test.example.com"},
  1410  			EmailAddresses:     []string{"gopher@golang.org"},
  1411  			IPAddresses:        []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
  1412  		}
  1413  
  1414  		derBytes, err := CreateCertificateRequest(random, &template, test.priv)
  1415  		if err != nil {
  1416  			t.Errorf("%s: failed to create certificate request: %s", test.name, err)
  1417  			continue
  1418  		}
  1419  
  1420  		out, err := ParseCertificateRequest(derBytes)
  1421  		if err != nil {
  1422  			t.Errorf("%s: failed to create certificate request: %s", test.name, err)
  1423  			continue
  1424  		}
  1425  
  1426  		err = out.CheckSignature()
  1427  		if err != nil {
  1428  			t.Errorf("%s: failed to check certificate request signature: %s", test.name, err)
  1429  			continue
  1430  		}
  1431  
  1432  		if out.Subject.CommonName != template.Subject.CommonName {
  1433  			t.Errorf("%s: output subject common name and template subject common name don't match", test.name)
  1434  		} else if len(out.Subject.Organization) != len(template.Subject.Organization) {
  1435  			t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name)
  1436  		} else if len(out.DNSNames) != len(template.DNSNames) {
  1437  			t.Errorf("%s: output DNS names and template DNS names don't match", test.name)
  1438  		} else if len(out.EmailAddresses) != len(template.EmailAddresses) {
  1439  			t.Errorf("%s: output email addresses and template email addresses don't match", test.name)
  1440  		} else if len(out.IPAddresses) != len(template.IPAddresses) {
  1441  			t.Errorf("%s: output IP addresses and template IP addresses names don't match", test.name)
  1442  		}
  1443  	}
  1444  }
  1445  
  1446  func marshalAndParseCSR(t *testing.T, template *CertificateRequest) *CertificateRequest {
  1447  	derBytes, err := CreateCertificateRequest(rand.Reader, template, testPrivateKey)
  1448  	if err != nil {
  1449  		t.Fatal(err)
  1450  	}
  1451  
  1452  	csr, err := ParseCertificateRequest(derBytes)
  1453  	if err != nil {
  1454  		t.Fatal(err)
  1455  	}
  1456  
  1457  	return csr
  1458  }
  1459  
  1460  func TestCertificateRequestOverrides(t *testing.T) {
  1461  	sanContents, err := marshalSANs([]string{"foo.example.com"}, nil, nil, nil)
  1462  	if err != nil {
  1463  		t.Fatal(err)
  1464  	}
  1465  
  1466  	template := CertificateRequest{
  1467  		Subject: pkix.Name{
  1468  			CommonName:   "test.example.com",
  1469  			Organization: []string{"Σ Acme Co"},
  1470  		},
  1471  		DNSNames: []string{"test.example.com"},
  1472  
  1473  		// An explicit extension should override the DNSNames from the
  1474  		// template.
  1475  		ExtraExtensions: []pkix.Extension{
  1476  			{
  1477  				Id:       oidExtensionSubjectAltName,
  1478  				Value:    sanContents,
  1479  				Critical: true,
  1480  			},
  1481  		},
  1482  	}
  1483  
  1484  	csr := marshalAndParseCSR(t, &template)
  1485  
  1486  	if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo.example.com" {
  1487  		t.Errorf("Extension did not override template. Got %v\n", csr.DNSNames)
  1488  	}
  1489  
  1490  	if len(csr.Extensions) != 1 || !csr.Extensions[0].Id.Equal(oidExtensionSubjectAltName) || !csr.Extensions[0].Critical {
  1491  		t.Errorf("SAN extension was not faithfully copied, got %#v", csr.Extensions)
  1492  	}
  1493  
  1494  	// If there is already an attribute with X.509 extensions then the
  1495  	// extra extensions should be added to it rather than creating a CSR
  1496  	// with two extension attributes.
  1497  
  1498  	//goland:noinspection GoDeprecation
  1499  	template.Attributes = []pkix.AttributeTypeAndValueSET{
  1500  		{
  1501  			Type: oidExtensionRequest,
  1502  			Value: [][]pkix.AttributeTypeAndValue{
  1503  				{
  1504  					{
  1505  						Type:  oidExtensionAuthorityInfoAccess,
  1506  						Value: []byte("foo"),
  1507  					},
  1508  				},
  1509  			},
  1510  		},
  1511  	}
  1512  
  1513  	csr = marshalAndParseCSR(t, &template)
  1514  	//goland:noinspection GoDeprecation
  1515  	if l := len(csr.Attributes); l != 1 {
  1516  		t.Errorf("incorrect number of attributes: %d\n", l)
  1517  	}
  1518  
  1519  	//goland:noinspection GoDeprecation
  1520  	if !csr.Attributes[0].Type.Equal(oidExtensionRequest) ||
  1521  		len(csr.Attributes[0].Value) != 1 ||
  1522  		len(csr.Attributes[0].Value[0]) != 2 {
  1523  		t.Errorf("bad attributes: %#v\n", csr.Attributes)
  1524  	}
  1525  
  1526  	sanContents2, err := marshalSANs([]string{"foo2.example.com"}, nil, nil, nil)
  1527  	if err != nil {
  1528  		t.Fatal(err)
  1529  	}
  1530  
  1531  	// Extensions in Attributes should override those in ExtraExtensions.
  1532  	//goland:noinspection GoDeprecation
  1533  	template.Attributes[0].Value[0] = append(template.Attributes[0].Value[0], pkix.AttributeTypeAndValue{
  1534  		Type:  oidExtensionSubjectAltName,
  1535  		Value: sanContents2,
  1536  	})
  1537  
  1538  	csr = marshalAndParseCSR(t, &template)
  1539  
  1540  	if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo2.example.com" {
  1541  		t.Errorf("Attributes did not override ExtraExtensions. Got %v\n", csr.DNSNames)
  1542  	}
  1543  }
  1544  
  1545  func TestParseCertificateRequest(t *testing.T) {
  1546  	for _, csrBase64 := range csrBase64Array {
  1547  		csrBytes := fromBase64(csrBase64)
  1548  		csr, err := ParseCertificateRequest(csrBytes)
  1549  		if err != nil {
  1550  			t.Fatalf("failed to parse CSR: %s", err)
  1551  		}
  1552  
  1553  		if len(csr.EmailAddresses) != 1 || csr.EmailAddresses[0] != "gopher@golang.org" {
  1554  			t.Errorf("incorrect email addresses found: %v", csr.EmailAddresses)
  1555  		}
  1556  
  1557  		if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "test.example.com" {
  1558  			t.Errorf("incorrect DNS names found: %v", csr.DNSNames)
  1559  		}
  1560  
  1561  		if len(csr.Subject.Country) != 1 || csr.Subject.Country[0] != "AU" {
  1562  			t.Errorf("incorrect Subject name: %v", csr.Subject)
  1563  		}
  1564  
  1565  		found := false
  1566  		for _, e := range csr.Extensions {
  1567  			if e.Id.Equal(oidExtensionBasicConstraints) {
  1568  				found = true
  1569  				break
  1570  			}
  1571  		}
  1572  		if !found {
  1573  			t.Errorf("basic constraints extension not found in CSR")
  1574  		}
  1575  	}
  1576  }
  1577  
  1578  func TestCriticalFlagInCSRRequestedExtensions(t *testing.T) {
  1579  	// This CSR contains an extension request where the extensions have a
  1580  	// critical flag in them. In the past we failed to handle this.
  1581  	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="
  1582  
  1583  	csrBytes := fromBase64(csrBase64)
  1584  	csr, err := ParseCertificateRequest(csrBytes)
  1585  	if err != nil {
  1586  		t.Fatalf("failed to parse CSR: %s", err)
  1587  	}
  1588  
  1589  	expected := []struct {
  1590  		Id    asn1.ObjectIdentifier
  1591  		Value []byte
  1592  	}{
  1593  		{oidExtensionBasicConstraints, fromBase64("MAYBAf8CAQA=")},
  1594  		{oidExtensionKeyUsage, fromBase64("AwIChA==")},
  1595  	}
  1596  
  1597  	if n := len(csr.Extensions); n != len(expected) {
  1598  		t.Fatalf("expected to find %d extensions but found %d", len(expected), n)
  1599  	}
  1600  
  1601  	for i, extension := range csr.Extensions {
  1602  		if !extension.Id.Equal(expected[i].Id) {
  1603  			t.Fatalf("extension #%d has unexpected type %v (expected %v)", i, extension.Id, expected[i].Id)
  1604  		}
  1605  
  1606  		if !bytes.Equal(extension.Value, expected[i].Value) {
  1607  			t.Fatalf("extension #%d has unexpected contents %x (expected %x)", i, extension.Value, expected[i].Value)
  1608  		}
  1609  	}
  1610  }
  1611  
  1612  // serialiseAndParse generates a self-signed certificate from template and
  1613  // returns a parsed version of it.
  1614  func serialiseAndParse(t *testing.T, template *Certificate) *Certificate {
  1615  	derBytes, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey)
  1616  	if err != nil {
  1617  		t.Fatalf("failed to create certificate: %s", err)
  1618  		return nil
  1619  	}
  1620  
  1621  	cert, err := ParseCertificate(derBytes)
  1622  	if err != nil {
  1623  		t.Fatalf("failed to parse certificate: %s", err)
  1624  		return nil
  1625  	}
  1626  
  1627  	return cert
  1628  }
  1629  
  1630  func TestMaxPathLenNotCA(t *testing.T) {
  1631  	template := &Certificate{
  1632  		SerialNumber: big.NewInt(1),
  1633  		Subject: pkix.Name{
  1634  			CommonName: "Σ Acme Co",
  1635  		},
  1636  		NotBefore: time.Unix(1000, 0),
  1637  		NotAfter:  time.Unix(100000, 0),
  1638  
  1639  		BasicConstraintsValid: true,
  1640  		IsCA:                  false,
  1641  	}
  1642  	if m := serialiseAndParse(t, template).MaxPathLen; m != -1 {
  1643  		t.Errorf("MaxPathLen should be -1 when IsCa is false, got %d", m)
  1644  	}
  1645  
  1646  	template.MaxPathLen = -1
  1647  	if m := serialiseAndParse(t, template).MaxPathLen; m != -1 {
  1648  		t.Errorf("MaxPathLen should be -1 when IsCa is false and MaxPathLen set to -1, got %d", m)
  1649  	}
  1650  
  1651  	template.MaxPathLen = 5
  1652  	if _, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey); err == nil {
  1653  		t.Error("specifying a MaxPathLen when IsCA is false should fail")
  1654  	}
  1655  
  1656  	template.MaxPathLen = 0
  1657  	template.MaxPathLenZero = true
  1658  	if _, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey); err == nil {
  1659  		t.Error("setting MaxPathLenZero when IsCA is false should fail")
  1660  	}
  1661  
  1662  	template.BasicConstraintsValid = false
  1663  	if m := serialiseAndParse(t, template).MaxPathLen; m != 0 {
  1664  		t.Errorf("Bad MaxPathLen should be ignored if BasicConstraintsValid is false, got %d", m)
  1665  	}
  1666  }
  1667  
  1668  func TestMaxPathLen(t *testing.T) {
  1669  	template := &Certificate{
  1670  		SerialNumber: big.NewInt(1),
  1671  		Subject: pkix.Name{
  1672  			CommonName: "Σ Acme Co",
  1673  		},
  1674  		NotBefore: time.Unix(1000, 0),
  1675  		NotAfter:  time.Unix(100000, 0),
  1676  
  1677  		BasicConstraintsValid: true,
  1678  		IsCA:                  true,
  1679  	}
  1680  
  1681  	cert1 := serialiseAndParse(t, template)
  1682  	if m := cert1.MaxPathLen; m != -1 {
  1683  		t.Errorf("Omitting MaxPathLen didn't turn into -1, got %d", m)
  1684  	}
  1685  	if cert1.MaxPathLenZero {
  1686  		t.Errorf("Omitting MaxPathLen resulted in MaxPathLenZero")
  1687  	}
  1688  
  1689  	template.MaxPathLen = 1
  1690  	cert2 := serialiseAndParse(t, template)
  1691  	if m := cert2.MaxPathLen; m != 1 {
  1692  		t.Errorf("Setting MaxPathLen didn't work. Got %d but set 1", m)
  1693  	}
  1694  	if cert2.MaxPathLenZero {
  1695  		t.Errorf("Setting MaxPathLen resulted in MaxPathLenZero")
  1696  	}
  1697  
  1698  	template.MaxPathLen = 0
  1699  	template.MaxPathLenZero = true
  1700  	cert3 := serialiseAndParse(t, template)
  1701  	if m := cert3.MaxPathLen; m != 0 {
  1702  		t.Errorf("Setting MaxPathLenZero didn't work, got %d", m)
  1703  	}
  1704  	if !cert3.MaxPathLenZero {
  1705  		t.Errorf("Setting MaxPathLen to zero didn't result in MaxPathLenZero")
  1706  	}
  1707  }
  1708  
  1709  func TestNoAuthorityKeyIdInSelfSignedCert(t *testing.T) {
  1710  	template := &Certificate{
  1711  		SerialNumber: big.NewInt(1),
  1712  		Subject: pkix.Name{
  1713  			CommonName: "Σ Acme Co",
  1714  		},
  1715  		NotBefore: time.Unix(1000, 0),
  1716  		NotAfter:  time.Unix(100000, 0),
  1717  
  1718  		BasicConstraintsValid: true,
  1719  		IsCA:                  true,
  1720  		SubjectKeyId:          []byte{1, 2, 3, 4},
  1721  	}
  1722  
  1723  	if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) != 0 {
  1724  		t.Fatalf("self-signed certificate contained default authority key id")
  1725  	}
  1726  
  1727  	template.AuthorityKeyId = []byte{1, 2, 3, 4}
  1728  	if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) == 0 {
  1729  		t.Fatalf("self-signed certificate erased explicit authority key id")
  1730  	}
  1731  }
  1732  
  1733  func TestNoSubjectKeyIdInCert(t *testing.T) {
  1734  	template := &Certificate{
  1735  		SerialNumber: big.NewInt(1),
  1736  		Subject: pkix.Name{
  1737  			CommonName: "Σ Acme Co",
  1738  		},
  1739  		NotBefore: time.Unix(1000, 0),
  1740  		NotAfter:  time.Unix(100000, 0),
  1741  
  1742  		BasicConstraintsValid: true,
  1743  		IsCA:                  true,
  1744  	}
  1745  	if cert := serialiseAndParse(t, template); len(cert.SubjectKeyId) == 0 {
  1746  		t.Fatalf("self-signed certificate did not generate subject key id using the public key")
  1747  	}
  1748  
  1749  	template.IsCA = false
  1750  	if cert := serialiseAndParse(t, template); len(cert.SubjectKeyId) != 0 {
  1751  		t.Fatalf("self-signed certificate generated subject key id when it isn't a CA")
  1752  	}
  1753  
  1754  	template.SubjectKeyId = []byte{1, 2, 3, 4}
  1755  	if cert := serialiseAndParse(t, template); len(cert.SubjectKeyId) == 0 {
  1756  		t.Fatalf("self-signed certificate erased explicit subject key id")
  1757  	}
  1758  }
  1759  
  1760  func TestASN1BitLength(t *testing.T) {
  1761  	tests := []struct {
  1762  		bytes  []byte
  1763  		bitLen int
  1764  	}{
  1765  		{nil, 0},
  1766  		{[]byte{0x00}, 0},
  1767  		{[]byte{0x00, 0x00}, 0},
  1768  		{[]byte{0xf0}, 4},
  1769  		{[]byte{0x88}, 5},
  1770  		{[]byte{0xff}, 8},
  1771  		{[]byte{0xff, 0x80}, 9},
  1772  		{[]byte{0xff, 0x81}, 16},
  1773  	}
  1774  
  1775  	for i, test := range tests {
  1776  		if got := asn1BitLength(test.bytes); got != test.bitLen {
  1777  			t.Errorf("#%d: calculated bit-length of %d for %x, wanted %d", i, got, test.bytes, test.bitLen)
  1778  		}
  1779  	}
  1780  }
  1781  
  1782  func TestVerifyEmptyCertificate(t *testing.T) {
  1783  	if _, err := new(Certificate).Verify(VerifyOptions{}); err != errNotParsed {
  1784  		t.Errorf("Verifying empty certificate resulted in unexpected error: %q (wanted %q)", err, errNotParsed)
  1785  	}
  1786  }
  1787  
  1788  func TestInsecureAlgorithmErrorString(t *testing.T) {
  1789  	tests := []struct {
  1790  		sa   SignatureAlgorithm
  1791  		want string
  1792  	}{
  1793  		{MD2WithRSA, "x509: cannot verify signature: insecure algorithm MD2-RSA"},
  1794  		{-1, "x509: cannot verify signature: insecure algorithm -1"},
  1795  		{0, "x509: cannot verify signature: insecure algorithm 0"},
  1796  		{9999, "x509: cannot verify signature: insecure algorithm 9999"},
  1797  	}
  1798  	for i, tt := range tests {
  1799  		if got := fmt.Sprint(InsecureAlgorithmError(tt.sa)); got != tt.want {
  1800  			t.Errorf("%d. mismatch.\n got: %s\nwant: %s\n", i, got, tt.want)
  1801  		}
  1802  	}
  1803  }
  1804  
  1805  // These CSR was generated with OpenSSL:
  1806  //
  1807  //	openssl req -out CSR.csr -new -sha256 -nodes -keyout privateKey.key -config openssl.cnf
  1808  //
  1809  // With openssl.cnf containing the following sections:
  1810  //
  1811  //	[ v3_req ]
  1812  //	basicConstraints = CA:FALSE
  1813  //	keyUsage = nonRepudiation, digitalSignature, keyEncipherment
  1814  //	subjectAltName = email:gopher@golang.org,DNS:test.example.com
  1815  //	[ req_attributes ]
  1816  //	challengePassword = ignored challenge
  1817  //	unstructuredName  = ignored unstructured name
  1818  var csrBase64Array = [...]string{
  1819  	// Just [ v3_req ]
  1820  	"MIIDHDCCAgQCAQAwfjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEUMBIGA1UEAwwLQ29tbW9uIE5hbWUxITAfBgkqhkiG9w0BCQEWEnRlc3RAZW1haWwuYWRkcmVzczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK1GY4YFx2ujlZEOJxQVYmsjUnLsd5nFVnNpLE4cV+77sgv9NPNlB8uhn3MXt5leD34rm/2BisCHOifPucYlSrszo2beuKhvwn4+2FxDmWtBEMu/QA16L5IvoOfYZm/gJTsPwKDqvaR0tTU67a9OtxwNTBMI56YKtmwd/o8d3hYv9cg+9ZGAZ/gKONcg/OWYx/XRh6bd0g8DMbCikpWgXKDsvvK1Nk+VtkDO1JxuBaj4Lz/p/MifTfnHoqHxWOWl4EaTs4Ychxsv34/rSj1KD1tJqorIv5Xv2aqv4sjxfbrYzX4kvS5SC1goIovLnhj5UjmQ3Qy8u65eow/LLWw+YFcCAwEAAaBZMFcGCSqGSIb3DQEJDjFKMEgwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwLgYDVR0RBCcwJYERZ29wa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J2t5AZEh80lPAgMB
  1834  AAEwDQYJKoZIhvcNAQEEBQADgYEAjGzp3K3ey/YfKHohf33yHHWd695HQxDAP+wY
  1835  cs9/TAyLR+gJzJP7d18EcDDLJWVi7bhfa4EAD86di05azOh9kWSn4b3o9QYRGCSw
  1836  GNnI3Zk0cwNKA49hZntKKiy22DhRk7JAHF01d6Bu3KkHkmENrtJ+zj/+159WAnUa
  1837  qViorq4=
  1838  -----END CERTIFICATE-----
  1839  `
  1840  
  1841  func TestMD5(t *testing.T) {
  1842  	pemBlock, _ := pem.Decode([]byte(md5cert))
  1843  	cert, err := ParseCertificate(pemBlock.Bytes)
  1844  	if err != nil {
  1845  		t.Fatalf("failed to parse certificate: %s", err)
  1846  	}
  1847  	if sa := cert.SignatureAlgorithm; sa != MD5WithRSA {
  1848  		t.Errorf("signature algorithm is %v, want %v", sa, MD5WithRSA)
  1849  	}
  1850  	if err = cert.CheckSignatureFrom(cert); err == nil {
  1851  		t.Fatalf("certificate verification succeeded incorrectly")
  1852  	}
  1853  	if _, ok := err.(InsecureAlgorithmError); !ok {
  1854  		t.Fatalf("certificate verification returned %v (%T), wanted InsecureAlgorithmError", err, err)
  1855  	}
  1856  }
  1857  
  1858  // certMissingRSANULL contains an RSA public key where the AlgorithmIdentifier
  1859  // parameters are omitted rather than being an ASN.1 NULL.
  1860  const certMissingRSANULL = `
  1861  -----BEGIN CERTIFICATE-----
  1862  MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD
  1863  bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4
  1864  MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc
  1865  MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG
  1866  hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE
  1867  ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e
  1868  E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw
  1869  DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A
  1870  p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4
  1871  hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE
  1872  GFGNEH5PlGffo05wc46QkYU=
  1873  -----END CERTIFICATE-----`
  1874  
  1875  func TestRSAMissingNULLParameters(t *testing.T) {
  1876  	block, _ := pem.Decode([]byte(certMissingRSANULL))
  1877  	if _, err := ParseCertificate(block.Bytes); err == nil {
  1878  		t.Error("unexpected success when parsing certificate with missing RSA NULL parameter")
  1879  	} else if !strings.Contains(err.Error(), "missing NULL") {
  1880  		t.Errorf("unrecognised error when parsing certificate with missing RSA NULL parameter: %s", err)
  1881  	}
  1882  }
  1883  
  1884  const certISOOID = `
  1885  -----BEGIN CERTIFICATE-----
  1886  MIIB5TCCAVKgAwIBAgIQtwyL3RPWV7dJQp34HwZG9DAJBgUrDgMCHQUAMBExDzAN
  1887  BgNVBAMTBm15dGVzdDAeFw0xNjA4MDkyMjExMDVaFw0zOTEyMzEyMzU5NTlaMBEx
  1888  DzANBgNVBAMTBm15dGVzdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArzIH
  1889  GsyDB3ohIGkkvijF2PTRUX1bvOtY1eUUpjwHyu0twpAKSuaQv2Ha+/63+aHe8O86
  1890  BT+98wjXFX6RFSagtAujo80rIF2dSm33BGt18pDN8v6zp93dnAm0jRaSQrHJ75xw
  1891  5O+S1oEYR1LtUoFJy6qB104j6aINBAgOiLIKiMkCAwEAAaNGMEQwQgYDVR0BBDsw
  1892  OYAQVuYVQ/WDjdGSkZRlTtJDNKETMBExDzANBgNVBAMTBm15dGVzdIIQtwyL3RPW
  1893  V7dJQp34HwZG9DAJBgUrDgMCHQUAA4GBABngrSkH7vG5lY4sa4AZF59lAAXqBVJE
  1894  J4TBiKC62hCdZv18rBleP6ETfhbPg7pTs8p4ebQbpmtNxRS9Lw3MzQ8Ya5Ybwzj2
  1895  NwBSyCtCQl7mrEg4nJqJl4A2EUhnET/oVxU0oTV/SZ3ziGXcY1oG1s6vidV7TZTu
  1896  MCRtdSdaM7g3
  1897  -----END CERTIFICATE-----`
  1898  
  1899  func TestISOOIDInCertificate(t *testing.T) {
  1900  	block, _ := pem.Decode([]byte(certISOOID))
  1901  	if cert, err := ParseCertificate(block.Bytes); err != nil {
  1902  		t.Errorf("certificate with ISO OID failed to parse: %s", err)
  1903  	} else if cert.SignatureAlgorithm == UnknownSignatureAlgorithm {
  1904  		t.Errorf("ISO OID not recognised in certificate")
  1905  	}
  1906  }
  1907  
  1908  // certMultipleRDN contains a RelativeDistinguishedName with two elements (the
  1909  // common name and serial number). This particular certificate was the first
  1910  // such certificate in the “Pilot” Certificate Transparency log.
  1911  const certMultipleRDN = `
  1912  -----BEGIN CERTIFICATE-----
  1913  MIIFRzCCBC+gAwIBAgIEOl59NTANBgkqhkiG9w0BAQUFADA9MQswCQYDVQQGEwJz
  1914  aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMREwDwYDVQQLEwhzaWdvdi1j
  1915  YTAeFw0xMjExMTYxMDUyNTdaFw0xNzExMTYxMjQ5MDVaMIGLMQswCQYDVQQGEwJz
  1916  aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMRkwFwYDVQQLExB3ZWItY2Vy
  1917  dGlmaWNhdGVzMRAwDgYDVQQLEwdTZXJ2ZXJzMTIwFAYDVQQFEw0xMjM2NDg0MDEw
  1918  MDEwMBoGA1UEA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R0jBBgwFoAUHvjUU2uzgwbpBAZXAvmlv8ZY
  1934  PHIwHQYDVR0OBBYEFGI1Duuu+wTGDZka/xHNbwcbM69ZMAkGA1UdEwQCMAAwGQYJ
  1935  KoZIhvZ9B0EABAwwChsEVjcuMQMCA6gwDQYJKoZIhvcNAQEFBQADggEBAHny0K1y
  1936  BQznrzDu3DDpBcGYguKU0dvU9rqsV1ua4nxkriSMWjgsX6XJFDdDW60I3P4VWab5
  1937  ag5fZzbGqi8kva/CzGgZh+CES0aWCPy+4Gb8lwOTt+854/laaJvd6kgKTER7z7U9
  1938  9C86Ch2y4sXNwwwPJ1A9dmrZJZOcJjS/WYZgwaafY2Hdxub5jqPE5nehwYUPVu9R
  1939  uH6/skk4OEKcfOtN0hCnISOVuKYyS4ANARWRG5VGHIH06z3lGUVARFRJ61gtAprd
  1940  La+fgSS+LVZ+kU2TkeoWAKvGq8MAgDq4D4Xqwekg7WKFeuyusi/NI5rm40XgjBMF
  1941  DF72IUofoVt7wo0=
  1942  -----END CERTIFICATE-----`
  1943  
  1944  func TestMultipleRDN(t *testing.T) {
  1945  	block, _ := pem.Decode([]byte(certMultipleRDN))
  1946  	cert, err := ParseCertificate(block.Bytes)
  1947  	if err != nil {
  1948  		t.Fatalf("certificate with two elements in an RDN failed to parse: %v", err)
  1949  	}
  1950  
  1951  	if want := "eportal.mss.edus.si"; cert.Subject.CommonName != want {
  1952  		t.Errorf("got common name of %q, but want %q", cert.Subject.CommonName, want)
  1953  	}
  1954  
  1955  	if want := "1236484010010"; cert.Subject.SerialNumber != want {
  1956  		t.Errorf("got serial number of %q, but want %q", cert.Subject.SerialNumber, want)
  1957  	}
  1958  }
  1959  
  1960  func TestSystemCertPool(t *testing.T) {
  1961  	if runtime.GOOS == "windows" {
  1962  		t.Skip("not implemented on Windows; Issue 16736, 18609")
  1963  	}
  1964  	a, err := SystemCertPool()
  1965  	if err != nil {
  1966  		t.Fatal(err)
  1967  	}
  1968  	b, err := SystemCertPool()
  1969  	if err != nil {
  1970  		t.Fatal(err)
  1971  	}
  1972  	if !certPoolEqual(a, b) {
  1973  		t.Fatal("two calls to SystemCertPool had different results")
  1974  	}
  1975  	if ok := b.AppendCertsFromPEM([]byte(`
  1976  -----BEGIN CERTIFICATE-----
  1977  MIIDBjCCAe6gAwIBAgIRANXM5I3gjuqDfTp/PYrs+u8wDQYJKoZIhvcNAQELBQAw
  1978  EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xODAzMjcxOTU2MjFaFw0xOTAzMjcxOTU2
  1979  MjFaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
  1980  ggEKAoIBAQDK+9m3rjsO2Djes6bIYQZ3eV29JF09ZrjOrEHLtaKrD6/acsoSoTsf
  1981  cQr+rzzztdB5ijWXCS64zo/0OiqBeZUNZ67jVdToa9qW5UYe2H0Y+ZNdfA5GYMFD
  1982  yk/l3/uBu3suTZPfXiW2TjEi27Q8ruNUIZ54DpTcs6y2rBRFzadPWwn/VQMlvRXM
  1983  jrzl8Y08dgnYmaAHprxVzwMXcQ/Brol+v9GvjaH1DooHqkn8O178wsPQNhdtvN01
  1984  IXL46cYdcUwWrE/GX5u+9DaSi+0KWxAPQ+NVD5qUI0CKl4714yGGh7feXMjJdHgl
  1985  VG4QJZlJvC4FsURgCHJT6uHGIelnSwhbAgMBAAGjVzBVMA4GA1UdDwEB/wQEAwIF
  1986  oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMCAGA1UdEQQZMBeC
  1987  FVRlc3RTeXN0ZW1DZXJ0UG9vbC5nbzANBgkqhkiG9w0BAQsFAAOCAQEAwuSRx/VR
  1988  BKh2ICxZjL6jBwk/7UlU1XKbhQD96RqkidDNGEc6eLZ90Z5XXTurEsXqdm5jQYPs
  1989  1cdcSW+fOSMl7MfW9e5tM66FaIPZl9rKZ1r7GkOfgn93xdLAWe8XHd19xRfDreub
  1990  YC8DVqgLASOEYFupVSl76ktPfxkU5KCvmUf3P2PrRybk1qLGFytGxfyice2gHSNI
  1991  gify3K/+H/7wCkyFW4xYvzl7WW4mXxoqPRPjQt1J423DhnnQ4G1P8V/vhUpXNXOq
  1992  N9IEPnWuihC09cyx/WMQIUlWnaQLHdfpPS04Iez3yy2PdfXJzwfPrja7rNE+skK6
  1993  pa/O1nF0AfWOpw==
  1994  -----END CERTIFICATE-----
  1995  	`)); !ok {
  1996  		t.Fatal("AppendCertsFromPEM failed")
  1997  	}
  1998  	if reflect.DeepEqual(a, b) {
  1999  		t.Fatal("changing one pool modified the other")
  2000  	}
  2001  }
  2002  
  2003  const emptyNameConstraintsPEM = `
  2004  -----BEGIN CERTIFICATE-----
  2005  MIIC1jCCAb6gAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w
  2006  dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw
  2007  NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB
  2008  IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD
  2009  F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx
  2010  f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq
  2011  Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0
  2012  LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD
  2013  blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID
  2014  AQABoxEwDzANBgNVHR4EBjAEoAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMH
  2015  QhP8uNCtgSHyim/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb
  2016  6L+iJa4ElREJOi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6H
  2017  v5SsvpYW+1XleYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6M
  2018  LYPmRhTioROA/drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOga
  2019  nCOSyFYfGhqOANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8
  2020  o+WoY6IsCKXV/g==
  2021  -----END CERTIFICATE-----`
  2022  
  2023  func TestEmptyNameConstraints(t *testing.T) {
  2024  	block, _ := pem.Decode([]byte(emptyNameConstraintsPEM))
  2025  	_, err := ParseCertificate(block.Bytes)
  2026  	if err == nil {
  2027  		t.Fatal("unexpected success")
  2028  	}
  2029  
  2030  	const expected = "empty name constraints"
  2031  	if str := err.Error(); !strings.Contains(str, expected) {
  2032  		t.Errorf("expected %q in error but got %q", expected, str)
  2033  	}
  2034  }
  2035  
  2036  func TestPKIXNameString(t *testing.T) {
  2037  	der, err := base64.StdEncoding.DecodeString(certBytes)
  2038  	if err != nil {
  2039  		t.Fatal(err)
  2040  	}
  2041  	certs, err := ParseCertificates(der)
  2042  	if err != nil {
  2043  		t.Fatal(err)
  2044  	}
  2045  
  2046  	// Check that parsed non-standard attributes are printed.
  2047  	//goland:noinspection GoDeprecation
  2048  	rdns := pkix.Name{
  2049  		Locality: []string{"Gophertown"},
  2050  		ExtraNames: []pkix.AttributeTypeAndValue{
  2051  			{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  2052  	}.ToRDNSequence()
  2053  	nn := pkix.Name{}
  2054  	nn.FillFromRDNSequence(&rdns)
  2055  
  2056  	// Check that zero-length non-nil ExtraNames hide Names.
  2057  	extra := []pkix.AttributeTypeAndValue{
  2058  		{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "backing array"}}
  2059  	extraNotNil := pkix.Name{
  2060  		Locality:   []string{"Gophertown"},
  2061  		ExtraNames: extra[:0],
  2062  		Names: []pkix.AttributeTypeAndValue{
  2063  			{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  2064  	}
  2065  
  2066  	tests := []struct {
  2067  		dn   pkix.Name
  2068  		want string
  2069  	}{
  2070  		{nn, "L=Gophertown,1.2.3.4.5=#130a676f6c616e672e6f7267"},
  2071  		{extraNotNil, "L=Gophertown"},
  2072  		{pkix.Name{
  2073  			CommonName:         "Steve Kille",
  2074  			Organization:       []string{"Isode Limited"},
  2075  			OrganizationalUnit: []string{"RFCs"},
  2076  			Locality:           []string{"Richmond"},
  2077  			Province:           []string{"Surrey"},
  2078  			StreetAddress:      []string{"The Square"},
  2079  			PostalCode:         []string{"TW9 1DT"},
  2080  			SerialNumber:       "RFC 2253",
  2081  			Country:            []string{"GB"},
  2082  		}, "SERIALNUMBER=RFC 2253,CN=Steve Kille,OU=RFCs,O=Isode Limited,POSTALCODE=TW9 1DT,STREET=The Square,L=Richmond,ST=Surrey,C=GB"},
  2083  		{certs[0].Subject,
  2084  			"CN=mail.google.com,O=Google LLC,L=Mountain View,ST=California,C=US"},
  2085  		{pkix.Name{
  2086  			Organization: []string{"#Google, Inc. \n-> 'Alphabet\" "},
  2087  			Country:      []string{"US"},
  2088  		}, "O=\\#Google\\, Inc. \n-\\> 'Alphabet\\\"\\ ,C=US"},
  2089  		{pkix.Name{
  2090  			CommonName:   "foo.com",
  2091  			Organization: []string{"Gopher Industries"},
  2092  			ExtraNames: []pkix.AttributeTypeAndValue{
  2093  				{Type: asn1.ObjectIdentifier([]int{2, 5, 4, 3}), Value: "bar.com"}},
  2094  		}, "CN=bar.com,O=Gopher Industries"},
  2095  		{pkix.Name{
  2096  			Locality: []string{"Gophertown"},
  2097  			ExtraNames: []pkix.AttributeTypeAndValue{
  2098  				{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  2099  		}, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"},
  2100  		// If there are no ExtraNames, the Names are printed instead.
  2101  		{pkix.Name{
  2102  			Locality: []string{"Gophertown"},
  2103  			Names: []pkix.AttributeTypeAndValue{
  2104  				{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  2105  		}, "L=Gophertown,1.2.3.4.5=#130a676f6c616e672e6f7267"},
  2106  		// If there are both, print only the ExtraNames.
  2107  		{pkix.Name{
  2108  			Locality: []string{"Gophertown"},
  2109  			ExtraNames: []pkix.AttributeTypeAndValue{
  2110  				{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  2111  			Names: []pkix.AttributeTypeAndValue{
  2112  				{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 6}), Value: "example.com"}},
  2113  		}, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"},
  2114  	}
  2115  
  2116  	for i, test := range tests {
  2117  		if got := test.dn.String(); got != test.want {
  2118  			t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
  2119  		}
  2120  	}
  2121  
  2122  	if extra[0].Value != "backing array" {
  2123  		t.Errorf("the backing array of an empty ExtraNames got modified by String")
  2124  	}
  2125  }
  2126  
  2127  func TestRDNSequenceString(t *testing.T) {
  2128  	// Test some extra cases that get lost in pkix.Name conversions such as
  2129  	// multi-valued attributes.
  2130  
  2131  	var (
  2132  		oidCountry            = []int{2, 5, 4, 6}
  2133  		oidOrganization       = []int{2, 5, 4, 10}
  2134  		oidOrganizationalUnit = []int{2, 5, 4, 11}
  2135  		oidCommonName         = []int{2, 5, 4, 3}
  2136  	)
  2137  
  2138  	tests := []struct {
  2139  		seq  pkix.RDNSequence
  2140  		want string
  2141  	}{
  2142  		{
  2143  			seq: pkix.RDNSequence{
  2144  				pkix.RelativeDistinguishedNameSET{
  2145  					pkix.AttributeTypeAndValue{Type: oidCountry, Value: "US"},
  2146  				},
  2147  				pkix.RelativeDistinguishedNameSET{
  2148  					pkix.AttributeTypeAndValue{Type: oidOrganization, Value: "Widget Inc."},
  2149  				},
  2150  				pkix.RelativeDistinguishedNameSET{
  2151  					pkix.AttributeTypeAndValue{Type: oidOrganizationalUnit, Value: "Sales"},
  2152  					pkix.AttributeTypeAndValue{Type: oidCommonName, Value: "J. Smith"},
  2153  				},
  2154  			},
  2155  			want: "OU=Sales+CN=J. Smith,O=Widget Inc.,C=US",
  2156  		},
  2157  	}
  2158  
  2159  	for i, test := range tests {
  2160  		if got := test.seq.String(); got != test.want {
  2161  			t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
  2162  		}
  2163  	}
  2164  }
  2165  
  2166  const criticalNameConstraintWithUnknownTypePEM = `
  2167  -----BEGIN CERTIFICATE-----
  2168  MIIC/TCCAeWgAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w
  2169  dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw
  2170  NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB
  2171  IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD
  2172  F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx
  2173  f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq
  2174  Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0
  2175  LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD
  2176  blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID
  2177  AQABozgwNjA0BgNVHR4BAf8EKjAooCQwIokgIACrzQAAAAAAAAAAAAAAAP////8A
  2178  AAAAAAAAAAAAAAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMHQhP8uNCtgSHy
  2179  im/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb6L+iJa4ElREJ
  2180  Oi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6Hv5SsvpYW+1Xl
  2181  eYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6MLYPmRhTioROA
  2182  /drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOganCOSyFYfGhqO
  2183  ANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8o+WoY6IsCKXV
  2184  /g==
  2185  -----END CERTIFICATE-----`
  2186  
  2187  func TestCriticalNameConstraintWithUnknownType(t *testing.T) {
  2188  	block, _ := pem.Decode([]byte(criticalNameConstraintWithUnknownTypePEM))
  2189  	cert, err := ParseCertificate(block.Bytes)
  2190  	if err != nil {
  2191  		t.Fatalf("unexpected parsing failure: %s", err)
  2192  	}
  2193  
  2194  	if l := len(cert.UnhandledCriticalExtensions); l != 1 {
  2195  		t.Fatalf("expected one unhandled critical extension, but found %d", l)
  2196  	}
  2197  }
  2198  
  2199  const badIPMaskPEM = `
  2200  -----BEGIN CERTIFICATE-----
  2201  MIICzzCCAbegAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwHTEbMBkGA1UEAxMSQmFk
  2202  IElQIG1hc2sgaXNzdWVyMB4XDTEzMDIwMTAwMDAwMFoXDTIwMDUzMDEwNDgzOFow
  2203  FjEUMBIGA1UEAxMLQmFkIElQIG1hc2swggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
  2204  ggEKAoIBAQDCuISVQi3csKqYk5uz7IOhY8MXkiqBaTqagihtiM997G1mJhTojcR+
  2205  8DCg3E8OQ3ZajByhxRkwlsR4Srl5sGSwWfF/XaAHGUhWIhjBkDO7toW+EMzI8pAj
  2206  cLwIbRlIL0AFnUTe6Z0DcIS5406Y/9MKE2oKXbf4EbVBv88mSkA74Z+lZJWFNxXn
  2207  cx/9wq8UdyMY2vHN1Kir1/JbtrqB9wYRBjQtWSbAVZR8nTBPyRp4uvQTS2jOQh+j
  2208  TUo1Y3O/o1xg/zRA4FEOUCla704OYRUkc8NuXHiPNNDcktr7gO8E06NVQ6n6aBGa
  2209  OJbSst2vHA7Eiog7A2PB4wKn+GDFf+FNAgMBAAGjIDAeMBwGA1UdHgEB/wQSMBCg
  2210  DDAKhwgBAgME//8BAKEAMA0GCSqGSIb3DQEBCwUAA4IBAQBYb7/NQwdCE/y40K2B
  2211  IfKKb++HvCaKfAC9aAwrGWQsEWezqdl5Cqw5XWUAFjtTRm6iprVnmdvov6IlrgSV
  2212  EQk6L96stz24vAF0MIBHSFRMoPtrqLiihLf0NOV7ztxSePQxbUJRroe/lKy+lhb7
  2213  VeV5gmT9rFA45NzLgSznd2+dmyNcfQQD9AeeftRX4maUTeu1XFxinowtg+ZGFOKh
  2214  E4D92uCGJxGSK72HF0/LGRhLXozmDdmPfSN2b6T/oLo942031iY46BqcI5LIVh8a
  2215  Go4A1jOma5X6gh50Cw+kht8jM3yeNhSzXOKj7Uigjijx10z2wJu09Tyj5ahjoiwI
  2216  pdX+
  2217  -----END CERTIFICATE-----`
  2218  
  2219  func TestBadIPMask(t *testing.T) {
  2220  	block, _ := pem.Decode([]byte(badIPMaskPEM))
  2221  	_, err := ParseCertificate(block.Bytes)
  2222  	if err == nil {
  2223  		t.Fatalf("unexpected success")
  2224  	}
  2225  
  2226  	const expected = "contained invalid mask"
  2227  	if !strings.Contains(err.Error(), expected) {
  2228  		t.Fatalf("expected %q in error but got: %s", expected, err)
  2229  	}
  2230  }
  2231  
  2232  const additionalGeneralSubtreePEM = `
  2233  -----BEGIN CERTIFICATE-----
  2234  MIIG4TCCBMmgAwIBAgIRALss+4rLw2Ia7tFFhxE8g5cwDQYJKoZIhvcNAQELBQAw
  2235  bjELMAkGA1UEBhMCTkwxIDAeBgNVBAoMF01pbmlzdGVyaWUgdmFuIERlZmVuc2ll
  2236  MT0wOwYDVQQDDDRNaW5pc3RlcmllIHZhbiBEZWZlbnNpZSBDZXJ0aWZpY2F0aWUg
  2237  QXV0b3JpdGVpdCAtIEcyMB4XDTEzMDMwNjEyMDM0OVoXDTEzMTEzMDEyMDM1MFow
  2238  bDELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUNlcnRpUGF0aCBMTEMxIjAgBgNVBAsT
  2239  GUNlcnRpZmljYXRpb24gQXV0aG9yaXRpZXMxITAfBgNVBAMTGENlcnRpUGF0aCBC
  2240  cmlkZ2UgQ0EgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANLW
  2241  4kXiRqvwBhJfN9uz12FA+P2D34MPxOt7TGXljm2plJ2CLzvaH8/ymsMdSWdJBS1M
  2242  8FmwvNL1w3A6ZuzksJjPikAu8kY3dcp3mrkk9eCPORDAwGtfsXwZysLiuEaDWpbD
  2243  dHOaHnI6qWU0N6OI+hNX58EjDpIGC1WQdho1tHOTPc5Hf5/hOpM/29v/wr7kySjs
  2244  Z+7nsvkm5rNhuJNzPsLsgzVaJ5/BVyOplZy24FKM8Y43MjR4osZm+a2e0zniqw6/
  2245  rvcjcGYabYaznZfQG1GXoyf2Vea+CCgpgUhlVafgkwEs8izl8rIpvBzXiFAgFQuG
  2246  Ituoy92PJbDs430fA/cCAwEAAaOCAnowggJ2MEUGCCsGAQUFBwEBBDkwNzA1Bggr
  2247  BgEFBQcwAoYpaHR0cDovL2NlcnRzLmNhLm1pbmRlZi5ubC9taW5kZWYtY2EtMi5w
  2248  N2MwHwYDVR0jBBgwFoAUzln9WSPz2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xrb2cwcZA6
  2264  8vdS4hzNd+ttS905ay31Ks4/1Wrm1bH5RhEfRSH0VSXnc0b+z+RyBbmiwtVZqzxE
  2265  u3UQg/rAmtLDclLFEzjp8YDTIRYSLwstDbEXO/0ArdGrQm79HQ8i/3ZbP2357myW
  2266  i15qd6gMJIgGHS4b8Hc7R1K8LQ9Gm1aLKBEWVNGZlPK/cpXThpVmoEyslN2DHCrc
  2267  fbMbjNZpXlTMa+/b9z7Fa4X8dY8u/ELzZuJXJv5Rmqtg29eopFFYDCl0Nkh1XAjo
  2268  QejEoHHUvYV8TThHZr6Z6Ib8CECgTehU4QvepkgDXNoNrKRZBG0JhLjkwxh2whZq
  2269  nvWBfALC2VuNOM6C0rDY+HmhMlVt0XeqnybD9MuQALMit7Z00Cw2CIjNsBI9xBqD
  2270  xKK9CjUb7gzRUWSpB9jGHsvpEMHOzIFhufvH2Bz1XJw+Cl7khw==
  2271  -----END CERTIFICATE-----`
  2272  
  2273  func TestAdditionFieldsInGeneralSubtree(t *testing.T) {
  2274  	// Very rarely, certificates can include additional fields in the
  2275  	// GeneralSubtree structure. This tests that such certificates can be
  2276  	// parsed.
  2277  	block, _ := pem.Decode([]byte(additionalGeneralSubtreePEM))
  2278  	if _, err := ParseCertificate(block.Bytes); err != nil {
  2279  		t.Fatalf("failed to parse certificate: %s", err)
  2280  	}
  2281  }
  2282  
  2283  func TestEmptySubject(t *testing.T) {
  2284  	template := Certificate{
  2285  		SerialNumber: big.NewInt(1),
  2286  		DNSNames:     []string{"example.com"},
  2287  	}
  2288  
  2289  	derBytes, err := CreateCertificate(rand.Reader, &template, &template, &testPrivateKey.PublicKey, testPrivateKey)
  2290  	if err != nil {
  2291  		t.Fatalf("failed to create certificate: %s", err)
  2292  	}
  2293  
  2294  	cert, err := ParseCertificate(derBytes)
  2295  	if err != nil {
  2296  		t.Fatalf("failed to parse certificate: %s", err)
  2297  	}
  2298  
  2299  	for _, ext := range cert.Extensions {
  2300  		if ext.Id.Equal(oidExtensionSubjectAltName) {
  2301  			if !ext.Critical {
  2302  				t.Fatal("SAN extension is not critical")
  2303  			}
  2304  			return
  2305  		}
  2306  	}
  2307  
  2308  	t.Fatal("SAN extension is missing")
  2309  }
  2310  
  2311  // multipleURLsInCRLDPPEM contains two URLs in a single CRL DistributionPoint
  2312  // structure. It is taken from https://crt.sh/?id=12721534.
  2313  const multipleURLsInCRLDPPEM = `
  2314  -----BEGIN CERTIFICATE-----
  2315  MIIF4TCCBMmgAwIBAgIQc+6uFePfrahUGpXs8lhiTzANBgkqhkiG9w0BAQsFADCB
  2316  8zELMAkGA1UEBhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2Vy
  2317  dGlmaWNhY2lvIChOSUYgUS0wODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1
  2318  YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYDVQQLEyxWZWdldSBodHRwczovL3d3
  2319  dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UECxMsSmVyYXJxdWlh
  2320  IEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMTBkVD
  2321  LUFDQzAeFw0xNDA5MTgwODIxMDBaFw0zMDA5MTgwODIxMDBaMIGGMQswCQYDVQQG
  2322  EwJFUzEzMDEGA1UECgwqQ09OU09SQ0kgQURNSU5JU1RSQUNJTyBPQkVSVEEgREUg
  2323  Q0FUQUxVTllBMSowKAYDVQQLDCFTZXJ2ZWlzIFDDumJsaWNzIGRlIENlcnRpZmlj
  2324  YWNpw7MxFjAUBgNVBAMMDUVDLUNpdXRhZGFuaWEwggEiMA0GCSqGSIb3DQEBAQUA
  2325  A4IBDwAwggEKAoIBAQDFkHPRZPZlXTWZ5psJhbS/Gx+bxcTpGrlVQHHtIkgGz77y
  2326  TA7UZUFb2EQMncfbOhR0OkvQQn1aMvhObFJSR6nI+caf2D+h/m/InMl1MyH3S0Ak
  2327  YGZZsthnyC6KxqK2A/NApncrOreh70ULkQs45aOKsi1kR1W0zE+iFN+/P19P7AkL
  2328  Rl3bXBCVd8w+DLhcwRrkf1FCDw6cEqaFm3cGgf5cbBDMaVYAweWTxwBZAq2RbQAW
  2329  jE7mledcYghcZa4U6bUmCBPuLOnO8KMFAvH+aRzaf3ws5/ZoOVmryyLLJVZ54peZ
  2330  OwnP9EL4OuWzmXCjBifXR2IAblxs5JYj57tls45nAgMBAAGjggHaMIIB1jASBgNV
  2331  HRMBAf8ECDAGAQH/AgEAMA4GA1UdDwEB/wQEAwIBBjAdBgNVHQ4EFgQUC2hZPofI
  2332  oxUa4ECCIl+fHbLFNxUwHwYDVR0jBBgwFoAUoMOLRKo3pUW/l4Ba0fF4opvpXY0w
  2333  gdYGA1UdIASBzjCByzCByAYEVR0gADCBvzAxBggrBgEFBQcCARYlaHR0cHM6Ly93
  2334  d3cuYW9jLmNhdC9DQVRDZXJ0L1JlZ3VsYWNpbzCBiQYIKwYBBQUHAgIwfQx7QXF1
  2335  ZXN0IGNlcnRpZmljYXQgw6lzIGVtw6hzIMO6bmljYSBpIGV4Y2x1c2l2YW1lbnQg
  2336  YSBFbnRpdGF0cyBkZSBDZXJ0aWZpY2FjacOzLiBWZWdldSBodHRwczovL3d3dy5h
  2337  b2MuY2F0L0NBVENlcnQvUmVndWxhY2lvMDMGCCsGAQUFBwEBBCcwJTAjBggrBgEF
  2338  BQcwAYYXaHR0cDovL29jc3AuY2F0Y2VydC5jYXQwYgYDVR0fBFswWTBXoFWgU4Yn
  2339  aHR0cDovL2Vwc2NkLmNhdGNlcnQubmV0L2NybC9lYy1hY2MuY3JshihodHRwOi8v
  2340  ZXBzY2QyLmNhdGNlcnQubmV0L2NybC9lYy1hY2MuY3JsMA0GCSqGSIb3DQEBCwUA
  2341  A4IBAQChqFTjlAH5PyIhLjLgEs68CyNNC1+vDuZXRhy22TI83JcvGmQrZosPvVIL
  2342  PsUXx+C06Pfqmh48Q9S89X9K8w1SdJxP/rZeGEoRiKpwvQzM4ArD9QxyC8jirxex
  2343  3Umg9Ai/sXQ+1lBf6xw4HfUUr1WIp7pNHj0ZWLo106urqktcdeAFWme+/klis5fu
  2344  labCSVPuT/QpwakPrtqOhRms8vgpKiXa/eLtL9ZiA28X/Mker0zlAeTA7Z7uAnp6
  2345  oPJTlZu1Gg1ZDJueTWWsLlO+P+Wzm3MRRIbcgdRzm4mdO7ubu26SzX/aQXDhuih+
  2346  eVxXDTCfs7GUlxnjOp5j559X/N0A
  2347  -----END CERTIFICATE-----
  2348  `
  2349  
  2350  func TestMultipleURLsInCRLDP(t *testing.T) {
  2351  	block, _ := pem.Decode([]byte(multipleURLsInCRLDPPEM))
  2352  	cert, err := ParseCertificate(block.Bytes)
  2353  	if err != nil {
  2354  		t.Fatalf("failed to parse certificate: %s", err)
  2355  	}
  2356  
  2357  	//goland:noinspection GoDeprecation
  2358  	want := []string{
  2359  		"http://epscd.catcert.net/crl/ec-acc.crl",
  2360  		"http://epscd2.catcert.net/crl/ec-acc.crl",
  2361  	}
  2362  	if got := cert.CRLDistributionPoints; !reflect.DeepEqual(got, want) {
  2363  		t.Errorf("CRL distribution points = %#v, want #%v", got, want)
  2364  	}
  2365  }
  2366  
  2367  const hexPKCS1TestPKCS8Key = "30820278020100300d06092a864886f70d0101010500048202623082025e02010002818100cfb1b5bf9685ffa97b4f99df4ff122b70e59ac9b992f3bc2b3dde17d53c1a34928719b02e8fd17839499bfbd515bd6ef99c7a1c47a239718fe36bfd824c0d96060084b5f67f0273443007a24dfaf5634f7772c9346e10eb294c2306671a5a5e719ae24b4de467291bc571014b0e02dec04534d66a9bb171d644b66b091780e8d020301000102818100b595778383c4afdbab95d2bfed12b3f93bb0a73a7ad952f44d7185fd9ec6c34de8f03a48770f2009c8580bcd275e9632714e9a5e3f32f29dc55474b2329ff0ebc08b3ffcb35bc96e6516b483df80a4a59cceb71918cbabf91564e64a39d7e35dce21cb3031824fdbc845dba6458852ec16af5dddf51a8397a8797ae0337b1439024100ea0eb1b914158c70db39031dd8904d6f18f408c85fbbc592d7d20dee7986969efbda081fdf8bc40e1b1336d6b638110c836bfdc3f314560d2e49cd4fbde1e20b024100e32a4e793b574c9c4a94c8803db5152141e72d03de64e54ef2c8ed104988ca780cd11397bc359630d01b97ebd87067c5451ba777cf045ca23f5912f1031308c702406dfcdbbd5a57c9f85abc4edf9e9e29153507b07ce0a7ef6f52e60dcfebe1b8341babd8b789a837485da6c8d55b29bbb142ace3c24a1f5b54b454d01b51e2ad03024100bd6a2b60dee01e1b3bfcef6a2f09ed027c273cdbbaf6ba55a80f6dcc64e4509ee560f84b4f3e076bd03b11e42fe71a3fdd2dffe7e0902c8584f8cad877cdc945024100aa512fa4ada69881f1d8bb8ad6614f192b83200aef5edf4811313d5ef30a86cbd0a90f7b025c71ea06ec6b34db6306c86b1040670fd8654ad7291d066d06d031"
  2368  const hexPKCS1TestECKey = "3081a40201010430bdb9839c08ee793d1157886a7a758a3c8b2a17a4df48f17ace57c72c56b4723cf21dcda21d4e1ad57ff034f19fcfd98ea00706052b81040022a16403620004feea808b5ee2429cfcce13c32160e1c960990bd050bb0fdf7222f3decd0a55008e32a6aa3c9062051c4cba92a7a3b178b24567412d43cdd2f882fa5addddd726fe3e208d2c26d733a773a597abb749714df7256ead5105fa6e7b3650de236b50"
  2369  
  2370  var pkcs1MismatchKeyTests = []struct {
  2371  	hexKey        string
  2372  	errorContains string
  2373  }{
  2374  	{hexKey: hexPKCS1TestPKCS8Key, errorContains: "use ParsePKCS8PrivateKey instead"},
  2375  	{hexKey: hexPKCS1TestECKey, errorContains: "use ParseECPrivateKey instead"},
  2376  }
  2377  
  2378  func TestPKCS1MismatchKeyFormat(t *testing.T) {
  2379  	for i, test := range pkcs1MismatchKeyTests {
  2380  		derBytes, _ := hex.DecodeString(test.hexKey)
  2381  		_, err := ParsePKCS1PrivateKey(derBytes)
  2382  		if !strings.Contains(err.Error(), test.errorContains) {
  2383  			t.Errorf("#%d: expected error containing %q, got %s", i, test.errorContains, err)
  2384  		}
  2385  	}
  2386  }
  2387  
  2388  func TestCreateRevocationList(t *testing.T) {
  2389  	ec256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2390  	if err != nil {
  2391  		t.Fatalf("Failed to generate ECDSA P256 key: %s", err)
  2392  	}
  2393  	_, ed25519Priv, err := ed25519.GenerateKey(rand.Reader)
  2394  	if err != nil {
  2395  		t.Fatalf("Failed to generate Ed25519 key: %s", err)
  2396  	}
  2397  	tests := []struct {
  2398  		name          string
  2399  		key           crypto.Signer
  2400  		issuer        *Certificate
  2401  		template      *RevocationList
  2402  		expectedError string
  2403  	}{
  2404  		{
  2405  			name:          "nil template",
  2406  			key:           ec256Priv,
  2407  			issuer:        nil,
  2408  			template:      nil,
  2409  			expectedError: "x509: template can not be nil",
  2410  		},
  2411  		{
  2412  			name:          "nil issuer",
  2413  			key:           ec256Priv,
  2414  			issuer:        nil,
  2415  			template:      &RevocationList{},
  2416  			expectedError: "x509: issuer can not be nil",
  2417  		},
  2418  		{
  2419  			name: "issuer doesn't have crlSign key usage bit set",
  2420  			key:  ec256Priv,
  2421  			issuer: &Certificate{
  2422  				KeyUsage: KeyUsageCertSign,
  2423  			},
  2424  			template:      &RevocationList{},
  2425  			expectedError: "x509: issuer must have the crlSign key usage bit set",
  2426  		},
  2427  		{
  2428  			name: "issuer missing SubjectKeyId",
  2429  			key:  ec256Priv,
  2430  			issuer: &Certificate{
  2431  				KeyUsage: KeyUsageCRLSign,
  2432  			},
  2433  			template:      &RevocationList{},
  2434  			expectedError: "x509: issuer certificate doesn't contain a subject key identifier",
  2435  		},
  2436  		{
  2437  			name: "nextUpdate before thisUpdate",
  2438  			key:  ec256Priv,
  2439  			issuer: &Certificate{
  2440  				KeyUsage: KeyUsageCRLSign,
  2441  				Subject: pkix.Name{
  2442  					CommonName: "testing",
  2443  				},
  2444  				SubjectKeyId: []byte{1, 2, 3},
  2445  			},
  2446  			template: &RevocationList{
  2447  				ThisUpdate: time.Time{}.Add(time.Hour),
  2448  				NextUpdate: time.Time{},
  2449  			},
  2450  			expectedError: "x509: template.ThisUpdate is after template.NextUpdate",
  2451  		},
  2452  		{
  2453  			name: "nil Number",
  2454  			key:  ec256Priv,
  2455  			issuer: &Certificate{
  2456  				KeyUsage: KeyUsageCRLSign,
  2457  				Subject: pkix.Name{
  2458  					CommonName: "testing",
  2459  				},
  2460  				SubjectKeyId: []byte{1, 2, 3},
  2461  			},
  2462  			template: &RevocationList{
  2463  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2464  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2465  			},
  2466  			expectedError: "x509: template contains nil Number field",
  2467  		},
  2468  		{
  2469  			name: "invalid signature algorithm",
  2470  			key:  ec256Priv,
  2471  			issuer: &Certificate{
  2472  				KeyUsage: KeyUsageCRLSign,
  2473  				Subject: pkix.Name{
  2474  					CommonName: "testing",
  2475  				},
  2476  				SubjectKeyId: []byte{1, 2, 3},
  2477  			},
  2478  			template: &RevocationList{
  2479  				SignatureAlgorithm: SHA256WithRSA,
  2480  				RevokedCertificates: []pkix.RevokedCertificate{
  2481  					{
  2482  						SerialNumber:   big.NewInt(2),
  2483  						RevocationTime: time.Time{}.Add(time.Hour),
  2484  					},
  2485  				},
  2486  				Number:     big.NewInt(5),
  2487  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2488  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2489  			},
  2490  			expectedError: "x509: requested SignatureAlgorithm does not match private key type",
  2491  		},
  2492  		{
  2493  			name: "valid",
  2494  			key:  ec256Priv,
  2495  			issuer: &Certificate{
  2496  				KeyUsage: KeyUsageCRLSign,
  2497  				Subject: pkix.Name{
  2498  					CommonName: "testing",
  2499  				},
  2500  				SubjectKeyId: []byte{1, 2, 3},
  2501  			},
  2502  			template: &RevocationList{
  2503  				RevokedCertificates: []pkix.RevokedCertificate{
  2504  					{
  2505  						SerialNumber:   big.NewInt(2),
  2506  						RevocationTime: time.Time{}.Add(time.Hour),
  2507  					},
  2508  				},
  2509  				Number:     big.NewInt(5),
  2510  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2511  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2512  			},
  2513  		},
  2514  		{
  2515  			name: "valid, Ed25519 key",
  2516  			key:  ed25519Priv,
  2517  			issuer: &Certificate{
  2518  				KeyUsage: KeyUsageCRLSign,
  2519  				Subject: pkix.Name{
  2520  					CommonName: "testing",
  2521  				},
  2522  				SubjectKeyId: []byte{1, 2, 3},
  2523  			},
  2524  			template: &RevocationList{
  2525  				RevokedCertificates: []pkix.RevokedCertificate{
  2526  					{
  2527  						SerialNumber:   big.NewInt(2),
  2528  						RevocationTime: time.Time{}.Add(time.Hour),
  2529  					},
  2530  				},
  2531  				Number:     big.NewInt(5),
  2532  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2533  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2534  			},
  2535  		},
  2536  		{
  2537  			name: "valid, non-default signature algorithm",
  2538  			key:  ec256Priv,
  2539  			issuer: &Certificate{
  2540  				KeyUsage: KeyUsageCRLSign,
  2541  				Subject: pkix.Name{
  2542  					CommonName: "testing",
  2543  				},
  2544  				SubjectKeyId: []byte{1, 2, 3},
  2545  			},
  2546  			template: &RevocationList{
  2547  				SignatureAlgorithm: ECDSAWithSHA512,
  2548  				RevokedCertificates: []pkix.RevokedCertificate{
  2549  					{
  2550  						SerialNumber:   big.NewInt(2),
  2551  						RevocationTime: time.Time{}.Add(time.Hour),
  2552  					},
  2553  				},
  2554  				Number:     big.NewInt(5),
  2555  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2556  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2557  			},
  2558  		},
  2559  		{
  2560  			name: "valid, extra extension",
  2561  			key:  ec256Priv,
  2562  			issuer: &Certificate{
  2563  				KeyUsage: KeyUsageCRLSign,
  2564  				Subject: pkix.Name{
  2565  					CommonName: "testing",
  2566  				},
  2567  				SubjectKeyId: []byte{1, 2, 3},
  2568  			},
  2569  			template: &RevocationList{
  2570  				RevokedCertificates: []pkix.RevokedCertificate{
  2571  					{
  2572  						SerialNumber:   big.NewInt(2),
  2573  						RevocationTime: time.Time{}.Add(time.Hour),
  2574  					},
  2575  				},
  2576  				Number:     big.NewInt(5),
  2577  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2578  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2579  				ExtraExtensions: []pkix.Extension{
  2580  					{
  2581  						Id:    []int{2, 5, 29, 99},
  2582  						Value: []byte{5, 0},
  2583  					},
  2584  				},
  2585  			},
  2586  		},
  2587  		{
  2588  			name: "valid, empty list",
  2589  			key:  ec256Priv,
  2590  			issuer: &Certificate{
  2591  				KeyUsage: KeyUsageCRLSign,
  2592  				Subject: pkix.Name{
  2593  					CommonName: "testing",
  2594  				},
  2595  				SubjectKeyId: []byte{1, 2, 3},
  2596  			},
  2597  			template: &RevocationList{
  2598  				Number:     big.NewInt(5),
  2599  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2600  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2601  			},
  2602  		},
  2603  	}
  2604  
  2605  	for _, tc := range tests {
  2606  		t.Run(tc.name, func(t *testing.T) {
  2607  			crl, err := CreateRevocationList(rand.Reader, tc.template, tc.issuer, tc.key)
  2608  			if err != nil && tc.expectedError == "" {
  2609  				t.Fatalf("CreateRevocationList failed unexpectedly: %s", err)
  2610  			} else if err != nil && tc.expectedError != err.Error() {
  2611  				t.Fatalf("CreateRevocationList failed unexpectedly, wanted: %s, got: %s", tc.expectedError, err)
  2612  			} else if err == nil && tc.expectedError != "" {
  2613  				t.Fatalf("CreateRevocationList didn't fail, expected: %s", tc.expectedError)
  2614  			}
  2615  			if tc.expectedError != "" {
  2616  				return
  2617  			}
  2618  
  2619  			parsedCRL, err := ParseDERCRL(crl)
  2620  			if err != nil {
  2621  				t.Fatalf("Failed to parse generated CRL: %s", err)
  2622  			}
  2623  
  2624  			if tc.template.SignatureAlgorithm != UnknownSignatureAlgorithm &&
  2625  				parsedCRL.SignatureAlgorithm.Algorithm.Equal(signatureAlgorithmDetails[tc.template.SignatureAlgorithm].oid) {
  2626  				t.Fatalf("SignatureAlgorithm mismatch: got %v; want %v.", parsedCRL.SignatureAlgorithm,
  2627  					tc.template.SignatureAlgorithm)
  2628  			}
  2629  
  2630  			if !reflect.DeepEqual(parsedCRL.TBSCertList.RevokedCertificates, tc.template.RevokedCertificates) {
  2631  				t.Fatalf("RevokedCertificates mismatch: got %v; want %v.",
  2632  					parsedCRL.TBSCertList.RevokedCertificates, tc.template.RevokedCertificates)
  2633  			}
  2634  
  2635  			if len(parsedCRL.TBSCertList.Extensions) != 2+len(tc.template.ExtraExtensions) {
  2636  				t.Fatalf("Generated CRL has wrong number of extensions, wanted: %d, got: %d", 2+len(tc.template.ExtraExtensions), len(parsedCRL.TBSCertList.Extensions))
  2637  			}
  2638  			expectedAKI, err := asn1.Marshal(authKeyId{Id: tc.issuer.SubjectKeyId})
  2639  			if err != nil {
  2640  				t.Fatalf("asn1.Marshal failed: %s", err)
  2641  			}
  2642  			akiExt := pkix.Extension{
  2643  				Id:    oidExtensionAuthorityKeyId,
  2644  				Value: expectedAKI,
  2645  			}
  2646  			if !reflect.DeepEqual(parsedCRL.TBSCertList.Extensions[0], akiExt) {
  2647  				t.Fatalf("Unexpected first extension: got %v, want %v",
  2648  					parsedCRL.TBSCertList.Extensions[0], akiExt)
  2649  			}
  2650  			expectedNum, err := asn1.Marshal(tc.template.Number)
  2651  			if err != nil {
  2652  				t.Fatalf("asn1.Marshal failed: %s", err)
  2653  			}
  2654  			crlExt := pkix.Extension{
  2655  				Id:    oidExtensionCRLNumber,
  2656  				Value: expectedNum,
  2657  			}
  2658  			if !reflect.DeepEqual(parsedCRL.TBSCertList.Extensions[1], crlExt) {
  2659  				t.Fatalf("Unexpected second extension: got %v, want %v",
  2660  					parsedCRL.TBSCertList.Extensions[1], crlExt)
  2661  			}
  2662  			if len(parsedCRL.TBSCertList.Extensions[2:]) == 0 && len(tc.template.ExtraExtensions) == 0 {
  2663  				// If we don't have anything to check return early so we don't
  2664  				// hit a [] != nil false positive below.
  2665  				return
  2666  			}
  2667  			if !reflect.DeepEqual(parsedCRL.TBSCertList.Extensions[2:], tc.template.ExtraExtensions) {
  2668  				t.Fatalf("Extensions mismatch: got %v; want %v.",
  2669  					parsedCRL.TBSCertList.Extensions[2:], tc.template.ExtraExtensions)
  2670  			}
  2671  		})
  2672  	}
  2673  }
  2674  
  2675  func TestRSAPSAParameters(t *testing.T) {
  2676  	generateParams := func(hashFunc Hash) []byte {
  2677  		var hashOID asn1.ObjectIdentifier
  2678  
  2679  		switch hashFunc {
  2680  		case SHA256:
  2681  			hashOID = oidSHA256
  2682  		case SHA384:
  2683  			hashOID = oidSHA384
  2684  		case SHA512:
  2685  			hashOID = oidSHA512
  2686  		}
  2687  
  2688  		params := pssParameters{
  2689  			Hash: pkix.AlgorithmIdentifier{
  2690  				Algorithm:  hashOID,
  2691  				Parameters: asn1.NullRawValue,
  2692  			},
  2693  			MGF: pkix.AlgorithmIdentifier{
  2694  				Algorithm: oidMGF1,
  2695  			},
  2696  			SaltLength:   hashFunc.Size(),
  2697  			TrailerField: 1,
  2698  		}
  2699  
  2700  		mgf1Params := pkix.AlgorithmIdentifier{
  2701  			Algorithm:  hashOID,
  2702  			Parameters: asn1.NullRawValue,
  2703  		}
  2704  
  2705  		var err error
  2706  		params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
  2707  		if err != nil {
  2708  			t.Fatalf("failed to marshal MGF parameters: %s", err)
  2709  		}
  2710  
  2711  		serialized, err := asn1.Marshal(params)
  2712  		if err != nil {
  2713  			t.Fatalf("failed to marshal parameters: %s", err)
  2714  		}
  2715  
  2716  		return serialized
  2717  	}
  2718  
  2719  	for h, params := range hashToPSSParameters {
  2720  		generated := generateParams(h)
  2721  		if !bytes.Equal(params.FullBytes, generated) {
  2722  			t.Errorf("hardcoded parameters for %s didn't match generated parameters: got (generated) %x, wanted (hardcoded) %x", h, generated, params.FullBytes)
  2723  		}
  2724  	}
  2725  }
  2726  
  2727  func TestUnknownExtKey(t *testing.T) {
  2728  	const errorContains = "unknown extended key usage"
  2729  
  2730  	template := &Certificate{
  2731  		SerialNumber: big.NewInt(10),
  2732  		DNSNames:     []string{"foo"},
  2733  		ExtKeyUsage:  []ExtKeyUsage{ExtKeyUsage(-1)},
  2734  	}
  2735  	signer, err := rsa.GenerateKey(rand.Reader, 1024)
  2736  	if err != nil {
  2737  		t.Errorf("failed to generate key for TestUnknownExtKey")
  2738  	}
  2739  
  2740  	_, err = CreateCertificate(rand.Reader, template, template, signer.Public(), signer)
  2741  	if !strings.Contains(err.Error(), errorContains) {
  2742  		t.Errorf("expected error containing %q, got %s", errorContains, err)
  2743  	}
  2744  }
  2745  
  2746  func TestIA5SANEnforcement(t *testing.T) {
  2747  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2748  	if err != nil {
  2749  		t.Fatalf("ecdsa.GenerateKey failed: %s", err)
  2750  	}
  2751  
  2752  	testURL, err := url.Parse("https://example.com/")
  2753  	if err != nil {
  2754  		t.Fatalf("url.Parse failed: %s", err)
  2755  	}
  2756  	testURL.RawQuery = "∞"
  2757  
  2758  	marshalTests := []struct {
  2759  		name          string
  2760  		template      *Certificate
  2761  		expectedError string
  2762  	}{
  2763  		{
  2764  			name: "marshal: unicode dNSName",
  2765  			template: &Certificate{
  2766  				SerialNumber: big.NewInt(0),
  2767  				DNSNames:     []string{"∞"},
  2768  			},
  2769  			expectedError: "x509: \"∞\" cannot be encoded as an IA5String",
  2770  		},
  2771  		{
  2772  			name: "marshal: unicode rfc822Name",
  2773  			template: &Certificate{
  2774  				SerialNumber:   big.NewInt(0),
  2775  				EmailAddresses: []string{"∞"},
  2776  			},
  2777  			expectedError: "x509: \"∞\" cannot be encoded as an IA5String",
  2778  		},
  2779  		{
  2780  			name: "marshal: unicode uniformResourceIdentifier",
  2781  			template: &Certificate{
  2782  				SerialNumber: big.NewInt(0),
  2783  				URIs:         []*url.URL{testURL},
  2784  			},
  2785  			expectedError: "x509: \"https://example.com/?∞\" cannot be encoded as an IA5String",
  2786  		},
  2787  	}
  2788  
  2789  	for _, tc := range marshalTests {
  2790  		t.Run(tc.name, func(t *testing.T) {
  2791  			_, err := CreateCertificate(rand.Reader, tc.template, tc.template, k.Public(), k)
  2792  			if err == nil {
  2793  				t.Errorf("expected CreateCertificate to fail with template: %v", tc.template)
  2794  			} else if err.Error() != tc.expectedError {
  2795  				t.Errorf("unexpected error: got %q, want %q", err.Error(), tc.expectedError)
  2796  			}
  2797  		})
  2798  	}
  2799  
  2800  	unmarshalTests := []struct {
  2801  		name          string
  2802  		cert          string
  2803  		expectedError string
  2804  	}{
  2805  		{
  2806  			name:          "unmarshal: unicode dNSName",
  2807  			cert:          "308201083081aea003020102020100300a06082a8648ce3d04030230003022180f30303031303130313030303030305a180f30303031303130313030303030305a30003059301306072a8648ce3d020106082a8648ce3d0301070342000424bcc48180d8d9db794028f2575ebe3cac79f04d7b0d0151c5292e588aac3668c495f108c626168462e0668c9705e08a211dd103a659d2684e0adf8c2bfd47baa315301330110603551d110101ff040730058203e2889e300a06082a8648ce3d04030203490030460221008ac7827ac326a6ee0fa70b2afe99af575ec60b975f820f3c25f60fff43fbccd0022100bffeed93556722d43d13e461d5b3e33efc61f6349300327d3a0196cb6da501c2",
  2808  			expectedError: "x509: SAN dNSName is malformed",
  2809  		},
  2810  		{
  2811  			name:          "unmarshal: unicode rfc822Name",
  2812  			cert:          "308201083081aea003020102020100300a06082a8648ce3d04030230003022180f30303031303130313030303030305a180f30303031303130313030303030305a30003059301306072a8648ce3d020106082a8648ce3d0301070342000405cb4c4ba72aac980f7b11b0285191425e29e196ce7c5df1c83f56886566e517f196657cc1b73de89ab84ce503fd634e2f2af88fde24c63ca536dc3a5eed2665a315301330110603551d110101ff040730058103e2889e300a06082a8648ce3d0403020349003046022100ed1431cd4b9bb03d88d1511a0ec128a51204375764c716280dc36e2a60142c8902210088c96d25cfaf97eea851ff17d87bb6fe619d6546656e1739f35c3566051c3d0f",
  2813  			expectedError: "x509: SAN rfc822Name is malformed",
  2814  		},
  2815  		{
  2816  			name:          "unmarshal: unicode uniformResourceIdentifier",
  2817  			cert:          "3082011b3081c3a003020102020100300a06082a8648ce3d04030230003022180f30303031303130313030303030305a180f30303031303130313030303030305a30003059301306072a8648ce3d020106082a8648ce3d03010703420004ce0a79b511701d9188e1ea76bcc5907f1db51de6cc1a037b803f256e8588145ca409d120288bfeb4e38f3088104674d374b35bb91fc80d768d1d519dbe2b0b5aa32a302830260603551d110101ff041c301a861868747470733a2f2f6578616d706c652e636f6d2f3fe2889e300a06082a8648ce3d0403020347003044022044f4697779fd1dae1e382d2452413c5c5ca67851e267d6bc64a8d164977c172c0220505015e657637aa1945d46e7650b6f59b968fc1508ca8b152c99f782446dfc81",
  2818  			expectedError: "x509: SAN uniformResourceIdentifier is malformed",
  2819  		},
  2820  	}
  2821  
  2822  	for _, tc := range unmarshalTests {
  2823  		der, err := hex.DecodeString(tc.cert)
  2824  		if err != nil {
  2825  			t.Fatalf("failed to decode test cert: %s", err)
  2826  		}
  2827  		_, err = ParseCertificate(der)
  2828  		if err == nil {
  2829  			t.Error("expected CreateCertificate to fail")
  2830  		} else if err.Error() != tc.expectedError {
  2831  			t.Errorf("unexpected error: got %q, want %q", err.Error(), tc.expectedError)
  2832  		}
  2833  	}
  2834  }
  2835  
  2836  func BenchmarkCreateCertificate(b *testing.B) {
  2837  	template := &Certificate{
  2838  		SerialNumber: big.NewInt(10),
  2839  		DNSNames:     []string{"example.com"},
  2840  	}
  2841  	tests := []struct {
  2842  		name string
  2843  		gen  func() crypto.Signer
  2844  	}{
  2845  		{
  2846  			name: "RSA 2048",
  2847  			gen: func() crypto.Signer {
  2848  				k, err := rsa.GenerateKey(rand.Reader, 2048)
  2849  				if err != nil {
  2850  					b.Fatalf("failed to generate test key: %s", err)
  2851  				}
  2852  				return k
  2853  			},
  2854  		},
  2855  		{
  2856  			name: "ECDSA P256",
  2857  			gen: func() crypto.Signer {
  2858  				k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2859  				if err != nil {
  2860  					b.Fatalf("failed to generate test key: %s", err)
  2861  				}
  2862  				return k
  2863  			},
  2864  		},
  2865  	}
  2866  
  2867  	for _, tc := range tests {
  2868  		k := tc.gen()
  2869  		b.ResetTimer()
  2870  		b.Run(tc.name, func(b *testing.B) {
  2871  			for i := 0; i < b.N; i++ {
  2872  				_, err := CreateCertificate(rand.Reader, template, template, k.Public(), k)
  2873  				if err != nil {
  2874  					b.Fatalf("failed to create certificate: %s", err)
  2875  				}
  2876  			}
  2877  		})
  2878  	}
  2879  }
  2880  
  2881  type brokenSigner struct {
  2882  	pub crypto.PublicKey
  2883  }
  2884  
  2885  func (bs *brokenSigner) Public() crypto.PublicKey {
  2886  	return bs.pub
  2887  }
  2888  
  2889  func (bs *brokenSigner) Sign(_ io.Reader, _ []byte, _ crypto.SignerOpts) ([]byte, error) {
  2890  	return []byte{1, 2, 3}, nil
  2891  }
  2892  
  2893  func TestCreateCertificateBrokenSigner(t *testing.T) {
  2894  	template := &Certificate{
  2895  		SerialNumber: big.NewInt(10),
  2896  		DNSNames:     []string{"example.com"},
  2897  	}
  2898  	k, err := rsa.GenerateKey(rand.Reader, 1024)
  2899  	if err != nil {
  2900  		t.Fatalf("failed to generate test key: %s", err)
  2901  	}
  2902  	expectedErr := "x509: signature over certificate returned by signer is invalid: crypto/rsa: verification error"
  2903  	_, err = CreateCertificate(rand.Reader, template, template, k.Public(), &brokenSigner{k.Public()})
  2904  	if err == nil {
  2905  		t.Fatal("expected CreateCertificate to fail with a broken signer")
  2906  	} else if err.Error() != expectedErr {
  2907  		t.Fatalf("CreateCertificate returned an unexpected error: got %q, want %q", err, expectedErr)
  2908  	}
  2909  }
  2910  
  2911  func TestCreateCertificateMD5(t *testing.T) {
  2912  	template := &Certificate{
  2913  		SerialNumber:       big.NewInt(10),
  2914  		DNSNames:           []string{"example.com"},
  2915  		SignatureAlgorithm: MD5WithRSA,
  2916  	}
  2917  	k, err := rsa.GenerateKey(rand.Reader, 1024)
  2918  	if err != nil {
  2919  		t.Fatalf("failed to generate test key: %s", err)
  2920  	}
  2921  	_, err = CreateCertificate(rand.Reader, template, template, k.Public(), &brokenSigner{k.Public()})
  2922  	if err != nil {
  2923  		t.Fatalf("CreateCertificate failed when SignatureAlgorithm = MD5WithRSA: %s", err)
  2924  	}
  2925  }
  2926  
  2927  func (s *CertPool) mustCert(t *testing.T, n int) *Certificate {
  2928  	c, err := s.lazyCerts[n].getCert()
  2929  	if err != nil {
  2930  		t.Fatalf("failed to load cert %d: %v", n, err)
  2931  	}
  2932  	return c
  2933  }
  2934  
  2935  func allCerts(t *testing.T, p *CertPool) []*Certificate {
  2936  	all := make([]*Certificate, p.len())
  2937  	for i := range all {
  2938  		all[i] = p.mustCert(t, i)
  2939  	}
  2940  	return all
  2941  }
  2942  
  2943  // certPoolEqual reports whether a and b are equal, except for the
  2944  // function pointers.
  2945  func certPoolEqual(a, b *CertPool) bool {
  2946  	if (a != nil) != (b != nil) {
  2947  		return false
  2948  	}
  2949  	if a == nil {
  2950  		return true
  2951  	}
  2952  	if !reflect.DeepEqual(a.byName, b.byName) ||
  2953  		len(a.lazyCerts) != len(b.lazyCerts) {
  2954  		return false
  2955  	}
  2956  	for i := range a.lazyCerts {
  2957  		la, lb := a.lazyCerts[i], b.lazyCerts[i]
  2958  		if !bytes.Equal(la.rawSubject, lb.rawSubject) {
  2959  			return false
  2960  		}
  2961  		ca, err := la.getCert()
  2962  		if err != nil {
  2963  			panic(err)
  2964  		}
  2965  		cb, err := la.getCert()
  2966  		if err != nil {
  2967  			panic(err)
  2968  		}
  2969  		if !ca.Equal(cb) {
  2970  			return false
  2971  		}
  2972  	}
  2973  
  2974  	return true
  2975  }
  2976  
  2977  func TestCertificateRequestRoundtripFields(t *testing.T) {
  2978  	urlA, err := url.Parse("https://example.com/_")
  2979  	if err != nil {
  2980  		t.Fatal(err)
  2981  	}
  2982  	urlB, err := url.Parse("https://example.org/_")
  2983  	if err != nil {
  2984  		t.Fatal(err)
  2985  	}
  2986  	in := &CertificateRequest{
  2987  		DNSNames:       []string{"example.com", "example.org"},
  2988  		EmailAddresses: []string{"a@example.com", "b@example.com"},
  2989  		IPAddresses:    []net.IP{net.IPv4(192, 0, 2, 0), net.IPv6loopback},
  2990  		URIs:           []*url.URL{urlA, urlB},
  2991  	}
  2992  	out := marshalAndParseCSR(t, in)
  2993  
  2994  	if !reflect.DeepEqual(in.DNSNames, out.DNSNames) {
  2995  		t.Fatalf("Unexpected DNSNames: got %v, want %v", out.DNSNames, in.DNSNames)
  2996  	}
  2997  	if !reflect.DeepEqual(in.EmailAddresses, out.EmailAddresses) {
  2998  		t.Fatalf("Unexpected EmailAddresses: got %v, want %v", out.EmailAddresses, in.EmailAddresses)
  2999  	}
  3000  	if len(in.IPAddresses) != len(out.IPAddresses) ||
  3001  		!in.IPAddresses[0].Equal(out.IPAddresses[0]) ||
  3002  		!in.IPAddresses[1].Equal(out.IPAddresses[1]) {
  3003  		t.Fatalf("Unexpected IPAddresses: got %v, want %v", out.IPAddresses, in.IPAddresses)
  3004  	}
  3005  	if !reflect.DeepEqual(in.URIs, out.URIs) {
  3006  		t.Fatalf("Unexpected URIs: got %v, want %v", out.URIs, in.URIs)
  3007  	}
  3008  }
  3009  
  3010  func BenchmarkParseCertificate(b *testing.B) {
  3011  	cases := []struct {
  3012  		name string
  3013  		pem  string
  3014  	}{
  3015  		{
  3016  			name: "ecdsa leaf",
  3017  			pem: `-----BEGIN CERTIFICATE-----
  3018  MIIINjCCBx6gAwIBAgIQHdQ6oBMoe/MJAAAAAEHzmTANBgkqhkiG9w0BAQsFADBG
  3019  MQswCQYDVQQGEwJVUzEiMCAGA1UEChMZR29vZ2xlIFRydXN0IFNlcnZpY2VzIExM
  3020  QzETMBEGA1UEAxMKR1RTIENBIDFDMzAeFw0yMDEyMDgwOTExMzZaFw0yMTAzMDIw
  3021  OTExMzVaMBcxFTATBgNVBAMMDCouZ29vZ2xlLmNvbTBZMBMGByqGSM49AgEGCCqG
  3022  SM49AwEHA0IABEFYegyHh1AHRS1nar5+zYJgMACcsIQMtg0YMyK/59ml8ERIt/JF
  3023  kXM3XIvQuCJhghUawZrrAcAs8djZF1U9M4mjggYYMIIGFDAOBgNVHQ8BAf8EBAMC
  3024  B4AwEwYDVR0lBAwwCgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQU
  3025  6SWWF36XBsmXJ6iV0EHPXUFoMbwwHwYDVR0jBBgwFoAUinR/r4XN7pXNPZzQ4kYU
  3026  83E1HScwagYIKwYBBQUHAQEEXjBcMCcGCCsGAQUFBzABhhtodHRwOi8vb2NzcC5w
  3027  a2kuZ29vZy9ndHMxYzMwMQYIKwYBBQUHMAKGJWh0dHA6Ly9wa2kuZ29vZy9yZXBv
  3028  L2NlcnRzL2d0czFjMy5kZXIwggTCBgNVHREEggS5MIIEtYIMKi5nb29nbGUuY29t
  3029  gg0qLmFuZHJvaWQuY29tghYqLmFwcGVuZ2luZS5nb29nbGUuY29tggkqLmJkbi5k
  3030  ZXaCEiouY2xvdWQuZ29vZ2xlLmNvbYIYKi5jcm93ZHNvdXJjZS5nb29nbGUuY29t
  3031  ghgqLmRhdGFjb21wdXRlLmdvb2dsZS5jb22CBiouZy5jb4IOKi5nY3AuZ3Z0Mi5j
  3032  b22CESouZ2NwY2RuLmd2dDEuY29tggoqLmdncGh0LmNugg4qLmdrZWNuYXBwcy5j
  3033  boIWKi5nb29nbGUtYW5hbHl0aWNzLmNvbYILKi5nb29nbGUuY2GCCyouZ29vZ2xl
  3034  LmNsgg4qLmdvb2dsZS5jby5pboIOKi5nb29nbGUuY28uanCCDiouZ29vZ2xlLmNv
  3035  LnVrgg8qLmdvb2dsZS5jb20uYXKCDyouZ29vZ2xlLmNvbS5hdYIPKi5nb29nbGUu
  3036  Y29tLmJygg8qLmdvb2dsZS5jb20uY2+CDyouZ29vZ2xlLmNvbS5teIIPKi5nb29n
  3037  bGUuY29tLnRygg8qLmdvb2dsZS5jb20udm6CCyouZ29vZ2xlLmRlggsqLmdvb2ds
  3038  ZS5lc4ILKi5nb29nbGUuZnKCCyouZ29vZ2xlLmh1ggsqLmdvb2dsZS5pdIILKi5n
  3039  b29nbGUubmyCCyouZ29vZ2xlLnBsggsqLmdvb2dsZS5wdIISKi5nb29nbGVhZGFw
  3040  aXMuY29tgg8qLmdvb2dsZWFwaXMuY26CESouZ29vZ2xlY25hcHBzLmNughQqLmdv
  3041  b2dsZWNvbW1lcmNlLmNvbYIRKi5nb29nbGV2aWRlby5jb22CDCouZ3N0YXRpYy5j
  3042  boINKi5nc3RhdGljLmNvbYISKi5nc3RhdGljY25hcHBzLmNuggoqLmd2dDEuY29t
  3043  ggoqLmd2dDIuY29tghQqLm1ldHJpYy5nc3RhdGljLmNvbYIMKi51cmNoaW4uY29t
  3044  ghAqLnVybC5nb29nbGUuY29tghMqLndlYXIuZ2tlY25hcHBzLmNughYqLnlvdXR1
  3045  YmUtbm9jb29raWUuY29tgg0qLnlvdXR1YmUuY29tghYqLnlvdXR1YmVlZHVjYXRp
  3046  b24uY29tghEqLnlvdXR1YmVraWRzLmNvbYIHKi55dC5iZYILKi55dGltZy5jb22C
  3047  GmFuZHJvaWQuY2xpZW50cy5nb29nbGUuY29tggthbmRyb2lkLmNvbYIbZGV2ZWxv
  3048  cGVyLmFuZHJvaWQuZ29vZ2xlLmNughxkZXZlbG9wZXJzLmFuZHJvaWQuZ29vZ2xl
  3049  LmNuggRnLmNvgghnZ3BodC5jboIMZ2tlY25hcHBzLmNuggZnb28uZ2yCFGdvb2ds
  3050  ZS1hbmFseXRpY3MuY29tggpnb29nbGUuY29tgg9nb29nbGVjbmFwcHMuY26CEmdv
  3051  b2dsZWNvbW1lcmNlLmNvbYIYc291cmNlLmFuZHJvaWQuZ29vZ2xlLmNuggp1cmNo
  3052  aW4uY29tggp3d3cuZ29vLmdsggh5b3V0dS5iZYILeW91dHViZS5jb22CFHlvdXR1
  3053  YmVlZHVjYXRpb24uY29tgg95b3V0dWJla2lkcy5jb22CBXl0LmJlMCEGA1UdIAQa
  3054  MBgwCAYGZ4EMAQIBMAwGCisGAQQB1nkCBQMwNQYDVR0fBC4wLDAqoCigJoYkaHR0
  3055  cDovL2NybC5wa2kuZ29vZy9ndHNyMS9ndHMxYzMuY3JsMBMGCisGAQQB1nkCBAMB
  3056  Af8EAgUAMA0GCSqGSIb3DQEBCwUAA4IBAQAlDQm5zY7JcPxcJ9ulfTGsWV/m6Pro
  3057  gLYmAlBUPGKy313aetT4Zjz44ZseVtUOKsXVHh4avPA9O+ta1FgkASlbkgJ05ivb
  3058  j/+MMqkrLemdMv9Svvx3CNaAq2jJ2E+8GdrA1RzMkiNthJCiRafaPnXnN6hOHGNr
  3059  GtqYfMHsvrRHW8J2IPHW0/MUHmJ/NDu/vNchxke2OEfCPLtseo3hJt8l8HbH+yE8
  3060  DFrt8YVRi1CLomEyuPJDF4og3O3ZsoXuxcPd9UPxULOCxycdolRw8Iv/Xgr082j3
  3061  svXC3HUd3apM2Yy3xJAlk/mUkzVXfdJZ+Zy1huNsUoJ+gM8rmpyGhYyx
  3062  -----END CERTIFICATE-----`,
  3063  		},
  3064  		{
  3065  			name: "rsa leaf",
  3066  			pem: `-----BEGIN CERTIFICATE-----
  3067  MIIJXjCCCEagAwIBAgIRAPYaTUsjP4iRBQAAAACHSSgwDQYJKoZIhvcNAQELBQAw
  3068  QjELMAkGA1UEBhMCVVMxHjAcBgNVBAoTFUdvb2dsZSBUcnVzdCBTZXJ2aWNlczET
  3069  MBEGA1UEAxMKR1RTIENBIDFPMTAeFw0yMTAxMjYwODQ2MzRaFw0yMTA0MjAwODQ2
  3070  MzNaMGYxCzAJBgNVBAYTAlVTMRMwEQYDVQQIEwpDYWxpZm9ybmlhMRYwFAYDVQQH
  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ghMqLmZsYXNoLmFuZHJvaWQuY29tggYqLmcuY2+CDiou
  3087  Z2NwLmd2dDIuY29tghEqLmdjcGNkbi5ndnQxLmNvbYIKKi5nZ3BodC5jboIOKi5n
  3088  a2VjbmFwcHMuY26CFiouZ29vZ2xlLWFuYWx5dGljcy5jb22CCyouZ29vZ2xlLmNh
  3089  ggsqLmdvb2dsZS5jbIIOKi5nb29nbGUuY28uaW6CDiouZ29vZ2xlLmNvLmpwgg4q
  3090  Lmdvb2dsZS5jby51a4IPKi5nb29nbGUuY29tLmFygg8qLmdvb2dsZS5jb20uYXWC
  3091  DyouZ29vZ2xlLmNvbS5icoIPKi5nb29nbGUuY29tLmNvgg8qLmdvb2dsZS5jb20u
  3092  bXiCDyouZ29vZ2xlLmNvbS50coIPKi5nb29nbGUuY29tLnZuggsqLmdvb2dsZS5k
  3093  ZYILKi5nb29nbGUuZXOCCyouZ29vZ2xlLmZyggsqLmdvb2dsZS5odYILKi5nb29n
  3094  bGUuaXSCCyouZ29vZ2xlLm5sggsqLmdvb2dsZS5wbIILKi5nb29nbGUucHSCEiou
  3095  Z29vZ2xlYWRhcGlzLmNvbYIPKi5nb29nbGVhcGlzLmNughEqLmdvb2dsZWNuYXBw
  3096  cy5jboIUKi5nb29nbGVjb21tZXJjZS5jb22CESouZ29vZ2xldmlkZW8uY29tggwq
  3097  LmdzdGF0aWMuY26CDSouZ3N0YXRpYy5jb22CEiouZ3N0YXRpY2NuYXBwcy5jboIK
  3098  Ki5ndnQxLmNvbYIKKi5ndnQyLmNvbYIUKi5tZXRyaWMuZ3N0YXRpYy5jb22CDCou
  3099  dXJjaGluLmNvbYIQKi51cmwuZ29vZ2xlLmNvbYITKi53ZWFyLmdrZWNuYXBwcy5j
  3100  boIWKi55b3V0dWJlLW5vY29va2llLmNvbYINKi55b3V0dWJlLmNvbYIWKi55b3V0
  3101  dWJlZWR1Y2F0aW9uLmNvbYIRKi55b3V0dWJla2lkcy5jb22CByoueXQuYmWCCyou
  3102  eXRpbWcuY29tghphbmRyb2lkLmNsaWVudHMuZ29vZ2xlLmNvbYILYW5kcm9pZC5j
  3103  b22CG2RldmVsb3Blci5hbmRyb2lkLmdvb2dsZS5jboIcZGV2ZWxvcGVycy5hbmRy
  3104  b2lkLmdvb2dsZS5jboIEZy5jb4IIZ2dwaHQuY26CDGdrZWNuYXBwcy5jboIGZ29v
  3105  LmdsghRnb29nbGUtYW5hbHl0aWNzLmNvbYIKZ29vZ2xlLmNvbYIPZ29vZ2xlY25h
  3106  cHBzLmNughJnb29nbGVjb21tZXJjZS5jb22CGHNvdXJjZS5hbmRyb2lkLmdvb2ds
  3107  ZS5jboIKdXJjaGluLmNvbYIKd3d3Lmdvby5nbIIIeW91dHUuYmWCC3lvdXR1YmUu
  3108  Y29tghR5b3V0dWJlZWR1Y2F0aW9uLmNvbYIPeW91dHViZWtpZHMuY29tggV5dC5i
  3109  ZTAhBgNVHSAEGjAYMAgGBmeBDAECAjAMBgorBgEEAdZ5AgUDMDMGA1UdHwQsMCow
  3110  KKAmoCSGImh0dHA6Ly9jcmwucGtpLmdvb2cvR1RTMU8xY29yZS5jcmwwEwYKKwYB
  3111  BAHWeQIEAwEB/wQCBQAwDQYJKoZIhvcNAQELBQADggEBAHh9/ozYUGRd+W5akWlM
  3112  4WvX808TK2oUISnagbxCCFZ2trpg2oi03CJf4o4o3Je5Qzzz10s22oQY6gPHAR0B
  3113  QHzrpqAveQw9D5vd8xjgtQ/SAujPzPKNQee5511rS7/EKW9I83ccd5XhhoEyx8A1
  3114  /65RTS+2hKpJKTMkr0yHBPJV7kUW+n/KIef5YaSOA9VYK7hyH0niDpvm9EmoqvWS
  3115  U5xAFAe/Xrrq3sxTuDJPQA8alk6h/ql5Klkw6dL53csiPka/MevDqdifWkzuT/6n
  3116  YK/ePeJzPD17FA9V+N1rcuF3Wk29AZvCOSasdIkIuE82vGr3dfNrsrn9E9lWIbCr
  3117  Qc4=
  3118  -----END CERTIFICATE-----`,
  3119  		},
  3120  	}
  3121  	for _, c := range cases {
  3122  		b.Run(c.name, func(b *testing.B) {
  3123  			pemBlock, _ := pem.Decode([]byte(c.pem))
  3124  			b.ReportAllocs()
  3125  			b.ResetTimer()
  3126  			for i := 0; i < b.N; i++ {
  3127  				_, err := ParseCertificate(pemBlock.Bytes)
  3128  				if err != nil {
  3129  					b.Fatal(err)
  3130  				}
  3131  			}
  3132  		})
  3133  	}
  3134  }
  3135  
  3136  func TestParseCertificateRawEquals(t *testing.T) {
  3137  	p, _ := pem.Decode([]byte(pemCertificate))
  3138  	cert, err := ParseCertificate(p.Bytes)
  3139  	if err != nil {
  3140  		t.Fatalf("failed to parse certificate: %s", err)
  3141  	}
  3142  	if !bytes.Equal(p.Bytes, cert.Raw) {
  3143  		t.Fatalf("unexpected Certificate.Raw\ngot: %x\nwant: %x\n", cert.Raw, p.Bytes)
  3144  	}
  3145  	fmt.Printf("in:  %x\nout: %x\n", p.Bytes, cert.Raw)
  3146  }
  3147  
  3148  // mismatchingSigAlgIDPEM contains a certificate where the Certificate
  3149  // signatureAlgorithm and the TBSCertificate signature contain
  3150  // mismatching OIDs
  3151  const mismatchingSigAlgIDPEM = `-----BEGIN CERTIFICATE-----
  3152  MIIBBzCBrqADAgECAgEAMAoGCCqGSM49BAMCMAAwIhgPMDAwMTAxMDEwMDAwMDBa
  3153  GA8wMDAxMDEwMTAwMDAwMFowADBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABOqV
  3154  EDuVXxwZgIU3+dOwv1SsMu0xuV48hf7xmK8n7sAMYgllB+96DnPqBeboJj4snYnx
  3155  0AcE0PDVQ1l4Z3YXsQWjFTATMBEGA1UdEQEB/wQHMAWCA2FzZDAKBggqhkjOPQQD
  3156  AwNIADBFAiBi1jz/T2HT5nAfrD7zsgR+68qh7Erc6Q4qlxYBOgKG4QIhAOtjIn+Q
  3157  tA+bq+55P3ntxTOVRq0nv1mwnkjwt9cQR9Fn
  3158  -----END CERTIFICATE-----`
  3159  
  3160  // mismatchingSigAlgParamPEM contains a certificate where the Certificate
  3161  // signatureAlgorithm and the TBSCertificate signature contain
  3162  // mismatching parameters
  3163  const mismatchingSigAlgParamPEM = `-----BEGIN CERTIFICATE-----
  3164  MIIBCTCBrqADAgECAgEAMAoGCCqGSM49BAMCMAAwIhgPMDAwMTAxMDEwMDAwMDBa
  3165  GA8wMDAxMDEwMTAwMDAwMFowADBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABOqV
  3166  EDuVXxwZgIU3+dOwv1SsMu0xuV48hf7xmK8n7sAMYgllB+96DnPqBeboJj4snYnx
  3167  0AcE0PDVQ1l4Z3YXsQWjFTATMBEGA1UdEQEB/wQHMAWCA2FzZDAMBggqhkjOPQQD
  3168  AgUAA0gAMEUCIGLWPP9PYdPmcB+sPvOyBH7ryqHsStzpDiqXFgE6AobhAiEA62Mi
  3169  f5C0D5ur7nk/ee3FM5VGrSe/WbCeSPC31xBH0Wc=
  3170  -----END CERTIFICATE-----`
  3171  
  3172  func TestSigAlgMismatch(t *testing.T) {
  3173  	for _, certPEM := range []string{mismatchingSigAlgIDPEM, mismatchingSigAlgParamPEM} {
  3174  		b, _ := pem.Decode([]byte(certPEM))
  3175  		if b == nil {
  3176  			t.Fatalf("couldn't decode test certificate")
  3177  		}
  3178  		_, err := ParseCertificate(b.Bytes)
  3179  		if err == nil {
  3180  			t.Fatalf("expected ParseCertificate to fail")
  3181  		}
  3182  		expected := "x509: inner and outer signature algorithm identifiers don't match"
  3183  		if err.Error() != expected {
  3184  			t.Errorf("unexpected error from ParseCertificate: got %q, want %q", err.Error(), expected)
  3185  		}
  3186  	}
  3187  }
  3188  
  3189  const optionalAuthKeyIDPEM = `-----BEGIN CERTIFICATE-----
  3190  MIIFEjCCBHugAwIBAgICAQwwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1Zh
  3191  bGlDZXJ0IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIElu
  3192  Yy4xNTAzBgNVBAsTLF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AxMYaHR0cDovL3d3dy52YWxpY2VydC5j
  3208  b20vMSAwHgYJKoZIhvcNAQkBFhFpbmZvQHZhbGljZXJ0LmNvbYIBATAPBgNVHRMB
  3209  Af8EBTADAQH/MDkGCCsGAQUFBwEBBC0wKzApBggrBgEFBQcwAYYdaHR0cDovL29j
  3210  c3Auc3RhcmZpZWxkdGVjaC5jb20wSgYDVR0fBEMwQTA/oD2gO4Y5aHR0cDovL2Nl
  3211  cnRpZmljYXRlcy5zdGFyZmllbGR0ZWNoLmNvbS9yZXBvc2l0b3J5L3Jvb3QuY3Js
  3212  MFEGA1UdIARKMEgwRgYEVR0gADA+MDwGCCsGAQUFBwIBFjBodHRwOi8vY2VydGlm
  3213  aWNhdGVzLnN0YXJmaWVsZHRlY2guY29tL3JlcG9zaXRvcnkwDgYDVR0PAQH/BAQD
  3214  AgEGMA0GCSqGSIb3DQEBBQUAA4GBAKVi8afCXSWlcD284ipxs33kDTcdVWptobCr
  3215  mADkhWBKIMuh8D1195TaQ39oXCUIuNJ9MxB73HZn8bjhU3zhxoNbKXuNSm8uf0So
  3216  GkVrMgfHeMpkksK0hAzc3S1fTbvdiuo43NlmouxBulVtWmQ9twPMHOKRUJ7jCUSV
  3217  FxdzPcwl
  3218  -----END CERTIFICATE-----`
  3219  
  3220  func TestAuthKeyIdOptional(t *testing.T) {
  3221  	b, _ := pem.Decode([]byte(optionalAuthKeyIDPEM))
  3222  	if b == nil {
  3223  		t.Fatalf("couldn't decode test certificate")
  3224  	}
  3225  	_, err := ParseCertificate(b.Bytes)
  3226  	if err != nil {
  3227  		t.Fatalf("ParseCertificate to failed to parse certificate with optional authority key identifier fields: %s", err)
  3228  	}
  3229  }
  3230  
  3231  // 添加国米相关测试案例
  3232  func TestX509(t *testing.T) {
  3233  	// 生成sm2密钥对
  3234  	// priv, err := sm2.GenerateKey(nil)
  3235  	priv, err := sm2.GenerateKey(rand.Reader)
  3236  	if err != nil {
  3237  		t.Fatal(err)
  3238  	}
  3239  	// 生成私钥文件字节流
  3240  	privPem, err := WritePrivateKeyToPem(priv, nil)
  3241  	if err != nil {
  3242  		t.Fatal(err)
  3243  	}
  3244  	pubKey, _ := priv.Public().(*sm2.PublicKey)
  3245  	// 生成公钥文件字节流
  3246  	pubkeyPem, _ := WritePublicKeyToPem(pubKey)
  3247  	// 读取私钥
  3248  	privKey, err := ReadPrivateKeyFromPem(privPem, nil)
  3249  	if err != nil {
  3250  		t.Fatal(err)
  3251  	}
  3252  	// 读取公钥
  3253  	pkTmp, err := ReadPublicKeyFromPem(pubkeyPem)
  3254  	if err != nil {
  3255  		t.Fatal(err)
  3256  	}
  3257  	pubKey = pkTmp.(*sm2.PublicKey)
  3258  	// 定义证书申请模板
  3259  	templateReq := CertificateRequest{
  3260  		Subject: pkix.Name{
  3261  			CommonName:   "pangzi.com",
  3262  			Organization: []string{"PANGZIXIEHUI"},
  3263  		},
  3264  		//		SignatureAlgorithm: ECDSAWithSHA256,
  3265  		SignatureAlgorithm: SM2WithSM3,
  3266  	}
  3267  	// 创建证书申请pem字节流并签名
  3268  	reqPem, err := CreateCertificateRequestToPem(&templateReq, privKey)
  3269  	if err != nil {
  3270  		t.Fatal(err)
  3271  	}
  3272  	// 从pem读取证书申请
  3273  	req, err := ReadCertificateRequestFromPem(reqPem)
  3274  	if err != nil {
  3275  		t.Fatal(err)
  3276  	}
  3277  	// 检查证书申请的签名
  3278  	err = req.CheckSignature()
  3279  	if err != nil {
  3280  		t.Fatalf("Request CheckSignature error:%v", err)
  3281  	} else {
  3282  		fmt.Printf("CheckSignature ok\n")
  3283  	}
  3284  	testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth}
  3285  	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
  3286  	extraExtensionData := []byte("extra extension")
  3287  	commonName := "pangzi.com"
  3288  	// 定义证书模板
  3289  	//goland:noinspection GoDeprecation
  3290  	template := Certificate{
  3291  		// SerialNumber is negative to ensure that negative
  3292  		// values are parsed. This is due to the prevalence of
  3293  		// buggy code that produces certificates with negative
  3294  		// serial numbers.
  3295  		SerialNumber: big.NewInt(-1),
  3296  		Subject: pkix.Name{
  3297  			CommonName:   commonName,
  3298  			Organization: []string{"PANGZIXIEHUI"},
  3299  			Country:      []string{"China"},
  3300  			ExtraNames: []pkix.AttributeTypeAndValue{
  3301  				{
  3302  					Type:  []int{2, 5, 4, 42},
  3303  					Value: "Gopher",
  3304  				},
  3305  				// This should override the Country, above.
  3306  				{
  3307  					Type:  []int{2, 5, 4, 6},
  3308  					Value: "NL",
  3309  				},
  3310  			},
  3311  		},
  3312  		NotBefore: time.Now(),
  3313  		NotAfter:  time.Date(2032, time.December, 31, 23, 59, 59, 1, time.UTC),
  3314  
  3315  		//		SignatureAlgorithm: ECDSAWithSHA256,
  3316  		SignatureAlgorithm: SM2WithSM3,
  3317  
  3318  		SubjectKeyId: []byte{1, 2, 3, 4},
  3319  		KeyUsage:     KeyUsageCertSign,
  3320  
  3321  		ExtKeyUsage:        testExtKeyUsage,
  3322  		UnknownExtKeyUsage: testUnknownExtKeyUsage,
  3323  
  3324  		BasicConstraintsValid: true,
  3325  		IsCA:                  true,
  3326  
  3327  		OCSPServer:            []string{"http://ocsp.pangzi.com"},
  3328  		IssuingCertificateURL: []string{"http://crt.pangzi.com/ca1.crt"},
  3329  
  3330  		DNSNames:       []string{"pangzi.com"},
  3331  		EmailAddresses: []string{"gopher@golang.org"},
  3332  		IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
  3333  
  3334  		PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
  3335  		PermittedDNSDomains: []string{".pangzi.com", "pangzi.com"},
  3336  
  3337  		CRLDistributionPoints: []string{"http://crl1.pangzi.com/ca1.crl", "http://crl2.pangzi.com/ca1.crl"},
  3338  
  3339  		ExtraExtensions: []pkix.Extension{
  3340  			{
  3341  				Id:    []int{1, 2, 3, 4},
  3342  				Value: extraExtensionData,
  3343  			},
  3344  			// This extension should override the SubjectKeyId, above.
  3345  			{
  3346  				Id:       oidExtensionSubjectKeyId,
  3347  				Critical: false,
  3348  				Value:    []byte{0x04, 0x04, 4, 3, 2, 1},
  3349  			},
  3350  		},
  3351  	}
  3352  	// pubKey, _ = priv.Public().(*sm2.PublicKey)
  3353  	// 创建证书pem字节流
  3354  	certpem, err := CreateCertificateToPem(&template, &template, pubKey, privKey)
  3355  	if err != nil {
  3356  		t.Fatal("failed to create cert file")
  3357  	}
  3358  	// 读取证书pem
  3359  	cert, err := ReadCertificateFromPem(certpem)
  3360  	if err != nil {
  3361  		t.Fatal("failed to read cert file")
  3362  	}
  3363  	// 检查证书签名
  3364  	err = cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature)
  3365  	if err != nil {
  3366  		t.Fatal(err)
  3367  	} else {
  3368  		fmt.Printf("CheckSignature ok\n")
  3369  	}
  3370  }
  3371  
  3372  func TestX509WithFile(t *testing.T) {
  3373  	// 生成sm2密钥对
  3374  	priv, err := sm2.GenerateKey(rand.Reader)
  3375  	if err != nil {
  3376  		t.Fatal(err)
  3377  	}
  3378  	pub := &priv.PublicKey
  3379  	// 生成私钥pem文件
  3380  	_, err = WritePrivateKeytoPemFile("testdata/pri_key.pem", priv, nil)
  3381  	if err != nil {
  3382  		t.Fatal(err)
  3383  	}
  3384  	// 生成公钥pem文件
  3385  	_, err = WritePublicKeytoPemFile("testdata/pub_key.pem", pub)
  3386  	if err != nil {
  3387  		t.Fatal(err)
  3388  	}
  3389  	// 从pem文件读取私钥
  3390  	privKey, err := ReadPrivateKeyFromPemFile("testdata/pri_key.pem", nil)
  3391  	if err != nil {
  3392  		t.Fatal(err)
  3393  	}
  3394  	fmt.Printf("读取到sm2私钥 : %v\n", privKey)
  3395  	// 从pem文件读取公钥
  3396  	pubKey, err := ReadPublicKeyFromPemFile("testdata/pub_key.pem")
  3397  	if err != nil {
  3398  		t.Fatal(err)
  3399  	}
  3400  	fmt.Printf("读取到sm2公钥 : %v\n", pubKey)
  3401  	fmt.Println("测试sm2私钥与公钥文件读写成功")
  3402  
  3403  	// 定义证书申请模板
  3404  	templateReq := CertificateRequest{
  3405  		Subject: pkix.Name{
  3406  			// Subject行的CN
  3407  			CommonName: "test.pangzi.com",
  3408  			// Subject行的O
  3409  			Organization: []string{"PANGZIXIEHUI", "dapangzixiehui"},
  3410  		},
  3411  		SignatureAlgorithm: SM2WithSM3,
  3412  	}
  3413  	// 创建证书申请pem字节流并签名
  3414  	_, err = CreateCertificateRequestToPemFile("testdata/csr.pem", &templateReq, privKey)
  3415  	if err != nil {
  3416  		t.Fatal(err)
  3417  	}
  3418  	// 创建证书申请csr文件后,可以用`openssl req -noout -text -in testdata/csr.pem`命令查看文件内容
  3419  
  3420  	// 模拟ca检查证书申请
  3421  	// 从pem读取证书申请
  3422  	req, err := ReadCertificateRequestFromPemFile("testdata/csr.pem")
  3423  	if err != nil {
  3424  		t.Fatal(err)
  3425  	}
  3426  	// 检查证书申请的签名
  3427  	err = req.CheckSignature()
  3428  	if err != nil {
  3429  		t.Fatalf("证书申请验签失败 : %v", err)
  3430  	} else {
  3431  		fmt.Printf("证书申请验签成功\n")
  3432  	}
  3433  	fmt.Println("测试证书申请文件读写与验签成功")
  3434  
  3435  	// 模拟ca发布证书
  3436  	testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth}
  3437  	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
  3438  	extraExtensionData := []byte("extra extension")
  3439  	commonName := "test.pangzi.com"
  3440  	// 定义证书模板
  3441  	//goland:noinspection GoDeprecation
  3442  	template := Certificate{
  3443  		SerialNumber: big.NewInt(-1),
  3444  		Subject: pkix.Name{
  3445  			// Subject行的CN
  3446  			CommonName: commonName,
  3447  			// Subject行的O
  3448  			Organization: []string{"PANGZIXIEHUI", "dapangzixiehui"},
  3449  			Country:      []string{"China"},
  3450  			// CN之后的附加名称
  3451  			ExtraNames: []pkix.AttributeTypeAndValue{
  3452  				{
  3453  					// GN
  3454  					Type:  []int{2, 5, 4, 42},
  3455  					Value: "Gopher",
  3456  				},
  3457  				// This should override the Country, above.
  3458  				{
  3459  					// C
  3460  					Type:  []int{2, 5, 4, 6},
  3461  					Value: "NL",
  3462  				},
  3463  			},
  3464  		},
  3465  		NotBefore: time.Now(),
  3466  		NotAfter:  time.Date(2032, time.December, 31, 23, 59, 59, 1, time.UTC),
  3467  
  3468  		SignatureAlgorithm: SM2WithSM3,
  3469  
  3470  		SubjectKeyId: []byte{1, 2, 3, 4},
  3471  		KeyUsage:     KeyUsageCertSign,
  3472  
  3473  		ExtKeyUsage:        testExtKeyUsage,
  3474  		UnknownExtKeyUsage: testUnknownExtKeyUsage,
  3475  
  3476  		BasicConstraintsValid: true,
  3477  		IsCA:                  true,
  3478  
  3479  		OCSPServer:            []string{"http://ocsp.pangzi.com"},
  3480  		IssuingCertificateURL: []string{"http://crt.pangzi.com/ca1.crt"},
  3481  
  3482  		DNSNames:       []string{"test.pangzi.com"},
  3483  		EmailAddresses: []string{"gopher@golang.org"},
  3484  		IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
  3485  
  3486  		PolicyIdentifiers:   []asn1.ObjectIdentifier{[]int{1, 2, 3}},
  3487  		PermittedDNSDomains: []string{".pangzi.com", "pangzi.com"},
  3488  
  3489  		CRLDistributionPoints: []string{"http://crl1.pangzi.com/ca1.crl", "http://crl2.pangzi.com/ca1.crl"},
  3490  
  3491  		ExtraExtensions: []pkix.Extension{
  3492  			{
  3493  				Id:    []int{1, 2, 3, 4},
  3494  				Value: extraExtensionData,
  3495  			},
  3496  			// This extension should override the SubjectKeyId, above.
  3497  			{
  3498  				Id:       oidExtensionSubjectKeyId,
  3499  				Critical: false,
  3500  				Value:    []byte{0x04, 0x04, 4, 3, 2, 1},
  3501  			},
  3502  		},
  3503  	}
  3504  	// 创建证书pem文件
  3505  	_, err = CreateCertificateToPemFile("testdata/cert.cer", &template, &template, pubKey, privKey)
  3506  	if err != nil {
  3507  		t.Fatal("failed to create cert file")
  3508  	}
  3509  	// 可以使用命令`openssl x509 -noout -text -in testdata/cert.cer`查看生成的x509证书
  3510  	// 读取证书pem文件
  3511  	cert, err := ReadCertificateFromPemFile("testdata/cert.cer")
  3512  	if err != nil {
  3513  		t.Fatal("failed to read cert file")
  3514  	}
  3515  	// 检查证书签名
  3516  	err = cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature)
  3517  	if err != nil {
  3518  		t.Fatal(err)
  3519  	} else {
  3520  		fmt.Printf("CheckSignature ok\n")
  3521  	}
  3522  	fmt.Println("测试证书文件读写与验签成功")
  3523  }
  3524  
  3525  func TestCreateCertFromCA(t *testing.T) {
  3526  	caPriv, caCert, err := createCACert()
  3527  	if err != nil {
  3528  		t.Fatal(err)
  3529  	}
  3530  	fmt.Println("生成CA密钥对与CA证书成功")
  3531  
  3532  	err = createSignCert(caPriv, caCert)
  3533  	if err != nil {
  3534  		t.Fatal(err)
  3535  	}
  3536  	fmt.Println("生成sm2_sign密钥对并模拟CA为其颁发证书成功")
  3537  
  3538  	err = createEncCert(caPriv, caCert)
  3539  	if err != nil {
  3540  		t.Fatal(err)
  3541  	}
  3542  	fmt.Println("生成sm2_enc密钥对并模拟CA为其颁发证书成功")
  3543  
  3544  	err = createAuthCert(caPriv, caCert)
  3545  	if err != nil {
  3546  		t.Fatal(err)
  3547  	}
  3548  	fmt.Println("生成sm2_auth密钥对并模拟CA为其颁发证书成功")
  3549  }
  3550  
  3551  // 创建ca证书,并返回ca私钥与ca证书
  3552  func createCACert() (*sm2.PrivateKey, *Certificate, error) {
  3553  	certType := "sm2_ca"
  3554  	// 生成sm2密钥对
  3555  	privKey, pubKey, err := createKeys(certType)
  3556  	if err != nil {
  3557  		return nil, nil, err
  3558  	}
  3559  	userKeyUsage := KeyUsageCertSign + KeyUsageCRLSign
  3560  	//goland:noinspection GoDeprecation
  3561  	userExtKeyUsage := []ExtKeyUsage{
  3562  		// ExtKeyUsageAny,
  3563  		// ExtKeyUsageServerAuth,
  3564  		// ExtKeyUsageClientAuth,
  3565  		// ExtKeyUsageCodeSigning,
  3566  		// ExtKeyUsageEmailProtection,
  3567  		// ExtKeyUsageIPSECEndSystem,
  3568  		// ExtKeyUsageIPSECTunnel,
  3569  		// ExtKeyUsageIPSECUser,
  3570  		// ExtKeyUsageTimeStamping,
  3571  		// ExtKeyUsageOCSPSigning,
  3572  		// ExtKeyUsageMicrosoftServerGatedCrypto,
  3573  		// ExtKeyUsageNetscapeServerGatedCrypto,
  3574  	}
  3575  	// // 使用公钥生成ski
  3576  	// sid := CreateEllipticSKI(pubKey.Curve, pubKey.X, pubKey.Y)
  3577  	// aid := sid
  3578  	// 创建证书,ca证书自签名
  3579  	cert, err := createCertSignSelf("ca.test.com", "catest", "CN", "Anhui Hefei", true, true, userKeyUsage, userExtKeyUsage, nil, certType, pubKey, privKey)
  3580  	if err != nil {
  3581  		return nil, nil, err
  3582  	}
  3583  	// 检查证书签名,因为是ca证书自签名,所以使用本证书自验
  3584  	err = cert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature)
  3585  	if err != nil {
  3586  		return nil, nil, err
  3587  	} else {
  3588  		fmt.Printf("CheckSignature ok\n")
  3589  	}
  3590  	return privKey, cert, nil
  3591  }
  3592  
  3593  func createSignCert(caPriv *sm2.PrivateKey, caCert *Certificate) error {
  3594  	certType := "sm2_sign"
  3595  	// 生成sm2密钥对
  3596  	_, pubKey, err := createKeys(certType)
  3597  	if err != nil {
  3598  		return err
  3599  	}
  3600  	userKeyUsage := KeyUsageDigitalSignature + KeyUsageContentCommitment
  3601  	userExtKeyUsage := []ExtKeyUsage{
  3602  		// ExtKeyUsageAny,
  3603  		ExtKeyUsageServerAuth,
  3604  		ExtKeyUsageClientAuth,
  3605  		// ExtKeyUsageCodeSigning,
  3606  		// ExtKeyUsageEmailProtection,
  3607  		// ExtKeyUsageIPSECEndSystem,
  3608  		// ExtKeyUsageIPSECTunnel,
  3609  		// ExtKeyUsageIPSECUser,
  3610  		// ExtKeyUsageTimeStamping,
  3611  		// ExtKeyUsageOCSPSigning,
  3612  		// ExtKeyUsageMicrosoftServerGatedCrypto,
  3613  		// ExtKeyUsageNetscapeServerGatedCrypto,
  3614  	}
  3615  	// sid := []byte{0, 0, 0, 2}
  3616  	// aid := caCert.SubjectKeyId
  3617  	// 模拟CA颁发证书,注意此时ca证书是父证书
  3618  	cert, err := createCertSignParent("server.test.com", "server_test", "CN", "Anhui Hefei", false, false, userKeyUsage, userExtKeyUsage, nil, certType, pubKey, caPriv, caCert)
  3619  	if err != nil {
  3620  		return err
  3621  	}
  3622  	// 使用父证书caCert验签
  3623  	err = caCert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature)
  3624  	if err != nil {
  3625  		return err
  3626  	} else {
  3627  		fmt.Printf("CheckSignature ok\n")
  3628  	}
  3629  	return nil
  3630  }
  3631  
  3632  func createEncCert(caPriv *sm2.PrivateKey, caCert *Certificate) error {
  3633  	certType := "sm2_enc"
  3634  	// 生成sm2密钥对
  3635  	_, pubKey, err := createKeys(certType)
  3636  	if err != nil {
  3637  		return err
  3638  	}
  3639  	userKeyUsage := KeyUsageKeyEncipherment + KeyUsageDataEncipherment
  3640  	//goland:noinspection GoDeprecation
  3641  	userExtKeyUsage := []ExtKeyUsage{
  3642  		// ExtKeyUsageAny,
  3643  		// ExtKeyUsageServerAuth,
  3644  		// ExtKeyUsageClientAuth,
  3645  		// ExtKeyUsageCodeSigning,
  3646  		// ExtKeyUsageEmailProtection,
  3647  		// ExtKeyUsageIPSECEndSystem,
  3648  		// ExtKeyUsageIPSECTunnel,
  3649  		// ExtKeyUsageIPSECUser,
  3650  		// ExtKeyUsageTimeStamping,
  3651  		// ExtKeyUsageOCSPSigning,
  3652  		// ExtKeyUsageMicrosoftServerGatedCrypto,
  3653  		// ExtKeyUsageNetscapeServerGatedCrypto,
  3654  	}
  3655  	// sid := []byte{0, 0, 0, 3}
  3656  	// aid := caCert.SubjectKeyId
  3657  	// 模拟CA颁发证书,注意此时ca证书是父证书
  3658  	cert, err := createCertSignParent("server.test.com", "server_test", "CN", "Anhui Hefei", false, false, userKeyUsage, userExtKeyUsage, nil, certType, pubKey, caPriv, caCert)
  3659  	if err != nil {
  3660  		return err
  3661  	}
  3662  	// 使用父证书caCert验签
  3663  	err = caCert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature)
  3664  	if err != nil {
  3665  		return err
  3666  	} else {
  3667  		fmt.Printf("CheckSignature ok\n")
  3668  	}
  3669  	return nil
  3670  }
  3671  
  3672  func createAuthCert(caPriv *sm2.PrivateKey, caCert *Certificate) error {
  3673  	certType := "sm2_auth"
  3674  	// 生成sm2密钥对
  3675  	_, pubKey, err := createKeys(certType)
  3676  	if err != nil {
  3677  		return err
  3678  	}
  3679  	userKeyUsage := KeyUsageDigitalSignature + KeyUsageContentCommitment
  3680  	userExtKeyUsage := []ExtKeyUsage{
  3681  		// ExtKeyUsageAny,
  3682  		ExtKeyUsageServerAuth,
  3683  		ExtKeyUsageClientAuth,
  3684  		// ExtKeyUsageCodeSigning,
  3685  		// ExtKeyUsageEmailProtection,
  3686  		// ExtKeyUsageIPSECEndSystem,
  3687  		// ExtKeyUsageIPSECTunnel,
  3688  		// ExtKeyUsageIPSECUser,
  3689  		// ExtKeyUsageTimeStamping,
  3690  		// ExtKeyUsageOCSPSigning,
  3691  		// ExtKeyUsageMicrosoftServerGatedCrypto,
  3692  		// ExtKeyUsageNetscapeServerGatedCrypto,
  3693  	}
  3694  	// sid := []byte{0, 0, 0, 4}
  3695  	// aid := caCert.SubjectKeyId
  3696  	// 模拟CA颁发证书,注意此时ca证书是父证书
  3697  	cert, err := createCertSignParent("client.test.com", "client_test", "CN", "Anhui Hefei", false, false, userKeyUsage, userExtKeyUsage, nil, certType, pubKey, caPriv, caCert)
  3698  	if err != nil {
  3699  		return err
  3700  	}
  3701  	// 使用父证书caCert验签
  3702  	err = caCert.CheckSignature(cert.SignatureAlgorithm, cert.RawTBSCertificate, cert.Signature)
  3703  	if err != nil {
  3704  		return err
  3705  	} else {
  3706  		fmt.Printf("CheckSignature ok\n")
  3707  	}
  3708  	return nil
  3709  }
  3710  
  3711  func createKeys(certType string) (*sm2.PrivateKey, *sm2.PublicKey, error) {
  3712  	// 生成sm2密钥对
  3713  	priv, err := sm2.GenerateKey(rand.Reader)
  3714  	if err != nil {
  3715  		return nil, nil, err
  3716  	}
  3717  	pub := &priv.PublicKey
  3718  	// 生成私钥pem文件
  3719  	_, err = WritePrivateKeytoPemFile("testdata/"+certType+"_key.pem", priv, nil)
  3720  	if err != nil {
  3721  		return nil, nil, err
  3722  	}
  3723  	// 生成公钥pem文件
  3724  	_, err = WritePublicKeytoPemFile("testdata/"+certType+"_pubkey.pem", pub)
  3725  	if err != nil {
  3726  		return nil, nil, err
  3727  	}
  3728  	// 从pem文件读取私钥
  3729  	privKey, err := ReadPrivateKeyFromPemFile("testdata/"+certType+"_key.pem", nil)
  3730  	if err != nil {
  3731  		return nil, nil, err
  3732  	}
  3733  	// 从pem文件读取公钥
  3734  	pubKey, err := ReadPublicKeyFromPemFile("testdata/" + certType + "_pubkey.pem")
  3735  	if err != nil {
  3736  		return nil, nil, err
  3737  	}
  3738  	return privKey.(*sm2.PrivateKey), pubKey.(*sm2.PublicKey), nil
  3739  }
  3740  
  3741  func createCertSignSelf(cn string, o string, c string, st string, bcs bool, isca bool,
  3742  	ku KeyUsage, ekus []ExtKeyUsage, uekus []asn1.ObjectIdentifier,
  3743  	certType string, pubKey *sm2.PublicKey, privKey *sm2.PrivateKey) (*Certificate, error) {
  3744  	// 获取ski
  3745  	ski := CreateEllipticSKI(pubKey.Curve, pubKey.X, pubKey.Y)
  3746  	// 定义证书模板
  3747  	template := createTemplate(cn, o, c, st, bcs, isca, ski, ku, ekus, uekus, certType, pubKey, privKey)
  3748  	// 创建自签名证书pem文件
  3749  	_, err := CreateCertificateToPemFile("testdata/"+certType+"_cert.cer", template, template, pubKey, privKey)
  3750  	if err != nil {
  3751  		return nil, err
  3752  	}
  3753  	// 可以使用命令`openssl x509 -noout -text -in testdata/user_cert.cer`查看生成的x509证书
  3754  	// 读取证书pem文件
  3755  	cert, err := ReadCertificateFromPemFile("testdata/" + certType + "_cert.cer")
  3756  	if err != nil {
  3757  		return nil, err
  3758  	}
  3759  	return cert, nil
  3760  }
  3761  
  3762  func createCertSignParent(cn string, o string, c string, st string, bcs bool, isca bool,
  3763  	ku KeyUsage, ekus []ExtKeyUsage, uekus []asn1.ObjectIdentifier,
  3764  	certType string, pubKey *sm2.PublicKey, privKey *sm2.PrivateKey, parent *Certificate) (*Certificate, error) {
  3765  	// 获取ski
  3766  	ski := CreateEllipticSKI(pubKey.Curve, pubKey.X, pubKey.Y)
  3767  	// 定义证书模板
  3768  	template := createTemplate(cn, o, c, st, bcs, isca, ski, ku, ekus, uekus, certType, pubKey, privKey)
  3769  	// 创建自签名证书pem文件
  3770  	_, err := CreateCertificateToPemFile("testdata/"+certType+"_cert.cer", template, parent, pubKey, privKey)
  3771  	if err != nil {
  3772  		return nil, err
  3773  	}
  3774  	// 可以使用命令`openssl x509 -noout -text -in testdata/user_cert.cer`查看生成的x509证书
  3775  	// 读取证书pem文件
  3776  	cert, err := ReadCertificateFromPemFile("testdata/" + certType + "_cert.cer")
  3777  	if err != nil {
  3778  		return nil, err
  3779  	}
  3780  	return cert, nil
  3781  }
  3782  
  3783  //goland:noinspection GoDeprecation
  3784  func createTemplate(cn string, o string, c string, st string, bcs bool, isca bool, sId []byte,
  3785  	ku KeyUsage, ekus []ExtKeyUsage, uekus []asn1.ObjectIdentifier,
  3786  	certType string, pubKey *sm2.PublicKey, privKey *sm2.PrivateKey) *Certificate {
  3787  	// 定义证书模板
  3788  	template := &Certificate{
  3789  		// 证书序列号
  3790  		SerialNumber: GetRandBigInt(),
  3791  		// 证书拥有者
  3792  		Subject: pkix.Name{
  3793  			// CN 证书拥有者通用名, 一般是域名
  3794  			CommonName: cn,
  3795  			// O 证书拥有者组织机构
  3796  			Organization: []string{o},
  3797  			// C 证书拥有者所在国家
  3798  			Country: []string{"China"},
  3799  			// 附加名称
  3800  			ExtraNames: []pkix.AttributeTypeAndValue{
  3801  				// This should override the Country, above.
  3802  				{
  3803  					// C 会覆盖Country
  3804  					Type:  []int{2, 5, 4, 6},
  3805  					Value: c,
  3806  				},
  3807  				{
  3808  					// ST 省市
  3809  					Type:  []int{2, 5, 4, 8},
  3810  					Value: st,
  3811  				},
  3812  			},
  3813  		},
  3814  		// 证书有效期 十年
  3815  		// NotBefore:             time.Now(),
  3816  		// NotAfter:              time.Date(2032, time.December, 31, 23, 59, 59, 1, time.UTC),
  3817  		NotBefore: time.Now().Add(-1 * time.Hour),
  3818  		NotAfter:  time.Now().Add(87600 * time.Hour),
  3819  		// 证书签名算法
  3820  		SignatureAlgorithm:    SM2WithSM3,
  3821  		BasicConstraintsValid: bcs,
  3822  		IsCA:                  isca,
  3823  		SubjectKeyId:          sId,
  3824  		// AuthorityKeyId:        aId,
  3825  		KeyUsage:           ku,
  3826  		ExtKeyUsage:        ekus,
  3827  		UnknownExtKeyUsage: uekus,
  3828  		// x509 v3 版本不再使用 CommonName 而是使用这里的SAN扩展信息
  3829  		DNSNames:       []string{cn, "test.example.com"},
  3830  		EmailAddresses: []string{"gopher@golang.org"},
  3831  		IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
  3832  		URIs:           []*url.URL{parseURI("https://foo.com/wibble#foo")},
  3833  	}
  3834  	return template
  3835  
  3836  }