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