github.com/emmansun/gmsm@v0.29.1/smx509/x509_test.go (about)

     1  package smx509
     2  
     3  import (
     4  	"bytes"
     5  	"crypto"
     6  	"crypto/dsa"
     7  	"crypto/ecdsa"
     8  	"crypto/ed25519"
     9  	"crypto/elliptic"
    10  	"crypto/rand"
    11  	"crypto/rsa"
    12  	"crypto/x509"
    13  	"crypto/x509/pkix"
    14  	"encoding/asn1"
    15  	"encoding/base64"
    16  	"encoding/hex"
    17  	"encoding/pem"
    18  	"io"
    19  	"math/big"
    20  	"net"
    21  	"net/url"
    22  	"reflect"
    23  	"runtime"
    24  	"strings"
    25  	"testing"
    26  	"time"
    27  
    28  	"github.com/emmansun/gmsm/sm2"
    29  )
    30  
    31  func TestMarshalInvalidPublicKey(t *testing.T) {
    32  	_, err := MarshalPKIXPublicKey(&ecdsa.PublicKey{})
    33  	if err == nil {
    34  		t.Errorf("expected error, got MarshalPKIXPublicKey success")
    35  	}
    36  	_, err = MarshalPKIXPublicKey(&ecdsa.PublicKey{
    37  		Curve: elliptic.P256(),
    38  		X:     big.NewInt(1), Y: big.NewInt(2),
    39  	})
    40  	if err == nil {
    41  		t.Errorf("expected error, got MarshalPKIXPublicKey success")
    42  	}
    43  }
    44  
    45  func testParsePKIXPublicKey(t *testing.T, pemBytes string) (pub any) {
    46  	block, _ := pem.Decode([]byte(pemBytes))
    47  	pub, err := ParsePKIXPublicKey(block.Bytes)
    48  	if err != nil {
    49  		t.Fatalf("Failed to parse public key: %s", err)
    50  	}
    51  
    52  	pubBytes2, err := MarshalPKIXPublicKey(pub)
    53  	if err != nil {
    54  		t.Errorf("Failed to marshal public key for the second time: %s", err)
    55  		return
    56  	}
    57  	if !bytes.Equal(pubBytes2, block.Bytes) {
    58  		t.Errorf("Reserialization of public key didn't match. got %x, want %x", pubBytes2, block.Bytes)
    59  	}
    60  	return
    61  }
    62  
    63  func TestParsePKIXPublicKey(t *testing.T) {
    64  	t.Run("RSA", func(t *testing.T) {
    65  		pub := testParsePKIXPublicKey(t, pemPublicKey)
    66  		_, ok := pub.(*rsa.PublicKey)
    67  		if !ok {
    68  			t.Errorf("Value returned from ParsePKIXPublicKey was not an RSA public key")
    69  		}
    70  	})
    71  	t.Run("Ed25519", func(t *testing.T) {
    72  		pub := testParsePKIXPublicKey(t, pemEd25519Key)
    73  		_, ok := pub.(ed25519.PublicKey)
    74  		if !ok {
    75  			t.Errorf("Value returned from ParsePKIXPublicKey was not an Ed25519 public key")
    76  		}
    77  	})
    78  }
    79  
    80  var pemPublicKey = `-----BEGIN PUBLIC KEY-----
    81  MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3VoPN9PKUjKFLMwOge6+
    82  wnDi8sbETGIx2FKXGgqtAKpzmem53kRGEQg8WeqRmp12wgp74TGpkEXsGae7RS1k
    83  enJCnma4fii+noGH7R0qKgHvPrI2Bwa9hzsH8tHxpyM3qrXslOmD45EH9SxIDUBJ
    84  FehNdaPbLP1gFyahKMsdfxFJLUvbUycuZSJ2ZnIgeVxwm4qbSvZInL9Iu4FzuPtg
    85  fINKcbbovy1qq4KvPIrXzhbY3PWDc6btxCf3SE0JdE1MCPThntB62/bLMSQ7xdDR
    86  FF53oIpvxe/SCOymfWq/LW849Ytv3Xwod0+wzAP8STXG4HSELS4UedPYeHJJJYcZ
    87  +QIDAQAB
    88  -----END PUBLIC KEY-----
    89  `
    90  
    91  var pemPrivateKey = testingKey(`
    92  -----BEGIN RSA TESTING KEY-----
    93  MIICXAIBAAKBgQCxoeCUW5KJxNPxMp+KmCxKLc1Zv9Ny+4CFqcUXVUYH69L3mQ7v
    94  IWrJ9GBfcaA7BPQqUlWxWM+OCEQZH1EZNIuqRMNQVuIGCbz5UQ8w6tS0gcgdeGX7
    95  J7jgCQ4RK3F/PuCM38QBLaHx988qG8NMc6VKErBjctCXFHQt14lerd5KpQIDAQAB
    96  AoGAYrf6Hbk+mT5AI33k2Jt1kcweodBP7UkExkPxeuQzRVe0KVJw0EkcFhywKpr1
    97  V5eLMrILWcJnpyHE5slWwtFHBG6a5fLaNtsBBtcAIfqTQ0Vfj5c6SzVaJv0Z5rOd
    98  7gQF6isy3t3w9IF3We9wXQKzT6q5ypPGdm6fciKQ8RnzREkCQQDZwppKATqQ41/R
    99  vhSj90fFifrGE6aVKC1hgSpxGQa4oIdsYYHwMzyhBmWW9Xv/R+fPyr8ZwPxp2c12
   100  33QwOLPLAkEA0NNUb+z4ebVVHyvSwF5jhfJxigim+s49KuzJ1+A2RaSApGyBZiwS
   101  rWvWkB471POAKUYt5ykIWVZ83zcceQiNTwJBAMJUFQZX5GDqWFc/zwGoKkeR49Yi
   102  MTXIvf7Wmv6E++eFcnT461FlGAUHRV+bQQXGsItR/opIG7mGogIkVXa3E1MCQARX
   103  AAA7eoZ9AEHflUeuLn9QJI/r0hyQQLEtrpwv6rDT1GCWaLII5HJ6NUFVf4TTcqxo
   104  6vdM4QGKTJoO+SaCyP0CQFdpcxSAuzpFcKv0IlJ8XzS/cy+mweCMwyJ1PFEc4FX6
   105  wg/HcAJWY60xZTJDFN+Qfx8ZQvBEin6c2/h+zZi5IVY=
   106  -----END RSA TESTING KEY-----
   107  `)
   108  
   109  // pemEd25519Key is the example from RFC 8410, Secrion 4.
   110  var pemEd25519Key = `
   111  -----BEGIN PUBLIC KEY-----
   112  MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE=
   113  -----END PUBLIC KEY-----
   114  `
   115  
   116  func TestPKIXMismatchPublicKeyFormat(t *testing.T) {
   117  
   118  	const pkcs1PublicKey = "308201080282010100817cfed98bcaa2e2a57087451c7674e0c675686dc33ff1268b0c2a6ee0202dec710858ee1c31bdf5e7783582e8ca800be45f3275c6576adc35d98e26e95bb88ca5beb186f853b8745d88bc9102c5f38753bcda519fb05948d5c77ac429255ff8aaf27d9f45d1586e95e2e9ba8a7cb771b8a09dd8c8fed3f933fd9b439bc9f30c475953418ef25f71a2b6496f53d94d39ce850aa0cc75d445b5f5b4f4ee4db78ab197a9a8d8a852f44529a007ac0ac23d895928d60ba538b16b0b087a7f903ed29770e215019b77eaecc360f35f7ab11b6d735978795b2c4a74e5bdea4dc6594cd67ed752a108e666729a753ab36d6c4f606f8760f507e1765be8cd744007e629020103"
   119  	const errorContains = "use ParsePKCS1PublicKey instead"
   120  	derBytes, _ := hex.DecodeString(pkcs1PublicKey)
   121  	_, err := ParsePKIXPublicKey(derBytes)
   122  	if !strings.Contains(err.Error(), errorContains) {
   123  		t.Errorf("expected error containing %q, got %s", errorContains, err)
   124  	}
   125  }
   126  
   127  var testPrivateKey *rsa.PrivateKey
   128  
   129  func init() {
   130  	block, _ := pem.Decode([]byte(pemPrivateKey))
   131  
   132  	var err error
   133  	if testPrivateKey, err = x509.ParsePKCS1PrivateKey(block.Bytes); err != nil {
   134  		panic("Failed to parse private key: " + err.Error())
   135  	}
   136  }
   137  
   138  func bigFromString(s string) *big.Int {
   139  	ret := new(big.Int)
   140  	ret.SetString(s, 10)
   141  	return ret
   142  }
   143  
   144  func fromBase10(base10 string) *big.Int {
   145  	i := new(big.Int)
   146  	i.SetString(base10, 10)
   147  	return i
   148  }
   149  
   150  func bigFromHexString(s string) *big.Int {
   151  	ret := new(big.Int)
   152  	ret.SetString(s, 16)
   153  	return ret
   154  }
   155  
   156  var rsaPrivateKey = &rsa.PrivateKey{
   157  	PublicKey: rsa.PublicKey{
   158  		N: bigFromString("124737666279038955318614287965056875799409043964547386061640914307192830334599556034328900586693254156136128122194531292927142396093148164407300419162827624945636708870992355233833321488652786796134504707628792159725681555822420087112284637501705261187690946267527866880072856272532711620639179596808018872997"),
   159  		E: 65537,
   160  	},
   161  	D: bigFromString("69322600686866301945688231018559005300304807960033948687567105312977055197015197977971637657636780793670599180105424702854759606794705928621125408040473426339714144598640466128488132656829419518221592374964225347786430566310906679585739468938549035854760501049443920822523780156843263434219450229353270690889"),
   162  	Primes: []*big.Int{
   163  		bigFromString("11405025354575369741595561190164746858706645478381139288033759331174478411254205003127028642766986913445391069745480057674348716675323735886284176682955723"),
   164  		bigFromString("10937079261204603443118731009201819560867324167189758120988909645641782263430128449826989846631183550578761324239709121189827307416350485191350050332642639"),
   165  	},
   166  }
   167  
   168  type matchHostnamesTest struct {
   169  	pattern, host string
   170  	ok            bool
   171  }
   172  
   173  var matchHostnamesTests = []matchHostnamesTest{
   174  	{"a.b.c", "a.b.c", true},
   175  	{"a.b.c", "b.b.c", false},
   176  	{"", "b.b.c", false},
   177  	{"a.b.c", "", false},
   178  	{"example.com", "example.com", true},
   179  	{"example.com", "www.example.com", false},
   180  	{"*.example.com", "example.com", false},
   181  	{"*.example.com", "www.example.com", true},
   182  	{"*.example.com", "www.example.com.", true},
   183  	{"*.example.com", "xyz.www.example.com", false},
   184  	{"*.example.com", "https://www.example.com", false}, // Issue 27591
   185  	{"*.example..com", "www.example..com", false},
   186  	{"www.example..com", "www.example..com", true},
   187  	{"*.*.example.com", "xyz.www.example.com", false},
   188  	{"*.www.*.com", "xyz.www.example.com", false},
   189  	{"*bar.example.com", "foobar.example.com", false},
   190  	{"f*.example.com", "foobar.example.com", false},
   191  	{"www.example.com", "*.example.com", false},
   192  	{"", ".", false},
   193  	{".", "", false},
   194  	{".", ".", false},
   195  	{"example.com", "example.com.", true},
   196  	{"example.com.", "example.com", false},
   197  	{"example.com.", "example.com.", true}, // perfect matches allow trailing dots in patterns
   198  	{"*.com.", "example.com.", false},
   199  	{"*.com.", "example.com", false},
   200  	{"*.com", "example.com", true},
   201  	{"*.com", "example.com.", true},
   202  	{"foo:bar", "foo:bar", true},
   203  	{"*.foo:bar", "xxx.foo:bar", false},
   204  	{"*.2.3.4", "1.2.3.4", false},
   205  	{"*.2.3.4", "[1.2.3.4]", false},
   206  	{"*:4860:4860::8888", "2001:4860:4860::8888", false},
   207  	{"*:4860:4860::8888", "[2001:4860:4860::8888]", false},
   208  	{"2001:4860:4860::8888", "2001:4860:4860::8888", false},
   209  	{"2001:4860:4860::8888", "[2001:4860:4860::8888]", false},
   210  	{"[2001:4860:4860::8888]", "2001:4860:4860::8888", false},
   211  	{"[2001:4860:4860::8888]", "[2001:4860:4860::8888]", false},
   212  }
   213  
   214  func TestMatchHostnames(t *testing.T) {
   215  	for i, test := range matchHostnamesTests {
   216  		c := &Certificate{DNSNames: []string{test.pattern}}
   217  		r := c.VerifyHostname(test.host) == nil
   218  		if r != test.ok {
   219  			t.Errorf("#%d mismatch got: %t want: %t when matching '%s' against '%s'", i, r, test.ok, test.host, test.pattern)
   220  		}
   221  	}
   222  }
   223  
   224  func TestMatchIP(t *testing.T) {
   225  	// Check that pattern matching is working.
   226  	c := &Certificate{
   227  		DNSNames: []string{"*.foo.bar.baz"},
   228  		Subject: pkix.Name{
   229  			CommonName: "*.foo.bar.baz",
   230  		},
   231  	}
   232  	err := c.VerifyHostname("quux.foo.bar.baz")
   233  	if err != nil {
   234  		t.Fatalf("VerifyHostname(quux.foo.bar.baz): %v", err)
   235  	}
   236  
   237  	// But check that if we change it to be matching against an IP address,
   238  	// it is rejected.
   239  	c = &Certificate{
   240  		DNSNames: []string{"*.2.3.4"},
   241  		Subject: pkix.Name{
   242  			CommonName: "*.2.3.4",
   243  		},
   244  	}
   245  	err = c.VerifyHostname("1.2.3.4")
   246  	if err == nil {
   247  		t.Fatalf("VerifyHostname(1.2.3.4) should have failed, did not")
   248  	}
   249  
   250  	c = &Certificate{
   251  		IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
   252  	}
   253  	err = c.VerifyHostname("127.0.0.1")
   254  	if err != nil {
   255  		t.Fatalf("VerifyHostname(127.0.0.1): %v", err)
   256  	}
   257  	err = c.VerifyHostname("::1")
   258  	if err != nil {
   259  		t.Fatalf("VerifyHostname(::1): %v", err)
   260  	}
   261  	err = c.VerifyHostname("[::1]")
   262  	if err != nil {
   263  		t.Fatalf("VerifyHostname([::1]): %v", err)
   264  	}
   265  }
   266  
   267  func TestCertificateParse(t *testing.T) {
   268  	s, _ := base64.StdEncoding.DecodeString(certBytes)
   269  	certs, err := ParseCertificates(s)
   270  	if err != nil {
   271  		t.Error(err)
   272  	}
   273  	if len(certs) != 2 {
   274  		t.Errorf("Wrong number of certs: got %d want 2", len(certs))
   275  		return
   276  	}
   277  
   278  	err = certs[0].CheckSignatureFrom(certs[1])
   279  	if err != nil {
   280  		t.Error(err)
   281  	}
   282  
   283  	if err := certs[0].VerifyHostname("mail.google.com"); err != nil {
   284  		t.Error(err)
   285  	}
   286  
   287  	const expectedExtensions = 10
   288  	if n := len(certs[0].Extensions); n != expectedExtensions {
   289  		t.Errorf("want %d extensions, got %d", expectedExtensions, n)
   290  	}
   291  }
   292  
   293  func TestCertificateEqualOnNil(t *testing.T) {
   294  	cNonNil := new(Certificate)
   295  	var cNil1, cNil2 *Certificate
   296  	if !cNil1.Equal(cNil2) {
   297  		t.Error("Nil certificates: cNil1 is not equal to cNil2")
   298  	}
   299  	if !cNil2.Equal(cNil1) {
   300  		t.Error("Nil certificates: cNil2 is not equal to cNil1")
   301  	}
   302  	if cNil1.Equal(cNonNil) {
   303  		t.Error("Unexpectedly cNil1 is equal to cNonNil")
   304  	}
   305  	if cNonNil.Equal(cNil1) {
   306  		t.Error("Unexpectedly cNonNil is equal to cNil1")
   307  	}
   308  }
   309  
   310  func TestMismatchedSignatureAlgorithm(t *testing.T) {
   311  	der, _ := pem.Decode([]byte(rsaPSSSelfSignedPEM))
   312  	if der == nil {
   313  		t.Fatal("Failed to find PEM block")
   314  	}
   315  
   316  	cert, err := ParseCertificate(der.Bytes)
   317  	if err != nil {
   318  		t.Fatal(err)
   319  	}
   320  
   321  	if err = cert.CheckSignature(ECDSAWithSHA256, nil, nil); err == nil {
   322  		t.Fatal("CheckSignature unexpectedly return no error")
   323  	}
   324  
   325  	const expectedSubstring = " but have public key of type "
   326  	if !strings.Contains(err.Error(), expectedSubstring) {
   327  		t.Errorf("Expected error containing %q, but got %q", expectedSubstring, err)
   328  	}
   329  }
   330  
   331  var certBytes = "MIIE0jCCA7qgAwIBAgIQWcvS+TTB3GwCAAAAAGEAWzANBgkqhkiG9w0BAQsFADBCMQswCQYD" +
   332  	"VQQGEwJVUzEeMBwGA1UEChMVR29vZ2xlIFRydXN0IFNlcnZpY2VzMRMwEQYDVQQDEwpHVFMg" +
   333  	"Q0EgMU8xMB4XDTIwMDQwMTEyNTg1NloXDTIwMDYyNDEyNTg1NlowaTELMAkGA1UEBhMCVVMx" +
   334  	"EzARBgNVBAgTCkNhbGlmb3JuaWExFjAUBgNVBAcTDU1vdW50YWluIFZpZXcxEzARBgNVBAoT" +
   335  	"Ckdvb2dsZSBMTEMxGDAWBgNVBAMTD21haWwuZ29vZ2xlLmNvbTBZMBMGByqGSM49AgEGCCqG" +
   336  	"SM49AwEHA0IABO+dYiPnkFl+cZVf6mrWeNp0RhQcJSBGH+sEJxjvc+cYlW3QJCnm57qlpFdd" +
   337  	"pz3MPyVejvXQdM6iI1mEWP4C2OujggJmMIICYjAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAww" +
   338  	"CgYIKwYBBQUHAwEwDAYDVR0TAQH/BAIwADAdBgNVHQ4EFgQUI6pZhnQ/lQgmPDwSKR2A54G7" +
   339  	"AS4wHwYDVR0jBBgwFoAUmNH4bhDrz5vsYJ8YkBug630J/SswZAYIKwYBBQUHAQEEWDBWMCcG" +
   340  	"CCsGAQUFBzABhhtodHRwOi8vb2NzcC5wa2kuZ29vZy9ndHMxbzEwKwYIKwYBBQUHMAKGH2h0" +
   341  	"dHA6Ly9wa2kuZ29vZy9nc3IyL0dUUzFPMS5jcnQwLAYDVR0RBCUwI4IPbWFpbC5nb29nbGUu" +
   342  	"Y29tghBpbmJveC5nb29nbGUuY29tMCEGA1UdIAQaMBgwCAYGZ4EMAQICMAwGCisGAQQB1nkC" +
   343  	"BQMwLwYDVR0fBCgwJjAkoCKgIIYeaHR0cDovL2NybC5wa2kuZ29vZy9HVFMxTzEuY3JsMIIB" +
   344  	"AwYKKwYBBAHWeQIEAgSB9ASB8QDvAHYAsh4FzIuizYogTodm+Su5iiUgZ2va+nDnsklTLe+L" +
   345  	"kF4AAAFxNgmxKgAABAMARzBFAiEA12/OHdTGXQ3qHHC3NvYCyB8aEz/+ZFOLCAI7lhqj28sC" +
   346  	"IG2/7Yz2zK6S6ai+dH7cTMZmoFGo39gtaTqtZAqEQX7nAHUAXqdz+d9WwOe1Nkh90EngMnqR" +
   347  	"mgyEoRIShBh1loFxRVgAAAFxNgmxTAAABAMARjBEAiA7PNq+MFfv6O9mBkxFViS2TfU66yRB" +
   348  	"/njcebWglLQjZQIgOyRKhxlEizncFRml7yn4Bg48ktXKGjo+uiw6zXEINb0wDQYJKoZIhvcN" +
   349  	"AQELBQADggEBADM2Rh306Q10PScsolYMxH1B/K4Nb2WICvpY0yDPJFdnGjqCYym196TjiEvs" +
   350  	"R6etfeHdyzlZj6nh82B4TVyHjiWM02dQgPalOuWQcuSy0OvLh7F1E7CeHzKlczdFPBTOTdM1" +
   351  	"RDTxlvw1bAqc0zueM8QIAyEy3opd7FxAcGQd5WRIJhzLBL+dbbMOW/LTeW7cm/Xzq8cgCybN" +
   352  	"BSZAvhjseJ1L29OlCTZL97IfnX0IlFQzWuvvHy7V2B0E3DHlzM0kjwkkCKDUUp/wajv2NZKC" +
   353  	"TkhEyERacZRKc9U0ADxwsAzHrdz5+5zfD2usEV/MQ5V6d8swLXs+ko0X6swrd4YCiB8wggRK" +
   354  	"MIIDMqADAgECAg0B47SaoY2KqYElaVC4MA0GCSqGSIb3DQEBCwUAMEwxIDAeBgNVBAsTF0ds" +
   355  	"b2JhbFNpZ24gUm9vdCBDQSAtIFIyMRMwEQYDVQQKEwpHbG9iYWxTaWduMRMwEQYDVQQDEwpH" +
   356  	"bG9iYWxTaWduMB4XDTE3MDYxNTAwMDA0MloXDTIxMTIxNTAwMDA0MlowQjELMAkGA1UEBhMC" +
   357  	"VVMxHjAcBgNVBAoTFUdvb2dsZSBUcnVzdCBTZXJ2aWNlczETMBEGA1UEAxMKR1RTIENBIDFP" +
   358  	"MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANAYz0XUi83TnORA73603WkhG8nP" +
   359  	"PI5MdbkPMRmEPZ48Ke9QDRCTbwWAgJ8qoL0SSwLhPZ9YFiT+MJ8LdHdVkx1L903hkoIQ9lGs" +
   360  	"DMOyIpQPNGuYEEnnC52DOd0gxhwt79EYYWXnI4MgqCMS/9Ikf9Qv50RqW03XUGawr55CYwX7" +
   361  	"4BzEY2Gvn2oz/2KXvUjZ03wUZ9x13C5p6PhteGnQtxAFuPExwjsk/RozdPgj4OxrGYoWxuPN" +
   362  	"pM0L27OkWWA4iDutHbnGjKdTG/y82aSrvN08YdeTFZjugb2P4mRHIEAGTtesl+i5wFkSoUkl" +
   363  	"I+TtcDQspbRjfPmjPYPRzW0krAcCAwEAAaOCATMwggEvMA4GA1UdDwEB/wQEAwIBhjAdBgNV" +
   364  	"HSUEFjAUBggrBgEFBQcDAQYIKwYBBQUHAwIwEgYDVR0TAQH/BAgwBgEB/wIBADAdBgNVHQ4E" +
   365  	"FgQUmNH4bhDrz5vsYJ8YkBug630J/SswHwYDVR0jBBgwFoAUm+IHV2ccHsBqBt5ZtJot39wZ" +
   366  	"hi4wNQYIKwYBBQUHAQEEKTAnMCUGCCsGAQUFBzABhhlodHRwOi8vb2NzcC5wa2kuZ29vZy9n" +
   367  	"c3IyMDIGA1UdHwQrMCkwJ6AloCOGIWh0dHA6Ly9jcmwucGtpLmdvb2cvZ3NyMi9nc3IyLmNy" +
   368  	"bDA/BgNVHSAEODA2MDQGBmeBDAECAjAqMCgGCCsGAQUFBwIBFhxodHRwczovL3BraS5nb29n" +
   369  	"L3JlcG9zaXRvcnkvMA0GCSqGSIb3DQEBCwUAA4IBAQAagD42efvzLqlGN31eVBY1rsdOCJn+" +
   370  	"vdE0aSZSZgc9CrpJy2L08RqO/BFPaJZMdCvTZ96yo6oFjYRNTCBlD6WW2g0W+Gw7228EI4hr" +
   371  	"OmzBYL1on3GO7i1YNAfw1VTphln9e14NIZT1jMmo+NjyrcwPGvOap6kEJ/mjybD/AnhrYbrH" +
   372  	"NSvoVvpPwxwM7bY8tEvq7czhPOzcDYzWPpvKQliLzBYhF0C8otZm79rEFVvNiaqbCSbnMtIN" +
   373  	"bmcgAlsQsJAJnAwfnq3YO+qh/GzoEFwIUhlRKnG7rHq13RXtK8kIKiyKtKYhq2P/11JJUNCJ" +
   374  	"t63yr/tQri/hlQ3zRq2dnPXK"
   375  
   376  func parseCIDR(s string) *net.IPNet {
   377  	_, net, err := net.ParseCIDR(s)
   378  	if err != nil {
   379  		panic(err)
   380  	}
   381  	return net
   382  }
   383  
   384  func parseURI(s string) *url.URL {
   385  	uri, err := url.Parse(s)
   386  	if err != nil {
   387  		panic(err)
   388  	}
   389  	return uri
   390  }
   391  
   392  func TestCreateSelfSignedCertificate(t *testing.T) {
   393  	random := rand.Reader
   394  
   395  	sm2Priv, err := sm2.GenerateKey(rand.Reader)
   396  	if err != nil {
   397  		t.Fatalf("Failed to generate SM2 key: %s", err)
   398  	}
   399  
   400  	ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   401  	if err != nil {
   402  		t.Fatalf("Failed to generate ECDSA key: %s", err)
   403  	}
   404  
   405  	ed25519Pub, ed25519Priv, err := ed25519.GenerateKey(random)
   406  	if err != nil {
   407  		t.Fatalf("Failed to generate Ed25519 key: %s", err)
   408  	}
   409  
   410  	tests := []struct {
   411  		name      string
   412  		pub, priv any
   413  		checkSig  bool
   414  		sigAlgo   SignatureAlgorithm
   415  	}{
   416  		{"RSA/RSA", &testPrivateKey.PublicKey, testPrivateKey, true, SHA384WithRSA},
   417  		{"RSA/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
   418  		{"RSA/SM2", &testPrivateKey.PublicKey, sm2Priv, false, SM2WithSM3},
   419  		{"ECDSA/RSA", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSA},
   420  		{"ECDSA/ECDSA", &ecdsaPriv.PublicKey, ecdsaPriv, true, ECDSAWithSHA256},
   421  		{"ECDSA/SM2", &ecdsaPriv.PublicKey, sm2Priv, false, SM2WithSM3},
   422  		{"SM2/ECDSA", &sm2Priv.PublicKey, ecdsaPriv, false, ECDSAWithSHA256},
   423  		{"RSAPSS/RSAPSS", &testPrivateKey.PublicKey, testPrivateKey, true, SHA256WithRSAPSS},
   424  		{"ECDSA/RSAPSS", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSAPSS},
   425  		{"SM2/RSAPSS", &sm2Priv.PublicKey, testPrivateKey, false, SHA256WithRSAPSS},
   426  		{"RSAPSS/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
   427  		{"Ed25519", ed25519Pub, ed25519Priv, true, PureEd25519},
   428  		{"SM2", &sm2Priv.PublicKey, sm2Priv, true, SM2WithSM3},
   429  	}
   430  
   431  	testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth}
   432  	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
   433  	extraExtensionData := []byte("extra extension")
   434  
   435  	for _, test := range tests {
   436  		commonName := "test.example.com"
   437  		template := x509.Certificate{
   438  			SerialNumber: big.NewInt(1),
   439  			Subject: pkix.Name{
   440  				CommonName:   commonName,
   441  				Organization: []string{"Σ Acme Co"},
   442  				Country:      []string{"US"},
   443  				ExtraNames: []pkix.AttributeTypeAndValue{
   444  					{
   445  						Type:  []int{2, 5, 4, 42},
   446  						Value: "Gopher",
   447  					},
   448  					// This should override the Country, above.
   449  					{
   450  						Type:  []int{2, 5, 4, 6},
   451  						Value: "NL",
   452  					},
   453  				},
   454  			},
   455  			NotBefore: time.Unix(1000, 0),
   456  			NotAfter:  time.Unix(100000, 0),
   457  
   458  			SignatureAlgorithm: test.sigAlgo,
   459  
   460  			SubjectKeyId: []byte{1, 2, 3, 4},
   461  			KeyUsage:     KeyUsageCertSign,
   462  
   463  			ExtKeyUsage:        testExtKeyUsage,
   464  			UnknownExtKeyUsage: testUnknownExtKeyUsage,
   465  
   466  			BasicConstraintsValid: true,
   467  			IsCA:                  true,
   468  
   469  			OCSPServer:            []string{"http://ocsp.example.com"},
   470  			IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
   471  
   472  			DNSNames:       []string{"test.example.com"},
   473  			EmailAddresses: []string{"gopher@golang.org"},
   474  			IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
   475  			URIs:           []*url.URL{parseURI("https://foo.com/wibble#foo")},
   476  
   477  			PolicyIdentifiers:       []asn1.ObjectIdentifier{[]int{1, 2, 3}},
   478  			PermittedDNSDomains:     []string{".example.com", "example.com"},
   479  			ExcludedDNSDomains:      []string{"bar.example.com"},
   480  			PermittedIPRanges:       []*net.IPNet{parseCIDR("192.168.1.1/16"), parseCIDR("1.2.3.4/8")},
   481  			ExcludedIPRanges:        []*net.IPNet{parseCIDR("2001:db8::/48")},
   482  			PermittedEmailAddresses: []string{"foo@example.com"},
   483  			ExcludedEmailAddresses:  []string{".example.com", "example.com"},
   484  			PermittedURIDomains:     []string{".bar.com", "bar.com"},
   485  			ExcludedURIDomains:      []string{".bar2.com", "bar2.com"},
   486  
   487  			CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
   488  
   489  			ExtraExtensions: []pkix.Extension{
   490  				{
   491  					Id:    []int{1, 2, 3, 4},
   492  					Value: extraExtensionData,
   493  				},
   494  				// This extension should override the SubjectKeyId, above.
   495  				{
   496  					Id:       oidExtensionSubjectKeyId,
   497  					Critical: false,
   498  					Value:    []byte{0x04, 0x04, 4, 3, 2, 1},
   499  				},
   500  			},
   501  		}
   502  
   503  		derBytes, err := CreateCertificate(random, &template, &template, test.pub, test.priv)
   504  		if err != nil {
   505  			t.Errorf("%s: failed to create certificate: %s", test.name, err)
   506  			continue
   507  		}
   508  
   509  		cert, err := ParseCertificate(derBytes)
   510  		if err != nil {
   511  			t.Errorf("%s: failed to parse certificate: %s", test.name, err)
   512  			continue
   513  		}
   514  
   515  		if len(cert.PolicyIdentifiers) != 1 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) {
   516  			t.Errorf("%s: failed to parse policy identifiers: got:%#v want:%#v", test.name, cert.PolicyIdentifiers, template.PolicyIdentifiers)
   517  		}
   518  
   519  		if len(cert.PermittedDNSDomains) != 2 || cert.PermittedDNSDomains[0] != ".example.com" || cert.PermittedDNSDomains[1] != "example.com" {
   520  			t.Errorf("%s: failed to parse name constraints: %#v", test.name, cert.PermittedDNSDomains)
   521  		}
   522  
   523  		if len(cert.ExcludedDNSDomains) != 1 || cert.ExcludedDNSDomains[0] != "bar.example.com" {
   524  			t.Errorf("%s: failed to parse name constraint exclusions: %#v", test.name, cert.ExcludedDNSDomains)
   525  		}
   526  
   527  		if len(cert.PermittedIPRanges) != 2 || cert.PermittedIPRanges[0].String() != "192.168.0.0/16" || cert.PermittedIPRanges[1].String() != "1.0.0.0/8" {
   528  			t.Errorf("%s: failed to parse IP constraints: %#v", test.name, cert.PermittedIPRanges)
   529  		}
   530  
   531  		if len(cert.ExcludedIPRanges) != 1 || cert.ExcludedIPRanges[0].String() != "2001:db8::/48" {
   532  			t.Errorf("%s: failed to parse IP constraint exclusions: %#v", test.name, cert.ExcludedIPRanges)
   533  		}
   534  
   535  		if len(cert.PermittedEmailAddresses) != 1 || cert.PermittedEmailAddresses[0] != "foo@example.com" {
   536  			t.Errorf("%s: failed to parse permitted email addreses: %#v", test.name, cert.PermittedEmailAddresses)
   537  		}
   538  
   539  		if len(cert.ExcludedEmailAddresses) != 2 || cert.ExcludedEmailAddresses[0] != ".example.com" || cert.ExcludedEmailAddresses[1] != "example.com" {
   540  			t.Errorf("%s: failed to parse excluded email addreses: %#v", test.name, cert.ExcludedEmailAddresses)
   541  		}
   542  
   543  		if len(cert.PermittedURIDomains) != 2 || cert.PermittedURIDomains[0] != ".bar.com" || cert.PermittedURIDomains[1] != "bar.com" {
   544  			t.Errorf("%s: failed to parse permitted URIs: %#v", test.name, cert.PermittedURIDomains)
   545  		}
   546  
   547  		if len(cert.ExcludedURIDomains) != 2 || cert.ExcludedURIDomains[0] != ".bar2.com" || cert.ExcludedURIDomains[1] != "bar2.com" {
   548  			t.Errorf("%s: failed to parse excluded URIs: %#v", test.name, cert.ExcludedURIDomains)
   549  		}
   550  
   551  		if cert.Subject.CommonName != commonName {
   552  			t.Errorf("%s: subject wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Subject.CommonName, commonName)
   553  		}
   554  
   555  		if len(cert.Subject.Country) != 1 || cert.Subject.Country[0] != "NL" {
   556  			t.Errorf("%s: ExtraNames didn't override Country", test.name)
   557  		}
   558  
   559  		for _, ext := range cert.Extensions {
   560  			if ext.Id.Equal(oidExtensionSubjectAltName) {
   561  				if ext.Critical {
   562  					t.Fatal("SAN extension is marked critical")
   563  				}
   564  			}
   565  		}
   566  
   567  		found := false
   568  		for _, atv := range cert.Subject.Names {
   569  			if atv.Type.Equal([]int{2, 5, 4, 42}) {
   570  				found = true
   571  				break
   572  			}
   573  		}
   574  		if !found {
   575  			t.Errorf("%s: Names didn't contain oid 2.5.4.42 from ExtraNames", test.name)
   576  		}
   577  
   578  		if cert.Issuer.CommonName != commonName {
   579  			t.Errorf("%s: issuer wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Issuer.CommonName, commonName)
   580  		}
   581  
   582  		if cert.SignatureAlgorithm != test.sigAlgo {
   583  			t.Errorf("%s: SignatureAlgorithm wasn't copied from template. Got %v, want %v", test.name, cert.SignatureAlgorithm, test.sigAlgo)
   584  		}
   585  
   586  		if !reflect.DeepEqual(cert.ExtKeyUsage, testExtKeyUsage) {
   587  			t.Errorf("%s: extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.ExtKeyUsage, testExtKeyUsage)
   588  		}
   589  
   590  		if !reflect.DeepEqual(cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) {
   591  			t.Errorf("%s: unknown extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.UnknownExtKeyUsage, testUnknownExtKeyUsage)
   592  		}
   593  
   594  		if !reflect.DeepEqual(cert.OCSPServer, template.OCSPServer) {
   595  			t.Errorf("%s: OCSP servers differ from template. Got %v, want %v", test.name, cert.OCSPServer, template.OCSPServer)
   596  		}
   597  
   598  		if !reflect.DeepEqual(cert.IssuingCertificateURL, template.IssuingCertificateURL) {
   599  			t.Errorf("%s: Issuing certificate URLs differ from template. Got %v, want %v", test.name, cert.IssuingCertificateURL, template.IssuingCertificateURL)
   600  		}
   601  
   602  		if !reflect.DeepEqual(cert.DNSNames, template.DNSNames) {
   603  			t.Errorf("%s: SAN DNS names differ from template. Got %v, want %v", test.name, cert.DNSNames, template.DNSNames)
   604  		}
   605  
   606  		if !reflect.DeepEqual(cert.EmailAddresses, template.EmailAddresses) {
   607  			t.Errorf("%s: SAN emails differ from template. Got %v, want %v", test.name, cert.EmailAddresses, template.EmailAddresses)
   608  		}
   609  
   610  		if len(cert.URIs) != 1 || cert.URIs[0].String() != "https://foo.com/wibble#foo" {
   611  			t.Errorf("%s: URIs differ from template. Got %v, want %v", test.name, cert.URIs, template.URIs)
   612  		}
   613  
   614  		if !reflect.DeepEqual(cert.IPAddresses, template.IPAddresses) {
   615  			t.Errorf("%s: SAN IPs differ from template. Got %v, want %v", test.name, cert.IPAddresses, template.IPAddresses)
   616  		}
   617  
   618  		if !reflect.DeepEqual(cert.CRLDistributionPoints, template.CRLDistributionPoints) {
   619  			t.Errorf("%s: CRL distribution points differ from template. Got %v, want %v", test.name, cert.CRLDistributionPoints, template.CRLDistributionPoints)
   620  		}
   621  
   622  		if !bytes.Equal(cert.SubjectKeyId, []byte{4, 3, 2, 1}) {
   623  			t.Errorf("%s: ExtraExtensions didn't override SubjectKeyId", test.name)
   624  		}
   625  
   626  		if !bytes.Contains(derBytes, extraExtensionData) {
   627  			t.Errorf("%s: didn't find extra extension in DER output", test.name)
   628  		}
   629  
   630  		if test.checkSig {
   631  			err = cert.CheckSignatureFrom(cert)
   632  			if err != nil {
   633  				t.Errorf("%s: signature verification failed: %s", test.name, err)
   634  			}
   635  		}
   636  	}
   637  }
   638  
   639  // Self-signed certificate using ECDSA with SHA1 & secp256r1
   640  var ecdsaSHA1CertPem = `
   641  -----BEGIN CERTIFICATE-----
   642  MIICDjCCAbUCCQDF6SfN0nsnrjAJBgcqhkjOPQQBMIGPMQswCQYDVQQGEwJVUzET
   643  MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEVMBMG
   644  A1UECgwMR29vZ2xlLCBJbmMuMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   645  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIwMjAyMDUw
   646  WhcNMjIwNTE4MjAyMDUwWjCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   647  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTATBgNVBAoMDEdvb2dsZSwg
   648  SW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAhBgkqhkiG9w0BCQEWFGdv
   649  bGFuZy1kZXZAZ21haWwuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/Wgn
   650  WQDo5+bz71T0327ERgd5SDDXFbXLpzIZDXTkjpe8QTEbsF+ezsQfrekrpDPC4Cd3
   651  P9LY0tG+aI8IyVKdUjAJBgcqhkjOPQQBA0gAMEUCIGlsqMcRqWVIWTD6wXwe6Jk2
   652  DKxL46r/FLgJYnzBEH99AiEA3fBouObsvV1R3oVkb4BQYnD4/4LeId6lAT43YvyV
   653  a/A=
   654  -----END CERTIFICATE-----
   655  `
   656  
   657  // Self-signed certificate using ECDSA with SHA256 & secp256r1
   658  var ecdsaSHA256p256CertPem = `
   659  -----BEGIN CERTIFICATE-----
   660  MIICDzCCAbYCCQDlsuMWvgQzhTAKBggqhkjOPQQDAjCBjzELMAkGA1UEBhMCVVMx
   661  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTAT
   662  BgNVBAoMDEdvb2dsZSwgSW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAh
   663  BgkqhkiG9w0BCQEWFGdvbGFuZy1kZXZAZ21haWwuY29tMB4XDTEyMDUyMTAwMTkx
   664  NloXDTIyMDUxOTAwMTkxNlowgY8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp
   665  Zm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRUwEwYDVQQKDAxHb29nbGUs
   666  IEluYy4xFzAVBgNVBAMMDnd3dy5nb29nbGUuY29tMSMwIQYJKoZIhvcNAQkBFhRn
   667  b2xhbmctZGV2QGdtYWlsLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPMt
   668  2ErhxAty5EJRu9yM+MTy+hUXm3pdW1ensAv382KoGExSXAFWP7pjJnNtHO+XSwVm
   669  YNtqjcAGFKpweoN//kQwCgYIKoZIzj0EAwIDRwAwRAIgIYSaUA/IB81gjbIw/hUV
   670  70twxJr5EcgOo0hLp3Jm+EYCIFDO3NNcgmURbJ1kfoS3N/0O+irUtoPw38YoNkqJ
   671  h5wi
   672  -----END CERTIFICATE-----
   673  `
   674  
   675  // Self-signed certificate using ECDSA with SHA256 & secp384r1
   676  var ecdsaSHA256p384CertPem = `
   677  -----BEGIN CERTIFICATE-----
   678  MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx
   679  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
   680  BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   681  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0
   682  WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   683  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
   684  SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
   685  YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK
   686  jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze
   687  qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI
   688  zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr
   689  PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh
   690  3yILeYQzllt/g0rKVRk=
   691  -----END CERTIFICATE-----
   692  `
   693  
   694  // Self-signed certificate using ECDSA with SHA384 & secp521r1
   695  var ecdsaSHA384p521CertPem = `
   696  -----BEGIN CERTIFICATE-----
   697  MIICljCCAfcCCQDhp1AFD/ahKjAKBggqhkjOPQQDAzCBjjELMAkGA1UEBhMCVVMx
   698  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
   699  BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   700  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMTUwNDI5
   701  WhcNMjIwNTE5MTUwNDI5WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   702  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
   703  SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
   704  YW5nLWRldkBnbWFpbC5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACqx9Rv
   705  IssRs1LWYcNN+WffwlHw4Tv3y8/LIAA9MF1ZScIonU9nRMxt4a2uGJVCPDw6JHpz
   706  PaYc0E9puLoE9AfKpwFr59Jkot7dBg55SKPEFkddoip/rvmN7NPAWjMBirOwjOkm
   707  8FPthvPhGPqsu9AvgVuHu3PosWiHGNrhh379pva8MzAKBggqhkjOPQQDAwOBjAAw
   708  gYgCQgEHNmswkUdPpHqrVxp9PvLVl+xxPuHBkT+75z9JizyxtqykHQo9Uh6SWCYH
   709  BF9KLolo01wMt8DjoYP5Fb3j5MH7xwJCAbWZzTOp4l4DPkIvAh4LeC4VWbwPPyqh
   710  kBg71w/iEcSY3wUKgHGcJJrObZw7wys91I5kENljqw/Samdr3ka+jBJa
   711  -----END CERTIFICATE-----
   712  `
   713  
   714  var ecdsaTests = []struct {
   715  	sigAlgo SignatureAlgorithm
   716  	pemCert string
   717  }{
   718  	{ECDSAWithSHA256, ecdsaSHA256p256CertPem},
   719  	{ECDSAWithSHA256, ecdsaSHA256p384CertPem},
   720  	{ECDSAWithSHA384, ecdsaSHA384p521CertPem},
   721  }
   722  
   723  func TestECDSA(t *testing.T) {
   724  	for i, test := range ecdsaTests {
   725  		pemBlock, _ := pem.Decode([]byte(test.pemCert))
   726  		cert, err := ParseCertificate(pemBlock.Bytes)
   727  		if err != nil {
   728  			t.Errorf("%d: failed to parse certificate: %s", i, err)
   729  			continue
   730  		}
   731  		if sa := cert.SignatureAlgorithm; sa != test.sigAlgo {
   732  			t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo)
   733  		}
   734  		if parsedKey, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok {
   735  			t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey)
   736  		}
   737  		if pka := cert.PublicKeyAlgorithm; pka != ECDSA {
   738  			t.Errorf("%d: public key algorithm is %v, want ECDSA", i, pka)
   739  		}
   740  		if err = cert.CheckSignatureFrom(cert); err != nil {
   741  			t.Errorf("%d: certificate verification failed: %s", i, err)
   742  		}
   743  	}
   744  }
   745  
   746  // Self-signed certificate using DSA with SHA1
   747  var dsaCertPem = `-----BEGIN CERTIFICATE-----
   748  MIIEDTCCA82gAwIBAgIJALHPghaoxeDhMAkGByqGSM44BAMweTELMAkGA1UEBhMC
   749  VVMxCzAJBgNVBAgTAk5DMQ8wDQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2ds
   750  ZSwgSW5jMRIwEAYDVQQDEwlKb24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFs
   751  bGllQGdvb2dsZS5jb20wHhcNMTEwNTE0MDMwMTQ1WhcNMTEwNjEzMDMwMTQ1WjB5
   752  MQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkMxDzANBgNVBAcTBk5ld3RvbjEUMBIG
   753  A1UEChMLR29vZ2xlLCBJbmMxEjAQBgNVBAMTCUpvbiBBbGxpZTEiMCAGCSqGSIb3
   754  DQEJARYTam9uYWxsaWVAZ29vZ2xlLmNvbTCCAbcwggEsBgcqhkjOOAQBMIIBHwKB
   755  gQC8hLUnQ7FpFYu4WXTj6DKvXvz8QrJkNJCVMTpKAT7uBpobk32S5RrPKXocd4gN
   756  8lyGB9ggS03EVlEwXvSmO0DH2MQtke2jl9j1HLydClMf4sbx5V6TV9IFw505U1iW
   757  jL7awRMgxge+FsudtJK254FjMFo03ZnOQ8ZJJ9E6AEDrlwIVAJpnBn9moyP11Ox5
   758  Asc/5dnjb6dPAoGBAJFHd4KVv1iTVCvEG6gGiYop5DJh28hUQcN9kul+2A0yPUSC
   759  X93oN00P8Vh3eYgSaCWZsha7zDG53MrVJ0Zf6v/X/CoZNhLldeNOepivTRAzn+Rz
   760  kKUYy5l1sxYLHQKF0UGNCXfFKZT0PCmgU+PWhYNBBMn6/cIh44vp85ideo5CA4GE
   761  AAKBgFmifCafzeRaohYKXJgMGSEaggCVCRq5xdyDCat+wbOkjC4mfG01/um3G8u5
   762  LxasjlWRKTR/tcAL7t0QuokVyQaYdVypZXNaMtx1db7YBuHjj3aP+8JOQRI9xz8c
   763  bp5NDJ5pISiFOv4p3GZfqZPcqckDt78AtkQrmnal2txhhjF6o4HeMIHbMB0GA1Ud
   764  DgQWBBQVyyr7hO11ZFFpWX50298Sa3V+rzCBqwYDVR0jBIGjMIGggBQVyyr7hO11
   765  ZFFpWX50298Sa3V+r6F9pHsweTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAk5DMQ8w
   766  DQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2dsZSwgSW5jMRIwEAYDVQQDEwlK
   767  b24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFsbGllQGdvb2dsZS5jb22CCQCx
   768  z4IWqMXg4TAMBgNVHRMEBTADAQH/MAkGByqGSM44BAMDLwAwLAIUPtn/5j8Q1jJI
   769  7ggOIsgrhgUdjGQCFCsmDq1H11q9+9Wp9IMeGrTSKHIM
   770  -----END CERTIFICATE-----
   771  `
   772  
   773  func TestParseCertificateWithDsaPublicKey(t *testing.T) {
   774  	expectedKey := &dsa.PublicKey{
   775  		Parameters: dsa.Parameters{
   776  			P: bigFromHexString("00BC84B52743B169158BB85974E3E832AF5EFCFC42B264349095313A4A013EEE069A1B937D92E51ACF297A1C77880DF25C8607D8204B4DC45651305EF4A63B40C7D8C42D91EDA397D8F51CBC9D0A531FE2C6F1E55E9357D205C39D395358968CBEDAC11320C607BE16CB9DB492B6E78163305A34DD99CE43C64927D13A0040EB97"),
   777  			Q: bigFromHexString("009A67067F66A323F5D4EC7902C73FE5D9E36FA74F"),
   778  			G: bigFromHexString("009147778295BF5893542BC41BA806898A29E43261DBC85441C37D92E97ED80D323D44825FDDE8374D0FF15877798812682599B216BBCC31B9DCCAD527465FEAFFD7FC2A193612E575E34E7A98AF4D10339FE47390A518CB9975B3160B1D0285D1418D0977C52994F43C29A053E3D685834104C9FAFDC221E38BE9F3989D7A8E42"),
   779  		},
   780  		Y: bigFromHexString("59A27C269FCDE45AA2160A5C980C19211A820095091AB9C5DC8309AB7EC1B3A48C2E267C6D35FEE9B71BCBB92F16AC8E559129347FB5C00BEEDD10BA8915C90698755CA965735A32DC7575BED806E1E38F768FFBC24E41123DC73F1C6E9E4D0C9E692128853AFE29DC665FA993DCA9C903B7BF00B6442B9A76A5DADC6186317A"),
   781  	}
   782  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   783  	cert, err := ParseCertificate(pemBlock.Bytes)
   784  	if err != nil {
   785  		t.Fatalf("Failed to parse certificate: %s", err)
   786  	}
   787  	if cert.PublicKeyAlgorithm != DSA {
   788  		t.Errorf("Parsed key algorithm was not DSA")
   789  	}
   790  	parsedKey, ok := cert.PublicKey.(*dsa.PublicKey)
   791  	if !ok {
   792  		t.Fatalf("Parsed key was not a DSA key: %s", err)
   793  	}
   794  	if expectedKey.Y.Cmp(parsedKey.Y) != 0 ||
   795  		expectedKey.P.Cmp(parsedKey.P) != 0 ||
   796  		expectedKey.Q.Cmp(parsedKey.Q) != 0 ||
   797  		expectedKey.G.Cmp(parsedKey.G) != 0 {
   798  		t.Fatal("Parsed key differs from expected key")
   799  	}
   800  }
   801  
   802  func TestParseCertificateWithDSASignatureAlgorithm(t *testing.T) {
   803  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   804  	cert, err := ParseCertificate(pemBlock.Bytes)
   805  	if err != nil {
   806  		t.Fatalf("Failed to parse certificate: %s", err)
   807  	}
   808  	if cert.SignatureAlgorithm != DSAWithSHA1 {
   809  		t.Errorf("Parsed signature algorithm was not DSAWithSHA1")
   810  	}
   811  }
   812  
   813  func TestVerifyCertificateWithDSASignature(t *testing.T) {
   814  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   815  	cert, err := ParseCertificate(pemBlock.Bytes)
   816  	if err != nil {
   817  		t.Fatalf("Failed to parse certificate: %s", err)
   818  	}
   819  	// test cert is self-signed
   820  	if err = cert.CheckSignatureFrom(cert); err == nil {
   821  		t.Fatalf("Expected error verifying DSA certificate")
   822  	}
   823  }
   824  
   825  var rsaPSSSelfSignedPEM = `-----BEGIN CERTIFICATE-----
   826  MIIGHjCCA9KgAwIBAgIBdjBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA
   827  oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCASAwbjELMAkGA1UEBhMC
   828  SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
   829  aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
   830  U0NBMB4XDTEzMDUxNDA1MDczMFoXDTI5MDUxNDA1MDczMFowbjELMAkGA1UEBhMC
   831  SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
   832  aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
   833  U0NBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAx/E3WRVxcCDXhoST
   834  8nVSLjW6hwM4Ni99AegWzcGtfGFo0zjFA1Cl5URqxauvYu3gQgQHBGA1CovWeGrl
   835  yVSRzOL1imcYsSgLOcnhVYB3Xcrof4ebv9+W+TwNdc9YzAwcj8rNd5nP6PKXIQ+W
   836  PCkEOXdyb80YEnxuT+NPjkVfFSPBS7QYZpvT2fwy4fZ0eh48253+7VleSmTO0mqj
   837  7TlzaG56q150SLZbhpOd8jD8bM/wACnLCPR88wj4hCcDLEwoLyY85HJCTIQQMnoT
   838  UpqyzEeupPREIm6yi4d8C9YqIWFn2YTnRcWcmMaJLzq+kYwKoudfnoC6RW2vzZXn
   839  defQs68IZuK+uALu9G3JWGPgu0CQGj0JNDT8zkiDV++4eNrZczWKjr1YnAL+VbLK
   840  bApwL2u19l2WDpfUklimhWfraqHNIUKU6CjZOG31RzXcplIj0mtqs0E1r7r357Es
   841  yFoB28iNo4cz1lCulh0E4WJzWzLZcT4ZspHHRCFyvYnXoibXEV1nULq8ByKKG0FS
   842  7nn4SseoV+8PvjHLPhmHGMvi4mxkbcXdV3wthHT1/HXdqY84A4xHWt1+sB/TpTek
   843  tDhFlEfcUygvTu58UtOnysomOVVeERmi7WSujfzKsGJAJYeetiA5R+zX7BxeyFVE
   844  qW0zh1Tkwh0S8LRe5diJh4+6FG0CAwEAAaNfMF0wHQYDVR0OBBYEFD+oahaikBTV
   845  Urk81Uz7kRS2sx0aMA4GA1UdDwEB/wQEAwIBBjAYBgNVHSAEETAPMA0GCyqDCIaP
   846  fgYFAQEBMBIGA1UdEwEB/wQIMAYBAf8CAQAwQQYJKoZIhvcNAQEKMDSgDzANBglg
   847  hkgBZQMEAgEFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgEFAKIDAgEgA4IC
   848  AQAaxWBQn5CZuNBfyzL57mn31ukHUFd61OMROSX3PT7oCv1Dy+C2AdRlxOcbN3/n
   849  li0yfXUUqiY3COlLAHKRlkr97mLtxEFoJ0R8nVN2IQdChNQM/XSCzSGyY8NVa1OR
   850  TTpEWLnexJ9kvIdbFXwUqdTnAkOI0m7Rg8j+E+lRRHg1xDAA1qKttrtUj3HRQWf3
   851  kNTu628SiMvap6aIdncburaK56MP7gkR1Wr/ichOfjIA3Jgw2PapI31i0GqeMd66
   852  U1+lC9FeyMAJpuSVp/SoiYzYo+79SFcVoM2yw3yAnIKg7q9GLYYqzncdykT6C06c
   853  15gWFI6igmReAsD9ITSvYh0jLrLHfEYcPTOD3ZXJ4EwwHtWSoO3gq1EAtOYKu/Lv
   854  C8zfBsZcFdsHvsSiYeBU8Oioe42mguky3Ax9O7D805Ek6R68ra07MW/G4YxvV7IN
   855  2BfSaYy8MX9IG0ZMIOcoc0FeF5xkFmJ7kdrlTaJzC0IE9PNxNaH5QnOAFB8vxHcO
   856  FioUxb6UKdHcPLR1VZtAdTdTMjSJxUqD/35Cdfqs7oDJXz8f6TXO2Tdy6G++YUs9
   857  qsGZWxzFvvkXUkQSl0dQQ5jO/FtUJcAVXVVp20LxPemfatAHpW31WdJYeWSQWky2
   858  +f9b5TXKXVyjlUL7uHxowWrT2AtTchDH22wTEtqLEF9Z3Q==
   859  -----END CERTIFICATE-----`
   860  
   861  // openssl req -newkey rsa:2048 -keyout test.key -sha256 -sigopt \
   862  // rsa_padding_mode:pss -sigopt rsa_pss_saltlen:32 -sigopt rsa_mgf1_md:sha256 \
   863  // -x509 -days 3650 -nodes -subj '/C=US/ST=CA/L=SF/O=Test/CN=Test' -out \
   864  // test.pem
   865  var rsaPSSSelfSignedOpenSSL110PEM = `-----BEGIN CERTIFICATE-----
   866  MIIDwDCCAnigAwIBAgIJAM9LAMHTE5xpMD0GCSqGSIb3DQEBCjAwoA0wCwYJYIZI
   867  AWUDBAIBoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFlAwQCAaIDAgEgMEUxCzAJBgNV
   868  BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDTALBgNVBAoMBFRlc3Qx
   869  DTALBgNVBAMMBFRlc3QwHhcNMTgwMjIyMjIxMzE4WhcNMjgwMjIwMjIxMzE4WjBF
   870  MQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExCzAJBgNVBAcMAlNGMQ0wCwYDVQQK
   871  DARUZXN0MQ0wCwYDVQQDDARUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
   872  CgKCAQEA4Zrsydod+GoTAJLLutWNF87qhhVPBsK1zB1Gj+NAAe4+VbrZ1E41H1wp
   873  qITx7DA8DRtJEf+NqrTAnAdZWBG/tAOA5LfXVax0ZSQtLnYLSeylLoMtDyY3eFAj
   874  TmuTOoyVy6raktowCnHCh01NsstqqTfrx6SbmzOmDmKTkq/I+7K0MCVsn41xRDVM
   875  +ShD0WGFGioEGoiWnFSWupxJDA3Q6jIDEygVwNKHwnhv/2NgG2kqZzrZSQA67en0
   876  iKAXtoDNPpmyD5oS9YbEJ+2Nbm7oLeON30i6kZvXKIzJXx+UWViazHZqnsi5rQ8G
   877  RHF+iVFXsqd0MzDKmkKOT5FDhrsbKQIDAQABo1MwUTAdBgNVHQ4EFgQU9uFY/nlg
   878  gLH00NBnr/o7QvpN9ugwHwYDVR0jBBgwFoAU9uFY/nlggLH00NBnr/o7QvpN9ugw
   879  DwYDVR0TAQH/BAUwAwEB/zA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAaEa
   880  MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgGiAwIBIAOCAQEAhJzpwxBNGKvzKWDe
   881  WLqv6RMrl/q4GcH3b7M9wjxe0yOm4F+Tb2zJ7re4h+D39YkJf8cX1NV9UQVu6z4s
   882  Fvo2kmlR0qZOXAg5augmCQ1xS0WHFoF6B52anNzHkZQbAIYJ3kGoFsUHzs7Sz7F/
   883  656FsRpHA9UzJQ3avPPMrA4Y4aoJ7ANJ6XIwTrdWrhULOVuvYRLCl4CdTVztVFX6
   884  wxX8nS1ISYd8jXPUMgsBKVbWufvLoIymMJW8CZbpprVZel5zFn0bmPrON8IHS30w
   885  Gs+ITJjKEnZgXmAQ25SLKVzkZkBcGANs2GsdHNJ370Puisy0FIPD2NXR5uASAf7J
   886  +w9fjQ==
   887  -----END CERTIFICATE-----`
   888  
   889  func TestRSAPSSSelfSigned(t *testing.T) {
   890  	for i, pemBlock := range []string{rsaPSSSelfSignedPEM, rsaPSSSelfSignedOpenSSL110PEM} {
   891  		der, _ := pem.Decode([]byte(pemBlock))
   892  		if der == nil {
   893  			t.Errorf("#%d: failed to find PEM block", i)
   894  			continue
   895  		}
   896  
   897  		cert, err := ParseCertificate(der.Bytes)
   898  		if err != nil {
   899  			t.Errorf("#%d: failed to parse: %s", i, err)
   900  			continue
   901  		}
   902  
   903  		if err = cert.CheckSignatureFrom(cert); err != nil {
   904  			t.Errorf("#%d: signature check failed: %s", i, err)
   905  			continue
   906  		}
   907  	}
   908  }
   909  
   910  const ed25519Certificate = `
   911  Certificate:
   912      Data:
   913          Version: 3 (0x2)
   914          Serial Number:
   915              0c:83:d8:21:2b:82:cb:23:98:23:63:e2:f7:97:8a:43:5b:f3:bd:92
   916          Signature Algorithm: ED25519
   917          Issuer: CN = Ed25519 test certificate
   918          Validity
   919              Not Before: May  6 17:27:16 2019 GMT
   920              Not After : Jun  5 17:27:16 2019 GMT
   921          Subject: CN = Ed25519 test certificate
   922          Subject Public Key Info:
   923              Public Key Algorithm: ED25519
   924                  ED25519 Public-Key:
   925                  pub:
   926                      36:29:c5:6c:0d:4f:14:6c:81:d0:ff:75:d3:6a:70:
   927                      5f:69:cd:0f:4d:66:d5:da:98:7e:82:49:89:a3:8a:
   928                      3c:fa
   929          X509v3 extensions:
   930              X509v3 Subject Key Identifier:
   931                  09:3B:3A:9D:4A:29:D8:95:FF:68:BE:7B:43:54:72:E0:AD:A2:E3:AE
   932              X509v3 Authority Key Identifier:
   933                  keyid:09:3B:3A:9D:4A:29:D8:95:FF:68:BE:7B:43:54:72:E0:AD:A2:E3:AE
   934              X509v3 Basic Constraints: critical
   935                  CA:TRUE
   936      Signature Algorithm: ED25519
   937           53:a5:58:1c:2c:3b:2a:9e:ac:9d:4e:a5:1d:5f:5d:6d:a6:b5:
   938           08:de:12:82:f3:97:20:ae:fa:d8:98:f4:1a:83:32:6b:91:f5:
   939           24:1d:c4:20:7f:2c:e2:4d:da:13:3b:6d:54:1a:d2:a8:28:dc:
   940           60:b9:d4:f4:78:4b:3c:1c:91:00
   941  -----BEGIN CERTIFICATE-----
   942  MIIBWzCCAQ2gAwIBAgIUDIPYISuCyyOYI2Pi95eKQ1vzvZIwBQYDK2VwMCMxITAf
   943  BgNVBAMMGEVkMjU1MTkgdGVzdCBjZXJ0aWZpY2F0ZTAeFw0xOTA1MDYxNzI3MTZa
   944  Fw0xOTA2MDUxNzI3MTZaMCMxITAfBgNVBAMMGEVkMjU1MTkgdGVzdCBjZXJ0aWZp
   945  Y2F0ZTAqMAUGAytlcAMhADYpxWwNTxRsgdD/ddNqcF9pzQ9NZtXamH6CSYmjijz6
   946  o1MwUTAdBgNVHQ4EFgQUCTs6nUop2JX/aL57Q1Ry4K2i464wHwYDVR0jBBgwFoAU
   947  CTs6nUop2JX/aL57Q1Ry4K2i464wDwYDVR0TAQH/BAUwAwEB/zAFBgMrZXADQQBT
   948  pVgcLDsqnqydTqUdX11tprUI3hKC85cgrvrYmPQagzJrkfUkHcQgfyziTdoTO21U
   949  GtKoKNxgudT0eEs8HJEA
   950  -----END CERTIFICATE-----`
   951  
   952  func TestEd25519SelfSigned(t *testing.T) {
   953  	der, _ := pem.Decode([]byte(ed25519Certificate))
   954  	if der == nil {
   955  		t.Fatalf("Failed to find PEM block")
   956  	}
   957  
   958  	cert, err := ParseCertificate(der.Bytes)
   959  	if err != nil {
   960  		t.Fatalf("Failed to parse: %s", err)
   961  	}
   962  
   963  	if cert.PublicKeyAlgorithm != Ed25519 {
   964  		t.Fatalf("Parsed key algorithm was not Ed25519")
   965  	}
   966  	parsedKey, ok := cert.PublicKey.(ed25519.PublicKey)
   967  	if !ok {
   968  		t.Fatalf("Parsed key was not an Ed25519 key: %s", err)
   969  	}
   970  	if len(parsedKey) != ed25519.PublicKeySize {
   971  		t.Fatalf("Invalid Ed25519 key")
   972  	}
   973  
   974  	if err = cert.CheckSignatureFrom(cert); err != nil {
   975  		t.Fatalf("Signature check failed: %s", err)
   976  	}
   977  }
   978  
   979  const pemCertificate = `-----BEGIN CERTIFICATE-----
   980  MIIDATCCAemgAwIBAgIRAKQkkrFx1T/dgB/Go/xBM5swDQYJKoZIhvcNAQELBQAw
   981  EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xNjA4MTcyMDM2MDdaFw0xNzA4MTcyMDM2
   982  MDdaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
   983  ggEKAoIBAQDAoJtjG7M6InsWwIo+l3qq9u+g2rKFXNu9/mZ24XQ8XhV6PUR+5HQ4
   984  jUFWC58ExYhottqK5zQtKGkw5NuhjowFUgWB/VlNGAUBHtJcWR/062wYrHBYRxJH
   985  qVXOpYKbIWwFKoXu3hcpg/CkdOlDWGKoZKBCwQwUBhWE7MDhpVdQ+ZljUJWL+FlK
   986  yQK5iRsJd5TGJ6VUzLzdT4fmN2DzeK6GLeyMpVpU3sWV90JJbxWQ4YrzkKzYhMmB
   987  EcpXTG2wm+ujiHU/k2p8zlf8Sm7VBM/scmnMFt0ynNXop4FWvJzEm1G0xD2t+e2I
   988  5Utr04dOZPCgkm++QJgYhtZvgW7ZZiGTAgMBAAGjUjBQMA4GA1UdDwEB/wQEAwIF
   989  oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBsGA1UdEQQUMBKC
   990  EHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEBADpqKQxrthH5InC7
   991  X96UP0OJCu/lLEMkrjoEWYIQaFl7uLPxKH5AmQPH4lYwF7u7gksR7owVG9QU9fs6
   992  1fK7II9CVgCd/4tZ0zm98FmU4D0lHGtPARrrzoZaqVZcAvRnFTlPX5pFkPhVjjai
   993  /mkxX9LpD8oK1445DFHxK5UjLMmPIIWd8EOi+v5a+hgGwnJpoW7hntSl8kHMtTmy
   994  fnnktsblSUV4lRCit0ymC7Ojhe+gzCCwkgs5kDzVVag+tnl/0e2DloIjASwOhpbH
   995  KVcg7fBd484ht/sS+l0dsB4KDOSpd8JzVDMF8OZqlaydizoJO0yWr9GbCN1+OKq5
   996  EhLrEqU=
   997  -----END CERTIFICATE-----`
   998  
   999  const ed25519CRLCertificate = `
  1000  Certificate:
  1001  Data:
  1002  	Version: 3 (0x2)
  1003  	Serial Number:
  1004  		7a:07:a0:9d:14:04:16:fc:1f:d8:e5:fe:d1:1d:1f:8d
  1005  	Signature Algorithm: ED25519
  1006  	Issuer: CN = Ed25519 CRL Test CA
  1007  	Validity
  1008  		Not Before: Oct 30 01:20:20 2019 GMT
  1009  		Not After : Dec 31 23:59:59 9999 GMT
  1010  	Subject: CN = Ed25519 CRL Test CA
  1011  	Subject Public Key Info:
  1012  		Public Key Algorithm: ED25519
  1013  			ED25519 Public-Key:
  1014  			pub:
  1015  				95:73:3b:b0:06:2a:31:5a:b6:a7:a6:6e:ef:71:df:
  1016  				ac:6f:6b:39:03:85:5e:63:4b:f8:a6:0f:68:c6:6f:
  1017  				75:21
  1018  	X509v3 extensions:
  1019  		X509v3 Key Usage: critical
  1020  			Digital Signature, Certificate Sign, CRL Sign
  1021  		X509v3 Extended Key Usage: 
  1022  			TLS Web Client Authentication, TLS Web Server Authentication, OCSP Signing
  1023  		X509v3 Basic Constraints: critical
  1024  			CA:TRUE
  1025  		X509v3 Subject Key Identifier: 
  1026  			B7:17:DA:16:EA:C5:ED:1F:18:49:44:D3:D2:E3:A0:35:0A:81:93:60
  1027  		X509v3 Authority Key Identifier: 
  1028  			keyid:B7:17:DA:16:EA:C5:ED:1F:18:49:44:D3:D2:E3:A0:35:0A:81:93:60
  1029  Signature Algorithm: ED25519
  1030  	 fc:3e:14:ea:bb:70:c2:6f:38:34:70:bc:c8:a7:f4:7c:0d:1e:
  1031  	 28:d7:2a:9f:22:8a:45:e8:02:76:84:1e:2d:64:2d:1e:09:b5:
  1032  	 29:71:1f:95:8a:4e:79:87:51:60:9a:e7:86:40:f6:60:c7:d1:
  1033  	 ee:68:76:17:1d:90:cc:92:93:07
  1034  -----BEGIN CERTIFICATE-----
  1035  MIIBijCCATygAwIBAgIQegegnRQEFvwf2OX+0R0fjTAFBgMrZXAwHjEcMBoGA1UE
  1036  AxMTRWQyNTUxOSBDUkwgVGVzdCBDQTAgFw0xOTEwMzAwMTIwMjBaGA85OTk5MTIz
  1037  MTIzNTk1OVowHjEcMBoGA1UEAxMTRWQyNTUxOSBDUkwgVGVzdCBDQTAqMAUGAytl
  1038  cAMhAJVzO7AGKjFatqembu9x36xvazkDhV5jS/imD2jGb3Uho4GNMIGKMA4GA1Ud
  1039  DwEB/wQEAwIBhjAnBgNVHSUEIDAeBggrBgEFBQcDAgYIKwYBBQUHAwEGCCsGAQUF
  1040  BwMJMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFLcX2hbqxe0fGElE09LjoDUK
  1041  gZNgMB8GA1UdIwQYMBaAFLcX2hbqxe0fGElE09LjoDUKgZNgMAUGAytlcANBAPw+
  1042  FOq7cMJvODRwvMin9HwNHijXKp8iikXoAnaEHi1kLR4JtSlxH5WKTnmHUWCa54ZA
  1043  9mDH0e5odhcdkMySkwc=
  1044  -----END CERTIFICATE-----`
  1045  
  1046  const ed25519CRLKey = `-----BEGIN PRIVATE KEY-----
  1047  MC4CAQAwBQYDK2VwBCIEINdKh2096vUBYu4EIFpjShsUSh3vimKya1sQ1YTT4RZG
  1048  -----END PRIVATE KEY-----`
  1049  
  1050  func TestCRLCreation(t *testing.T) {
  1051  	block, _ := pem.Decode([]byte(pemPrivateKey))
  1052  	privRSA, _ := x509.ParsePKCS1PrivateKey(block.Bytes)
  1053  	block, _ = pem.Decode([]byte(pemCertificate))
  1054  	certRSA, _ := ParseCertificate(block.Bytes)
  1055  
  1056  	block, _ = pem.Decode([]byte(ed25519CRLKey))
  1057  	privEd25519, _ := ParsePKCS8PrivateKey(block.Bytes)
  1058  	block, _ = pem.Decode([]byte(ed25519CRLCertificate))
  1059  	certEd25519, _ := ParseCertificate(block.Bytes)
  1060  
  1061  	tests := []struct {
  1062  		name string
  1063  		priv any
  1064  		cert *Certificate
  1065  	}{
  1066  		{"RSA CA", privRSA, certRSA},
  1067  		{"Ed25519 CA", privEd25519, certEd25519},
  1068  	}
  1069  
  1070  	loc := time.FixedZone("Oz/Atlantis", int((2 * time.Hour).Seconds()))
  1071  
  1072  	now := time.Unix(1000, 0).In(loc)
  1073  	nowUTC := now.UTC()
  1074  	expiry := time.Unix(10000, 0)
  1075  
  1076  	revokedCerts := []pkix.RevokedCertificate{
  1077  		{
  1078  			SerialNumber:   big.NewInt(1),
  1079  			RevocationTime: nowUTC,
  1080  		},
  1081  		{
  1082  			SerialNumber: big.NewInt(42),
  1083  			// RevocationTime should be converted to UTC before marshaling.
  1084  			RevocationTime: now,
  1085  		},
  1086  	}
  1087  	expectedCerts := []pkix.RevokedCertificate{
  1088  		{
  1089  			SerialNumber:   big.NewInt(1),
  1090  			RevocationTime: nowUTC,
  1091  		},
  1092  		{
  1093  			SerialNumber:   big.NewInt(42),
  1094  			RevocationTime: nowUTC,
  1095  		},
  1096  	}
  1097  
  1098  	for _, test := range tests {
  1099  		crlBytes, err := test.cert.CreateCRL(rand.Reader, test.priv, revokedCerts, now, expiry)
  1100  		if err != nil {
  1101  			t.Errorf("%s: error creating CRL: %s", test.name, err)
  1102  			continue
  1103  		}
  1104  
  1105  		parsedCRL, err := ParseDERCRL(crlBytes)
  1106  		if err != nil {
  1107  			t.Errorf("%s: error reparsing CRL: %s", test.name, err)
  1108  			continue
  1109  		}
  1110  		if !reflect.DeepEqual(parsedCRL.TBSCertList.RevokedCertificates, expectedCerts) {
  1111  			t.Errorf("%s: RevokedCertificates mismatch: got %v; want %v.", test.name,
  1112  				parsedCRL.TBSCertList.RevokedCertificates, expectedCerts)
  1113  		}
  1114  	}
  1115  }
  1116  
  1117  func fromBase64(in string) []byte {
  1118  	out := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
  1119  	n, err := base64.StdEncoding.Decode(out, []byte(in))
  1120  	if err != nil {
  1121  		panic("failed to base64 decode")
  1122  	}
  1123  	return out[:n]
  1124  }
  1125  
  1126  func TestParseDERCRL(t *testing.T) {
  1127  	derBytes := fromBase64(derCRLBase64)
  1128  	certList, err := ParseDERCRL(derBytes)
  1129  	if err != nil {
  1130  		t.Errorf("error parsing: %s", err)
  1131  		return
  1132  	}
  1133  	numCerts := len(certList.TBSCertList.RevokedCertificates)
  1134  	expected := 88
  1135  	if numCerts != expected {
  1136  		t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
  1137  	}
  1138  
  1139  	if certList.HasExpired(time.Unix(1302517272, 0)) {
  1140  		t.Errorf("CRL has expired (but shouldn't have)")
  1141  	}
  1142  
  1143  	// Can't check the signature here without a package cycle.
  1144  }
  1145  
  1146  func TestCRLWithoutExpiry(t *testing.T) {
  1147  	derBytes := fromBase64("MIHYMIGZMAkGByqGSM44BAMwEjEQMA4GA1UEAxMHQ2FybERTUxcNOTkwODI3MDcwMDAwWjBpMBMCAgDIFw05OTA4MjIwNzAwMDBaMBMCAgDJFw05OTA4MjIwNzAwMDBaMBMCAgDTFw05OTA4MjIwNzAwMDBaMBMCAgDSFw05OTA4MjIwNzAwMDBaMBMCAgDUFw05OTA4MjQwNzAwMDBaMAkGByqGSM44BAMDLwAwLAIUfmVSdjP+NHMX0feW+aDU2G1cfT0CFAJ6W7fVWxjBz4fvftok8yqDnDWh")
  1148  	certList, err := ParseDERCRL(derBytes)
  1149  	if err != nil {
  1150  		t.Fatal(err)
  1151  	}
  1152  	if !certList.TBSCertList.NextUpdate.IsZero() {
  1153  		t.Errorf("NextUpdate is not the zero value")
  1154  	}
  1155  }
  1156  
  1157  func TestParsePEMCRL(t *testing.T) {
  1158  	pemBytes := fromBase64(pemCRLBase64)
  1159  	certList, err := ParseCRL(pemBytes)
  1160  	if err != nil {
  1161  		t.Errorf("error parsing: %s", err)
  1162  		return
  1163  	}
  1164  	numCerts := len(certList.TBSCertList.RevokedCertificates)
  1165  	expected := 2
  1166  	if numCerts != expected {
  1167  		t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
  1168  	}
  1169  
  1170  	if certList.HasExpired(time.Unix(1302517272, 0)) {
  1171  		t.Errorf("CRL has expired (but shouldn't have)")
  1172  	}
  1173  
  1174  	// Can't check the signature here without a package cycle.
  1175  }
  1176  
  1177  const derCRLBase64 = "MIINqzCCDJMCAQEwDQYJKoZIhvcNAQEFBQAwVjEZMBcGA1UEAxMQUEtJIEZJTk1FQ0NBTklDQTEVMBMGA1UEChMMRklOTUVDQ0FOSUNBMRUwEwYDVQQLEwxGSU5NRUNDQU5JQ0ExCzAJBgNVBAYTAklUFw0xMTA1MDQxNjU3NDJaFw0xMTA1MDQyMDU3NDJaMIIMBzAhAg4Ze1od49Lt1qIXBydAzhcNMDkwNzE2MDg0MzIyWjAAMCECDl0HSL9bcZ1Ci/UHJ0DPFw0wOTA3MTYwODQzMTNaMAAwIQIOESB9tVAmX3cY7QcnQNAXDTA5MDcxNjA4NDUyMlowADAhAg4S1tGAQ3mHt8uVBydA1RcNMDkwODA0MTUyNTIyWjAAMCECDlQ249Y7vtC25ScHJ0DWFw0wOTA4MDQxNTI1MzdaMAAwIQIOISMop3NkA4PfYwcnQNkXDTA5MDgwNDExMDAzNFowADAhAg56/BMoS29KEShTBydA2hcNMDkwODA0MTEwMTAzWjAAMCECDnBp/22HPH5CSWoHJ0DbFw0wOTA4MDQxMDU0NDlaMAAwIQIOV9IP+8CD8bK+XAcnQNwXDTA5MDgwNDEwNTcxN1owADAhAg4v5aRz0IxWqYiXBydA3RcNMDkwODA0MTA1NzQ1WjAAMCECDlOU34VzvZAybQwHJ0DeFw0wOTA4MDQxMDU4MjFaMAAwIAINO4CD9lluIxcwBydBAxcNMDkwNzIyMTUzMTU5WjAAMCECDgOllfO8Y1QA7/wHJ0ExFw0wOTA3MjQxMTQxNDNaMAAwIQIOJBX7jbiCdRdyjgcnQUQXDTA5MDkxNjA5MzAwOFowADAhAg5iYSAgmDrlH/RZBydBRRcNMDkwOTE2MDkzMDE3WjAAMCECDmu6k6srP3jcMaQHJ0FRFw0wOTA4MDQxMDU2NDBaMAAwIQIOX8aHlO0V+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lCZ05WDQpIUmdFRVJnUE1qQXdNakV3TWpNeE5EVXdNVFJhb0RBd0xqQWZCZ05WSFNNRUdEQVdnQlQxVERGNlVRTS9MTmVMDQpsNWx2cUhHUXEzZzltekFMQmdOVkhSUUVCQUlDQUlRd0RRWUpLb1pJaHZjTkFRRUZCUUFEZ1lFQUZVNUFzNk16DQpxNVBSc2lmYW9iUVBHaDFhSkx5QytNczVBZ2MwYld5QTNHQWR4dXI1U3BQWmVSV0NCamlQL01FSEJXSkNsQkhQDQpHUmNxNXlJZDNFakRrYUV5eFJhK2k2N0x6dmhJNmMyOUVlNks5cFNZd2ppLzdSVWhtbW5Qclh0VHhsTDBsckxyDQptUVFKNnhoRFJhNUczUUE0Q21VZHNITnZicnpnbUNZcHZWRT0NCi0tLS0tRU5EIFg1MDkgQ1JMLS0tLS0NCg0K"
  1180  
  1181  func TestCreateCertificateRequest(t *testing.T) {
  1182  	random := rand.Reader
  1183  
  1184  	sm2Priv, err := sm2.GenerateKey(rand.Reader)
  1185  	if err != nil {
  1186  		t.Fatalf("Failed to generate SM2 key: %s", err)
  1187  	}
  1188  
  1189  	ecdsa256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1190  	if err != nil {
  1191  		t.Fatalf("Failed to generate ECDSA key: %s", err)
  1192  	}
  1193  
  1194  	ecdsa384Priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  1195  	if err != nil {
  1196  		t.Fatalf("Failed to generate ECDSA key: %s", err)
  1197  	}
  1198  
  1199  	ecdsa521Priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
  1200  	if err != nil {
  1201  		t.Fatalf("Failed to generate ECDSA key: %s", err)
  1202  	}
  1203  
  1204  	_, ed25519Priv, err := ed25519.GenerateKey(random)
  1205  	if err != nil {
  1206  		t.Fatalf("Failed to generate Ed25519 key: %s", err)
  1207  	}
  1208  
  1209  	tests := []struct {
  1210  		name    string
  1211  		priv    any
  1212  		sigAlgo SignatureAlgorithm
  1213  	}{
  1214  		{"RSA", testPrivateKey, SHA1WithRSA},
  1215  		{"SM2-256", sm2Priv, SM2WithSM3},
  1216  		{"ECDSA-256", ecdsa256Priv, ECDSAWithSHA1},
  1217  		{"ECDSA-384", ecdsa384Priv, ECDSAWithSHA1},
  1218  		{"ECDSA-521", ecdsa521Priv, ECDSAWithSHA1},
  1219  		{"Ed25519", ed25519Priv, PureEd25519},
  1220  	}
  1221  
  1222  	for _, test := range tests {
  1223  		template := x509.CertificateRequest{
  1224  			Subject: pkix.Name{
  1225  				CommonName:   "test.example.com",
  1226  				Organization: []string{"Σ Acme Co"},
  1227  			},
  1228  			SignatureAlgorithm: test.sigAlgo,
  1229  			DNSNames:           []string{"test.example.com"},
  1230  			EmailAddresses:     []string{"gopher@golang.org"},
  1231  			IPAddresses:        []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
  1232  		}
  1233  
  1234  		derBytes, err := CreateCertificateRequest(random, &template, test.priv)
  1235  		if err != nil {
  1236  			t.Errorf("%s: failed to create certificate request: %s", test.name, err)
  1237  			continue
  1238  		}
  1239  
  1240  		out, err := ParseCertificateRequest(derBytes)
  1241  		if err != nil {
  1242  			t.Errorf("%s: failed to parse certificate request: %s", test.name, err)
  1243  			continue
  1244  		}
  1245  
  1246  		err = out.CheckSignature()
  1247  		if err != nil {
  1248  			t.Errorf("%s: failed to check certificate request signature: %s", test.name, err)
  1249  			continue
  1250  		}
  1251  
  1252  		if out.Subject.CommonName != template.Subject.CommonName {
  1253  			t.Errorf("%s: output subject common name and template subject common name don't match", test.name)
  1254  		} else if len(out.Subject.Organization) != len(template.Subject.Organization) {
  1255  			t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name)
  1256  		} else if len(out.DNSNames) != len(template.DNSNames) {
  1257  			t.Errorf("%s: output DNS names and template DNS names don't match", test.name)
  1258  		} else if len(out.EmailAddresses) != len(template.EmailAddresses) {
  1259  			t.Errorf("%s: output email addresses and template email addresses don't match", test.name)
  1260  		} else if len(out.IPAddresses) != len(template.IPAddresses) {
  1261  			t.Errorf("%s: output IP addresses and template IP addresses names don't match", test.name)
  1262  		}
  1263  	}
  1264  }
  1265  
  1266  func marshalAndParseCSR(t *testing.T, template *x509.CertificateRequest) *CertificateRequest {
  1267  	t.Helper()
  1268  	derBytes, err := CreateCertificateRequest(rand.Reader, template, testPrivateKey)
  1269  	if err != nil {
  1270  		t.Fatal(err)
  1271  	}
  1272  
  1273  	csr, err := ParseCertificateRequest(derBytes)
  1274  	if err != nil {
  1275  		t.Fatal(err)
  1276  	}
  1277  
  1278  	return csr
  1279  }
  1280  
  1281  func TestCertificateRequestOverrides(t *testing.T) {
  1282  	sanContents, err := marshalSANs([]string{"foo.example.com"}, nil, nil, nil)
  1283  	if err != nil {
  1284  		t.Fatal(err)
  1285  	}
  1286  
  1287  	template := x509.CertificateRequest{
  1288  		Subject: pkix.Name{
  1289  			CommonName:   "test.example.com",
  1290  			Organization: []string{"Σ Acme Co"},
  1291  		},
  1292  		DNSNames: []string{"test.example.com"},
  1293  
  1294  		// An explicit extension should override the DNSNames from the
  1295  		// template.
  1296  		ExtraExtensions: []pkix.Extension{
  1297  			{
  1298  				Id:       oidExtensionSubjectAltName,
  1299  				Value:    sanContents,
  1300  				Critical: true,
  1301  			},
  1302  		},
  1303  	}
  1304  
  1305  	csr := marshalAndParseCSR(t, &template)
  1306  
  1307  	if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo.example.com" {
  1308  		t.Errorf("Extension did not override template. Got %v\n", csr.DNSNames)
  1309  	}
  1310  
  1311  	if len(csr.Extensions) != 1 || !csr.Extensions[0].Id.Equal(oidExtensionSubjectAltName) || !csr.Extensions[0].Critical {
  1312  		t.Errorf("SAN extension was not faithfully copied, got %#v", csr.Extensions)
  1313  	}
  1314  
  1315  	// If there is already an attribute with X.509 extensions then the
  1316  	// extra extensions should be added to it rather than creating a CSR
  1317  	// with two extension attributes.
  1318  
  1319  	template.Attributes = []pkix.AttributeTypeAndValueSET{
  1320  		{
  1321  			Type: oidExtensionRequest,
  1322  			Value: [][]pkix.AttributeTypeAndValue{
  1323  				{
  1324  					{
  1325  						Type:  oidExtensionAuthorityInfoAccess,
  1326  						Value: []byte("foo"),
  1327  					},
  1328  				},
  1329  			},
  1330  		},
  1331  	}
  1332  
  1333  	csr = marshalAndParseCSR(t, &template)
  1334  	if l := len(csr.Attributes); l != 1 {
  1335  		t.Errorf("incorrect number of attributes: %d\n", l)
  1336  	}
  1337  
  1338  	if !csr.Attributes[0].Type.Equal(oidExtensionRequest) ||
  1339  		len(csr.Attributes[0].Value) != 1 ||
  1340  		len(csr.Attributes[0].Value[0]) != 2 {
  1341  		t.Errorf("bad attributes: %#v\n", csr.Attributes)
  1342  	}
  1343  
  1344  	sanContents2, err := marshalSANs([]string{"foo2.example.com"}, nil, nil, nil)
  1345  	if err != nil {
  1346  		t.Fatal(err)
  1347  	}
  1348  
  1349  	// Extensions in Attributes should override those in ExtraExtensions.
  1350  	template.Attributes[0].Value[0] = append(template.Attributes[0].Value[0], pkix.AttributeTypeAndValue{
  1351  		Type:  oidExtensionSubjectAltName,
  1352  		Value: sanContents2,
  1353  	})
  1354  
  1355  	csr = marshalAndParseCSR(t, &template)
  1356  
  1357  	if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo2.example.com" {
  1358  		t.Errorf("Attributes did not override ExtraExtensions. Got %v\n", csr.DNSNames)
  1359  	}
  1360  }
  1361  
  1362  func TestParseCertificateRequest(t *testing.T) {
  1363  	for _, csrBase64 := range csrBase64Array {
  1364  		csrBytes := fromBase64(csrBase64)
  1365  		csr, err := ParseCertificateRequest(csrBytes)
  1366  		if err != nil {
  1367  			t.Fatalf("failed to parse CSR: %s", err)
  1368  		}
  1369  
  1370  		if len(csr.EmailAddresses) != 1 || csr.EmailAddresses[0] != "gopher@golang.org" {
  1371  			t.Errorf("incorrect email addresses found: %v", csr.EmailAddresses)
  1372  		}
  1373  
  1374  		if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "test.example.com" {
  1375  			t.Errorf("incorrect DNS names found: %v", csr.DNSNames)
  1376  		}
  1377  
  1378  		if len(csr.Subject.Country) != 1 || csr.Subject.Country[0] != "AU" {
  1379  			t.Errorf("incorrect Subject name: %v", csr.Subject)
  1380  		}
  1381  
  1382  		found := false
  1383  		for _, e := range csr.Extensions {
  1384  			if e.Id.Equal(oidExtensionBasicConstraints) {
  1385  				found = true
  1386  				break
  1387  			}
  1388  		}
  1389  		if !found {
  1390  			t.Errorf("basic constraints extension not found in CSR")
  1391  		}
  1392  	}
  1393  }
  1394  
  1395  func TestCriticalFlagInCSRRequestedExtensions(t *testing.T) {
  1396  	// This CSR contains an extension request where the extensions have a
  1397  	// critical flag in them. In the past we failed to handle this.
  1398  	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="
  1399  
  1400  	csrBytes := fromBase64(csrBase64)
  1401  	csr, err := ParseCertificateRequest(csrBytes)
  1402  	if err != nil {
  1403  		t.Fatalf("failed to parse CSR: %s", err)
  1404  	}
  1405  
  1406  	expected := []struct {
  1407  		Id    asn1.ObjectIdentifier
  1408  		Value []byte
  1409  	}{
  1410  		{oidExtensionBasicConstraints, fromBase64("MAYBAf8CAQA=")},
  1411  		{oidExtensionKeyUsage, fromBase64("AwIChA==")},
  1412  	}
  1413  
  1414  	if n := len(csr.Extensions); n != len(expected) {
  1415  		t.Fatalf("expected to find %d extensions but found %d", len(expected), n)
  1416  	}
  1417  
  1418  	for i, extension := range csr.Extensions {
  1419  		if !extension.Id.Equal(expected[i].Id) {
  1420  			t.Fatalf("extension #%d has unexpected type %v (expected %v)", i, extension.Id, expected[i].Id)
  1421  		}
  1422  
  1423  		if !bytes.Equal(extension.Value, expected[i].Value) {
  1424  			t.Fatalf("extension #%d has unexpected contents %x (expected %x)", i, extension.Value, expected[i].Value)
  1425  		}
  1426  	}
  1427  }
  1428  
  1429  // serialiseAndParse generates a self-signed certificate from template and
  1430  // returns a parsed version of it.
  1431  func serialiseAndParse(t *testing.T, template *x509.Certificate) *Certificate {
  1432  	t.Helper()
  1433  	derBytes, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey)
  1434  	if err != nil {
  1435  		t.Fatalf("failed to create certificate: %s", err)
  1436  		return nil
  1437  	}
  1438  
  1439  	cert, err := ParseCertificate(derBytes)
  1440  	if err != nil {
  1441  		t.Fatalf("failed to parse certificate: %s", err)
  1442  		return nil
  1443  	}
  1444  
  1445  	return cert
  1446  }
  1447  
  1448  func TestMaxPathLenNotCA(t *testing.T) {
  1449  	template := &x509.Certificate{
  1450  		SerialNumber: big.NewInt(1),
  1451  		Subject: pkix.Name{
  1452  			CommonName: "Σ Acme Co",
  1453  		},
  1454  		NotBefore: time.Unix(1000, 0),
  1455  		NotAfter:  time.Unix(100000, 0),
  1456  
  1457  		BasicConstraintsValid: true,
  1458  		IsCA:                  false,
  1459  	}
  1460  	if m := serialiseAndParse(t, template).MaxPathLen; m != -1 {
  1461  		t.Errorf("MaxPathLen should be -1 when IsCa is false, got %d", m)
  1462  	}
  1463  
  1464  	template.MaxPathLen = -1
  1465  	if m := serialiseAndParse(t, template).MaxPathLen; m != -1 {
  1466  		t.Errorf("MaxPathLen should be -1 when IsCa is false and MaxPathLen set to -1, got %d", m)
  1467  	}
  1468  
  1469  	template.MaxPathLen = 5
  1470  	if _, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey); err == nil {
  1471  		t.Error("specifying a MaxPathLen when IsCA is false should fail")
  1472  	}
  1473  
  1474  	template.MaxPathLen = 0
  1475  	template.MaxPathLenZero = true
  1476  	if _, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey); err == nil {
  1477  		t.Error("setting MaxPathLenZero when IsCA is false should fail")
  1478  	}
  1479  
  1480  	template.BasicConstraintsValid = false
  1481  	if m := serialiseAndParse(t, template).MaxPathLen; m != 0 {
  1482  		t.Errorf("Bad MaxPathLen should be ignored if BasicConstraintsValid is false, got %d", m)
  1483  	}
  1484  }
  1485  
  1486  func TestMaxPathLen(t *testing.T) {
  1487  	template := &x509.Certificate{
  1488  		SerialNumber: big.NewInt(1),
  1489  		Subject: pkix.Name{
  1490  			CommonName: "Σ Acme Co",
  1491  		},
  1492  		NotBefore: time.Unix(1000, 0),
  1493  		NotAfter:  time.Unix(100000, 0),
  1494  
  1495  		BasicConstraintsValid: true,
  1496  		IsCA:                  true,
  1497  	}
  1498  
  1499  	cert1 := serialiseAndParse(t, template)
  1500  	if m := cert1.MaxPathLen; m != -1 {
  1501  		t.Errorf("Omitting MaxPathLen didn't turn into -1, got %d", m)
  1502  	}
  1503  	if cert1.MaxPathLenZero {
  1504  		t.Errorf("Omitting MaxPathLen resulted in MaxPathLenZero")
  1505  	}
  1506  
  1507  	template.MaxPathLen = 1
  1508  	cert2 := serialiseAndParse(t, template)
  1509  	if m := cert2.MaxPathLen; m != 1 {
  1510  		t.Errorf("Setting MaxPathLen didn't work. Got %d but set 1", m)
  1511  	}
  1512  	if cert2.MaxPathLenZero {
  1513  		t.Errorf("Setting MaxPathLen resulted in MaxPathLenZero")
  1514  	}
  1515  
  1516  	template.MaxPathLen = 0
  1517  	template.MaxPathLenZero = true
  1518  	cert3 := serialiseAndParse(t, template)
  1519  	if m := cert3.MaxPathLen; m != 0 {
  1520  		t.Errorf("Setting MaxPathLenZero didn't work, got %d", m)
  1521  	}
  1522  	if !cert3.MaxPathLenZero {
  1523  		t.Errorf("Setting MaxPathLen to zero didn't result in MaxPathLenZero")
  1524  	}
  1525  }
  1526  
  1527  func TestNoAuthorityKeyIdInSelfSignedCert(t *testing.T) {
  1528  	template := &x509.Certificate{
  1529  		SerialNumber: big.NewInt(1),
  1530  		Subject: pkix.Name{
  1531  			CommonName: "Σ Acme Co",
  1532  		},
  1533  		NotBefore: time.Unix(1000, 0),
  1534  		NotAfter:  time.Unix(100000, 0),
  1535  
  1536  		BasicConstraintsValid: true,
  1537  		IsCA:                  true,
  1538  		SubjectKeyId:          []byte{1, 2, 3, 4},
  1539  	}
  1540  
  1541  	if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) != 0 {
  1542  		t.Fatalf("self-signed certificate contained default authority key id")
  1543  	}
  1544  
  1545  	template.AuthorityKeyId = []byte{1, 2, 3, 4}
  1546  	if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) == 0 {
  1547  		t.Fatalf("self-signed certificate erased explicit authority key id")
  1548  	}
  1549  }
  1550  
  1551  func TestNoSubjectKeyIdInCert(t *testing.T) {
  1552  	template := &x509.Certificate{
  1553  		SerialNumber: big.NewInt(1),
  1554  		Subject: pkix.Name{
  1555  			CommonName: "Σ Acme Co",
  1556  		},
  1557  		NotBefore: time.Unix(1000, 0),
  1558  		NotAfter:  time.Unix(100000, 0),
  1559  
  1560  		BasicConstraintsValid: true,
  1561  		IsCA:                  true,
  1562  	}
  1563  	if cert := serialiseAndParse(t, template); len(cert.SubjectKeyId) == 0 {
  1564  		t.Fatalf("self-signed certificate did not generate subject key id using the public key")
  1565  	}
  1566  
  1567  	template.IsCA = false
  1568  	if cert := serialiseAndParse(t, template); len(cert.SubjectKeyId) != 0 {
  1569  		t.Fatalf("self-signed certificate generated subject key id when it isn't a CA")
  1570  	}
  1571  
  1572  	template.SubjectKeyId = []byte{1, 2, 3, 4}
  1573  	if cert := serialiseAndParse(t, template); len(cert.SubjectKeyId) == 0 {
  1574  		t.Fatalf("self-signed certificate erased explicit subject key id")
  1575  	}
  1576  }
  1577  
  1578  func TestASN1BitLength(t *testing.T) {
  1579  	tests := []struct {
  1580  		bytes  []byte
  1581  		bitLen int
  1582  	}{
  1583  		{nil, 0},
  1584  		{[]byte{0x00}, 0},
  1585  		{[]byte{0x00, 0x00}, 0},
  1586  		{[]byte{0xf0}, 4},
  1587  		{[]byte{0x88}, 5},
  1588  		{[]byte{0xff}, 8},
  1589  		{[]byte{0xff, 0x80}, 9},
  1590  		{[]byte{0xff, 0x81}, 16},
  1591  	}
  1592  
  1593  	for i, test := range tests {
  1594  		if got := asn1BitLength(test.bytes); got != test.bitLen {
  1595  			t.Errorf("#%d: calculated bit-length of %d for %x, wanted %d", i, got, test.bytes, test.bitLen)
  1596  		}
  1597  	}
  1598  }
  1599  
  1600  func TestVerifyEmptyCertificate(t *testing.T) {
  1601  	if _, err := new(Certificate).Verify(VerifyOptions{}); err != errNotParsed {
  1602  		t.Errorf("Verifying empty certificate resulted in unexpected error: %q (wanted %q)", err, errNotParsed)
  1603  	}
  1604  }
  1605  
  1606  /*
  1607  func TestInsecureAlgorithmErrorString(t *testing.T) {
  1608  	tests := []struct {
  1609  		sa   SignatureAlgorithm
  1610  		want string
  1611  	}{
  1612  		{MD5WithRSA, "x509: cannot verify signature: insecure algorithm MD5-RSA"},
  1613  		{SHA1WithRSA, "x509: cannot verify signature: insecure algorithm SHA1-RSA (temporarily override with GODEBUG=x509sha1=1)"},
  1614  		{ECDSAWithSHA1, "x509: cannot verify signature: insecure algorithm ECDSA-SHA1 (temporarily override with GODEBUG=x509sha1=1)"},
  1615  		{MD2WithRSA, "x509: cannot verify signature: insecure algorithm MD2-RSA"},
  1616  		{-1, "x509: cannot verify signature: insecure algorithm -1"},
  1617  		{0, "x509: cannot verify signature: insecure algorithm 0"},
  1618  		{9999, "x509: cannot verify signature: insecure algorithm 9999"},
  1619  	}
  1620  	for i, tt := range tests {
  1621  		if got := fmt.Sprint(x509.InsecureAlgorithmError(tt.sa)); got != tt.want {
  1622  			t.Errorf("%d. mismatch.\n got: %s\nwant: %s\n", i, got, tt.want)
  1623  		}
  1624  	}
  1625  }
  1626  */
  1627  
  1628  // These CSR was generated with OpenSSL:
  1629  //  openssl req -out CSR.csr -new -sha256 -nodes -keyout privateKey.key -config openssl.cnf
  1630  //
  1631  // With openssl.cnf containing the following sections:
  1632  //   [ v3_req ]
  1633  //   basicConstraints = CA:FALSE
  1634  //   keyUsage = nonRepudiation, digitalSignature, keyEncipherment
  1635  //   subjectAltName = email:gopher@golang.org,DNS:test.example.com
  1636  //   [ req_attributes ]
  1637  //   challengePassword = ignored challenge
  1638  //   unstructuredName  = ignored unstructured name
  1639  var csrBase64Array = [...]string{
  1640  	// Just [ v3_req ]
  1641  	"MIIDHDCCAgQCAQAwfjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVB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jwRM4gIRHFHPeAAE9D9YAoqdIvj/iFm/eQ++7DP8MDwOZWsXeB6jjwHuLmkQ==",
  1644  }
  1645  
  1646  var md5cert = `
  1647  -----BEGIN CERTIFICATE-----
  1648  MIIB4TCCAUoCCQCfmw3vMgPS5TANBgkqhkiG9w0BAQQFADA1MQswCQYDVQQGEwJB
  1649  VTETMBEGA1UECBMKU29tZS1TdGF0ZTERMA8GA1UEChMITUQ1IEluYy4wHhcNMTUx
  1650  MjAzMTkyOTMyWhcNMjkwODEyMTkyOTMyWjA1MQswCQYDVQQGEwJBVTETMBEGA1UE
  1651  CBMKU29tZS1TdGF0ZTERMA8GA1UEChMITUQ1IEluYy4wgZ8wDQYJKoZIhvcNAQEB
  1652  BQADgY0AMIGJAoGBANrq2nhLQj5mlXbpVX3QUPhfEm/vdEqPkoWtR/jRZIWm4WGf
  1653  Wpq/LKHJx2Pqwn+t117syN8l4U5unyAi1BJSXjBwPZNd7dXjcuJ+bRLV7FZ/iuvs
  1654  cfYyQQFTxan4TaJMd0x1HoNDbNbjHa02IyjjYE/r3mb/PIg+J2t5AZEh80lPAgMB
  1655  AAEwDQYJKoZIhvcNAQEEBQADgYEAjGzp3K3ey/YfKHohf33yHHWd695HQxDAP+wY
  1656  cs9/TAyLR+gJzJP7d18EcDDLJWVi7bhfa4EAD86di05azOh9kWSn4b3o9QYRGCSw
  1657  GNnI3Zk0cwNKA49hZntKKiy22DhRk7JAHF01d6Bu3KkHkmENrtJ+zj/+159WAnUa
  1658  qViorq4=
  1659  -----END CERTIFICATE-----
  1660  `
  1661  
  1662  func TestMD5(t *testing.T) {
  1663  	pemBlock, _ := pem.Decode([]byte(md5cert))
  1664  	cert, err := ParseCertificate(pemBlock.Bytes)
  1665  	if err != nil {
  1666  		t.Fatalf("failed to parse certificate: %s", err)
  1667  	}
  1668  	if sa := cert.SignatureAlgorithm; sa != MD5WithRSA {
  1669  		t.Errorf("signature algorithm is %v, want %v", sa, MD5WithRSA)
  1670  	}
  1671  	if err = cert.CheckSignatureFrom(cert); err == nil {
  1672  		t.Fatalf("certificate verification succeeded incorrectly")
  1673  	}
  1674  	if _, ok := err.(x509.InsecureAlgorithmError); !ok {
  1675  		t.Fatalf("certificate verification returned %v (%T), wanted InsecureAlgorithmError", err, err)
  1676  	}
  1677  }
  1678  
  1679  func TestSHA1(t *testing.T) {
  1680  	pemBlock, _ := pem.Decode([]byte(ecdsaSHA1CertPem))
  1681  	cert, err := ParseCertificate(pemBlock.Bytes)
  1682  	if err != nil {
  1683  		t.Fatalf("failed to parse certificate: %s", err)
  1684  	}
  1685  	if sa := cert.SignatureAlgorithm; sa != ECDSAWithSHA1 {
  1686  		t.Errorf("signature algorithm is %v, want %v", sa, ECDSAWithSHA1)
  1687  	}
  1688  	if !debugAllowSHA1 {
  1689  		if err = cert.CheckSignatureFrom(cert); err == nil {
  1690  			t.Fatalf("certificate verification succeeded incorrectly")
  1691  		}
  1692  		if _, ok := err.(x509.InsecureAlgorithmError); !ok {
  1693  			t.Fatalf("certificate verification returned %v (%T), wanted InsecureAlgorithmError", err, err)
  1694  		}
  1695  
  1696  		defer func(old bool) { debugAllowSHA1 = old }(debugAllowSHA1)
  1697  		debugAllowSHA1 = true
  1698  	}
  1699  	if err = cert.CheckSignatureFrom(cert); err != nil {
  1700  		t.Fatalf("SHA-1 certificate did not verify with GODEBUG=x509sha1=1: %v", err)
  1701  	}
  1702  
  1703  }
  1704  
  1705  // certMissingRSANULL contains an RSA public key where the AlgorithmIdentifier
  1706  // parameters are omitted rather than being an ASN.1 NULL.
  1707  const certMissingRSANULL = `
  1708  -----BEGIN CERTIFICATE-----
  1709  MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD
  1710  bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4
  1711  MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc
  1712  MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG
  1713  hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE
  1714  ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e
  1715  E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw
  1716  DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A
  1717  p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4
  1718  hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE
  1719  GFGNEH5PlGffo05wc46QkYU=
  1720  -----END CERTIFICATE-----`
  1721  
  1722  func TestRSAMissingNULLParameters(t *testing.T) {
  1723  	block, _ := pem.Decode([]byte(certMissingRSANULL))
  1724  	if _, err := ParseCertificate(block.Bytes); err == nil {
  1725  		t.Error("unexpected success when parsing certificate with missing RSA NULL parameter")
  1726  	} else if !strings.Contains(err.Error(), "missing NULL") {
  1727  		t.Errorf("unrecognised error when parsing certificate with missing RSA NULL parameter: %s", err)
  1728  	}
  1729  }
  1730  
  1731  const certISOOID = `
  1732  -----BEGIN CERTIFICATE-----
  1733  MIIB5TCCAVKgAwIBAgIQtwyL3RPWV7dJQp34HwZG9DAJBgUrDgMCHQUAMBExDzAN
  1734  BgNVBAMTBm15dGVzdDAeFw0xNjA4MDkyMjExMDVaFw0zOTEyMzEyMzU5NTlaMBEx
  1735  DzANBgNVBAMTBm15dGVzdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArzIH
  1736  GsyDB3ohIGkkvijF2PTRUX1bvOtY1eUUpjwHyu0twpAKSuaQv2Ha+/63+aHe8O86
  1737  BT+98wjXFX6RFSagtAujo80rIF2dSm33BGt18pDN8v6zp93dnAm0jRaSQrHJ75xw
  1738  5O+S1oEYR1LtUoFJy6qB104j6aINBAgOiLIKiMkCAwEAAaNGMEQwQgYDVR0BBDsw
  1739  OYAQVuYVQ/WDjdGSkZRlTtJDNKETMBExDzANBgNVBAMTBm15dGVzdIIQtwyL3RPW
  1740  V7dJQp34HwZG9DAJBgUrDgMCHQUAA4GBABngrSkH7vG5lY4sa4AZF59lAAXqBVJE
  1741  J4TBiKC62hCdZv18rBleP6ETfhbPg7pTs8p4ebQbpmtNxRS9Lw3MzQ8Ya5Ybwzj2
  1742  NwBSyCtCQl7mrEg4nJqJl4A2EUhnET/oVxU0oTV/SZ3ziGXcY1oG1s6vidV7TZTu
  1743  MCRtdSdaM7g3
  1744  -----END CERTIFICATE-----`
  1745  
  1746  func TestISOOIDInCertificate(t *testing.T) {
  1747  	block, _ := pem.Decode([]byte(certISOOID))
  1748  	if cert, err := ParseCertificate(block.Bytes); err != nil {
  1749  		t.Errorf("certificate with ISO OID failed to parse: %s", err)
  1750  	} else if cert.SignatureAlgorithm == UnknownSignatureAlgorithm {
  1751  		t.Errorf("ISO OID not recognised in certificate")
  1752  	}
  1753  }
  1754  
  1755  // certMultipleRDN contains a RelativeDistinguishedName with two elements (the
  1756  // common name and serial number). This particular certificate was the first
  1757  // such certificate in the “Pilot” Certificate Transparency log.
  1758  const certMultipleRDN = `
  1759  -----BEGIN CERTIFICATE-----
  1760  MIIFRzCCBC+gAwIBAgIEOl59NTANBgkqhkiG9w0BAQUFADA9MQswCQYDVQQGEwJz
  1761  aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMREwDwYDVQQLEwhzaWdvdi1j
  1762  YTAeFw0xMjExMTYxMDUyNTdaFw0xNzExMTYxMjQ5MDVaMIGLMQswCQYDVQQGEwJz
  1763  aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMRkwF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YtY2EuZ292
  1779  LnNpL2NybC9zaWdvdi1jYS5jcmwwKwYDVR0QBCQwIoAPMjAxMjExMTYxMDUyNTda
  1780  gQ8yMDE3MTExNjEyNDkwNVowHwYDVR0jBBgwFoAUHvjUU2uzgwbpBAZXAvmlv8ZY
  1781  PHIwHQYDVR0OBBYEFGI1Duuu+wTGDZka/xHNbwcbM69ZMAkGA1UdEwQCMAAwGQYJ
  1782  KoZIhvZ9B0EABAwwChsEVjcuMQMCA6gwDQYJKoZIhvcNAQEFBQADggEBAHny0K1y
  1783  BQznrzDu3DDpBcGYguKU0dvU9rqsV1ua4nxkriSMWjgsX6XJFDdDW60I3P4VWab5
  1784  ag5fZzbGqi8kva/CzGgZh+CES0aWCPy+4Gb8lwOTt+854/laaJvd6kgKTER7z7U9
  1785  9C86Ch2y4sXNwwwPJ1A9dmrZJZOcJjS/WYZgwaafY2Hdxub5jqPE5nehwYUPVu9R
  1786  uH6/skk4OEKcfOtN0hCnISOVuKYyS4ANARWRG5VGHIH06z3lGUVARFRJ61gtAprd
  1787  La+fgSS+LVZ+kU2TkeoWAKvGq8MAgDq4D4Xqwekg7WKFeuyusi/NI5rm40XgjBMF
  1788  DF72IUofoVt7wo0=
  1789  -----END CERTIFICATE-----`
  1790  
  1791  func TestMultipleRDN(t *testing.T) {
  1792  	block, _ := pem.Decode([]byte(certMultipleRDN))
  1793  	cert, err := ParseCertificate(block.Bytes)
  1794  	if err != nil {
  1795  		t.Fatalf("certificate with two elements in an RDN failed to parse: %v", err)
  1796  	}
  1797  
  1798  	if want := "eportal.mss.edus.si"; cert.Subject.CommonName != want {
  1799  		t.Errorf("got common name of %q, but want %q", cert.Subject.CommonName, want)
  1800  	}
  1801  
  1802  	if want := "1236484010010"; cert.Subject.SerialNumber != want {
  1803  		t.Errorf("got serial number of %q, but want %q", cert.Subject.SerialNumber, want)
  1804  	}
  1805  }
  1806  
  1807  func TestSystemCertPool(t *testing.T) {
  1808  	if runtime.GOOS == "windows" {
  1809  		t.Skip("not implemented on Windows (Issue 16736, 18609) or darwin (Issue 46287)")
  1810  	}
  1811  	a, err := SystemCertPool()
  1812  	if err != nil {
  1813  		t.Fatal(err)
  1814  	}
  1815  	b, err := SystemCertPool()
  1816  	if err != nil {
  1817  		t.Fatal(err)
  1818  	}
  1819  	if !certPoolEqual(a, b) {
  1820  		t.Fatal("two calls to SystemCertPool had different results")
  1821  	}
  1822  	if ok := b.AppendCertsFromPEM([]byte(`
  1823  -----BEGIN CERTIFICATE-----
  1824  MIIDBjCCAe6gAwIBAgIRANXM5I3gjuqDfTp/PYrs+u8wDQYJKoZIhvcNAQELBQAw
  1825  EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xODAzMjcxOTU2MjFaFw0xOTAzMjcxOTU2
  1826  MjFaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
  1827  ggEKAoIBAQDK+9m3rjsO2Djes6bIYQZ3eV29JF09ZrjOrEHLtaKrD6/acsoSoTsf
  1828  cQr+rzzztdB5ijWXCS64zo/0OiqBeZUNZ67jVdToa9qW5UYe2H0Y+ZNdfA5GYMFD
  1829  yk/l3/uBu3suTZPfXiW2TjEi27Q8ruNUIZ54DpTcs6y2rBRFzadPWwn/VQMlvRXM
  1830  jrzl8Y08dgnYmaAHprxVzwMXcQ/Brol+v9GvjaH1DooHqkn8O178wsPQNhdtvN01
  1831  IXL46cYdcUwWrE/GX5u+9DaSi+0KWxAPQ+NVD5qUI0CKl4714yGGh7feXMjJdHgl
  1832  VG4QJZlJvC4FsURgCHJT6uHGIelnSwhbAgMBAAGjVzBVMA4GA1UdDwEB/wQEAwIF
  1833  oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMCAGA1UdEQQZMBeC
  1834  FVRlc3RTeXN0ZW1DZXJ0UG9vbC5nbzANBgkqhkiG9w0BAQsFAAOCAQEAwuSRx/VR
  1835  BKh2ICxZjL6jBwk/7UlU1XKbhQD96RqkidDNGEc6eLZ90Z5XXTurEsXqdm5jQYPs
  1836  1cdcSW+fOSMl7MfW9e5tM66FaIPZl9rKZ1r7GkOfgn93xdLAWe8XHd19xRfDreub
  1837  YC8DVqgLASOEYFupVSl76ktPfxkU5KCvmUf3P2PrRybk1qLGFytGxfyice2gHSNI
  1838  gify3K/+H/7wCkyFW4xYvzl7WW4mXxoqPRPjQt1J423DhnnQ4G1P8V/vhUpXNXOq
  1839  N9IEPnWuihC09cyx/WMQIUlWnaQLHdfpPS04Iez3yy2PdfXJzwfPrja7rNE+skK6
  1840  pa/O1nF0AfWOpw==
  1841  -----END CERTIFICATE-----
  1842  	`)); !ok {
  1843  		t.Fatal("AppendCertsFromPEM failed")
  1844  	}
  1845  	if reflect.DeepEqual(a, b) {
  1846  		t.Fatal("changing one pool modified the other")
  1847  	}
  1848  }
  1849  
  1850  const emptyNameConstraintsPEM = `
  1851  -----BEGIN CERTIFICATE-----
  1852  MIIC1jCCAb6gAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w
  1853  dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw
  1854  NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB
  1855  IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD
  1856  F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx
  1857  f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq
  1858  Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0
  1859  LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD
  1860  blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID
  1861  AQABoxEwDzANBgNVHR4EBjAEoAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMH
  1862  QhP8uNCtgSHyim/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb
  1863  6L+iJa4ElREJOi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6H
  1864  v5SsvpYW+1XleYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6M
  1865  LYPmRhTioROA/drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOga
  1866  nCOSyFYfGhqOANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8
  1867  o+WoY6IsCKXV/g==
  1868  -----END CERTIFICATE-----`
  1869  
  1870  func TestEmptyNameConstraints(t *testing.T) {
  1871  	block, _ := pem.Decode([]byte(emptyNameConstraintsPEM))
  1872  	_, err := ParseCertificate(block.Bytes)
  1873  	if err == nil {
  1874  		t.Fatal("unexpected success")
  1875  	}
  1876  
  1877  	const expected = "empty name constraints"
  1878  	if str := err.Error(); !strings.Contains(str, expected) {
  1879  		t.Errorf("expected %q in error but got %q", expected, str)
  1880  	}
  1881  }
  1882  
  1883  func TestPKIXNameString(t *testing.T) {
  1884  	der, err := base64.StdEncoding.DecodeString(certBytes)
  1885  	if err != nil {
  1886  		t.Fatal(err)
  1887  	}
  1888  	certs, err := ParseCertificates(der)
  1889  	if err != nil {
  1890  		t.Fatal(err)
  1891  	}
  1892  
  1893  	// Check that parsed non-standard attributes are printed.
  1894  	rdns := pkix.Name{
  1895  		Locality: []string{"Gophertown"},
  1896  		ExtraNames: []pkix.AttributeTypeAndValue{
  1897  			{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  1898  	}.ToRDNSequence()
  1899  	nn := pkix.Name{}
  1900  	nn.FillFromRDNSequence(&rdns)
  1901  
  1902  	// Check that zero-length non-nil ExtraNames hide Names.
  1903  	extra := []pkix.AttributeTypeAndValue{
  1904  		{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "backing array"}}
  1905  	extraNotNil := pkix.Name{
  1906  		Locality:   []string{"Gophertown"},
  1907  		ExtraNames: extra[:0],
  1908  		Names: []pkix.AttributeTypeAndValue{
  1909  			{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  1910  	}
  1911  
  1912  	tests := []struct {
  1913  		dn   pkix.Name
  1914  		want string
  1915  	}{
  1916  		{nn, "L=Gophertown,1.2.3.4.5=#130a676f6c616e672e6f7267"},
  1917  		{extraNotNil, "L=Gophertown"},
  1918  		{pkix.Name{
  1919  			CommonName:         "Steve Kille",
  1920  			Organization:       []string{"Isode Limited"},
  1921  			OrganizationalUnit: []string{"RFCs"},
  1922  			Locality:           []string{"Richmond"},
  1923  			Province:           []string{"Surrey"},
  1924  			StreetAddress:      []string{"The Square"},
  1925  			PostalCode:         []string{"TW9 1DT"},
  1926  			SerialNumber:       "RFC 2253",
  1927  			Country:            []string{"GB"},
  1928  		}, "SERIALNUMBER=RFC 2253,CN=Steve Kille,OU=RFCs,O=Isode Limited,POSTALCODE=TW9 1DT,STREET=The Square,L=Richmond,ST=Surrey,C=GB"},
  1929  		{certs[0].Subject,
  1930  			"CN=mail.google.com,O=Google LLC,L=Mountain View,ST=California,C=US"},
  1931  		{pkix.Name{
  1932  			Organization: []string{"#Google, Inc. \n-> 'Alphabet\" "},
  1933  			Country:      []string{"US"},
  1934  		}, "O=\\#Google\\, Inc. \n-\\> 'Alphabet\\\"\\ ,C=US"},
  1935  		{pkix.Name{
  1936  			CommonName:   "foo.com",
  1937  			Organization: []string{"Gopher Industries"},
  1938  			ExtraNames: []pkix.AttributeTypeAndValue{
  1939  				{Type: asn1.ObjectIdentifier([]int{2, 5, 4, 3}), Value: "bar.com"}},
  1940  		}, "CN=bar.com,O=Gopher Industries"},
  1941  		{pkix.Name{
  1942  			Locality: []string{"Gophertown"},
  1943  			ExtraNames: []pkix.AttributeTypeAndValue{
  1944  				{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  1945  		}, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"},
  1946  		// If there are no ExtraNames, the Names are printed instead.
  1947  		{pkix.Name{
  1948  			Locality: []string{"Gophertown"},
  1949  			Names: []pkix.AttributeTypeAndValue{
  1950  				{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  1951  		}, "L=Gophertown,1.2.3.4.5=#130a676f6c616e672e6f7267"},
  1952  		// If there are both, print only the ExtraNames.
  1953  		{pkix.Name{
  1954  			Locality: []string{"Gophertown"},
  1955  			ExtraNames: []pkix.AttributeTypeAndValue{
  1956  				{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  1957  			Names: []pkix.AttributeTypeAndValue{
  1958  				{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 6}), Value: "example.com"}},
  1959  		}, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"},
  1960  	}
  1961  
  1962  	for i, test := range tests {
  1963  		if got := test.dn.String(); got != test.want {
  1964  			t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
  1965  		}
  1966  	}
  1967  
  1968  	if extra[0].Value != "backing array" {
  1969  		t.Errorf("the backing array of an empty ExtraNames got modified by String")
  1970  	}
  1971  }
  1972  
  1973  func TestRDNSequenceString(t *testing.T) {
  1974  	// Test some extra cases that get lost in pkix.Name conversions such as
  1975  	// multi-valued attributes.
  1976  
  1977  	var (
  1978  		oidCountry            = []int{2, 5, 4, 6}
  1979  		oidOrganization       = []int{2, 5, 4, 10}
  1980  		oidOrganizationalUnit = []int{2, 5, 4, 11}
  1981  		oidCommonName         = []int{2, 5, 4, 3}
  1982  	)
  1983  
  1984  	tests := []struct {
  1985  		seq  pkix.RDNSequence
  1986  		want string
  1987  	}{
  1988  		{
  1989  			seq: pkix.RDNSequence{
  1990  				pkix.RelativeDistinguishedNameSET{
  1991  					pkix.AttributeTypeAndValue{Type: oidCountry, Value: "US"},
  1992  				},
  1993  				pkix.RelativeDistinguishedNameSET{
  1994  					pkix.AttributeTypeAndValue{Type: oidOrganization, Value: "Widget Inc."},
  1995  				},
  1996  				pkix.RelativeDistinguishedNameSET{
  1997  					pkix.AttributeTypeAndValue{Type: oidOrganizationalUnit, Value: "Sales"},
  1998  					pkix.AttributeTypeAndValue{Type: oidCommonName, Value: "J. Smith"},
  1999  				},
  2000  			},
  2001  			want: "OU=Sales+CN=J. Smith,O=Widget Inc.,C=US",
  2002  		},
  2003  	}
  2004  
  2005  	for i, test := range tests {
  2006  		if got := test.seq.String(); got != test.want {
  2007  			t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
  2008  		}
  2009  	}
  2010  }
  2011  
  2012  const criticalNameConstraintWithUnknownTypePEM = `
  2013  -----BEGIN CERTIFICATE-----
  2014  MIIC/TCCAeWgAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w
  2015  dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw
  2016  NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB
  2017  IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD
  2018  F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx
  2019  f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq
  2020  Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0
  2021  LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD
  2022  blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID
  2023  AQABozgwNjA0BgNVHR4BAf8EKjAooCQwIokgIACrzQAAAAAAAAAAAAAAAP////8A
  2024  AAAAAAAAAAAAAAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMHQhP8uNCtgSHy
  2025  im/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb6L+iJa4ElREJ
  2026  Oi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6Hv5SsvpYW+1Xl
  2027  eYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6MLYPmRhTioROA
  2028  /drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOganCOSyFYfGhqO
  2029  ANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8o+WoY6IsCKXV
  2030  /g==
  2031  -----END CERTIFICATE-----`
  2032  
  2033  func TestCriticalNameConstraintWithUnknownType(t *testing.T) {
  2034  	block, _ := pem.Decode([]byte(criticalNameConstraintWithUnknownTypePEM))
  2035  	cert, err := ParseCertificate(block.Bytes)
  2036  	if err != nil {
  2037  		t.Fatalf("unexpected parsing failure: %s", err)
  2038  	}
  2039  
  2040  	if l := len(cert.UnhandledCriticalExtensions); l != 1 {
  2041  		t.Fatalf("expected one unhandled critical extension, but found %d", l)
  2042  	}
  2043  }
  2044  
  2045  const badIPMaskPEM = `
  2046  -----BEGIN CERTIFICATE-----
  2047  MIICzzCCAbegAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwHTEbMBkGA1UEAxMSQmFk
  2048  IElQIG1hc2sgaXNzdWVyMB4XDTEzMDIwMTAwMDAwMFoXDTIwMDUzMDEwNDgzOFow
  2049  FjEUMBIGA1UEAxMLQmFkIElQIG1hc2swggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
  2050  ggEKAoIBAQDCuISVQi3csKqYk5uz7IOhY8MXkiqBaTqagihtiM997G1mJhTojcR+
  2051  8DCg3E8OQ3ZajByhxRkwlsR4Srl5sGSwWfF/XaAHGUhWIhjBkDO7toW+EMzI8pAj
  2052  cLwIbRlIL0AFnUTe6Z0DcIS5406Y/9MKE2oKXbf4EbVBv88mSkA74Z+lZJWFNxXn
  2053  cx/9wq8UdyMY2vHN1Kir1/JbtrqB9wYRBjQtWSbAVZR8nTBPyRp4uvQTS2jOQh+j
  2054  TUo1Y3O/o1xg/zRA4FEOUCla704OYRUkc8NuXHiPNNDcktr7gO8E06NVQ6n6aBGa
  2055  OJbSst2vHA7Eiog7A2PB4wKn+GDFf+FNAgMBAAGjIDAeMBwGA1UdHgEB/wQSMBCg
  2056  DDAKhwgBAgME//8BAKEAMA0GCSqGSIb3DQEBCwUAA4IBAQBYb7/NQwdCE/y40K2B
  2057  IfKKb++HvCaKfAC9aAwrGWQsEWezqdl5Cqw5XWUAFjtTRm6iprVnmdvov6IlrgSV
  2058  EQk6L96stz24vAF0MIBHSFRMoPtrqLiihLf0NOV7ztxSePQxbUJRroe/lKy+lhb7
  2059  VeV5gmT9rFA45NzLgSznd2+dmyNcfQQD9AeeftRX4maUTeu1XFxinowtg+ZGFOKh
  2060  E4D92uCGJxGSK72HF0/LGRhLXozmDdmPfSN2b6T/oLo942031iY46BqcI5LIVh8a
  2061  Go4A1jOma5X6gh50Cw+kht8jM3yeNhSzXOKj7Uigjijx10z2wJu09Tyj5ahjoiwI
  2062  pdX+
  2063  -----END CERTIFICATE-----`
  2064  
  2065  func TestBadIPMask(t *testing.T) {
  2066  	block, _ := pem.Decode([]byte(badIPMaskPEM))
  2067  	_, err := ParseCertificate(block.Bytes)
  2068  	if err == nil {
  2069  		t.Fatalf("unexpected success")
  2070  	}
  2071  
  2072  	const expected = "contained invalid mask"
  2073  	if !strings.Contains(err.Error(), expected) {
  2074  		t.Fatalf("expected %q in error but got: %s", expected, err)
  2075  	}
  2076  }
  2077  
  2078  const additionalGeneralSubtreePEM = `
  2079  -----BEGIN CERTIFICATE-----
  2080  MIIG4TCCBMmgAwIBAgIRALss+4rLw2Ia7tFFhxE8g5cwDQYJKoZIhvcNAQELBQAw
  2081  bjELMAkGA1UEBhMCTkwxIDAeBgNVBAoMF01pbmlzdGVyaWUgdmFuIERlZmVuc2ll
  2082  MT0wOwYDVQQDDDRNaW5pc3RlcmllIHZhbiBEZWZlbnNpZSBDZXJ0aWZpY2F0aWUg
  2083  QXV0b3JpdGVpdCAtIEcyMB4XDTEzMDMwNjEyMDM0OVoXDTEzMTEzMDEyMDM1MFow
  2084  bDELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUNlcnRpUGF0aCBMTEMxIjAgBgNVBAsT
  2085  GUNlcnRpZmljYXRpb24gQXV0aG9yaXRpZXMxITAfBgNVBAMTGENlcnRpUGF0aCBC
  2086  cmlkZ2UgQ0EgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANLW
  2087  4kXiRqvwBhJfN9uz12FA+P2D34MPxOt7TGXljm2plJ2CLzvaH8/ymsMdSWdJBS1M
  2088  8FmwvNL1w3A6ZuzksJjPikAu8kY3dcp3mrkk9eCPORDAwGtfsXwZysLiuEaDWpbD
  2089  dHOaHnI6qWU0N6OI+hNX58EjDpIGC1WQdho1tHOTPc5Hf5/hOpM/29v/wr7kySjs
  2090  Z+7nsvkm5rNhuJNzPsLsgzVaJ5/BVyOplZy24FKM8Y43MjR4osZm+a2e0zniqw6/
  2091  rvcjcGYabYaznZfQG1GXoyf2Vea+CCgpgUhlVafgkwEs8izl8rIpvBzXiFAgFQuG
  2092  Ituoy92PJbDs430fA/cCAwEAAaOCAnowggJ2MEUGCCsGAQUFBwEBBDkwNzA1Bggr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AQSOrpE/TVgWfu/+MMRWwX9y6VbooBR7BLv7zMuVH0WqLn
  2109  6OMFth7fqsThlfMSzkE/RDSaU6n3wXAWT1SIqBITtccRjSUQUFm/q3xrb2cwcZA6
  2110  8vdS4hzNd+ttS905ay31Ks4/1Wrm1bH5RhEfRSH0VSXnc0b+z+RyBbmiwtVZqzxE
  2111  u3UQg/rAmtLDclLFEzjp8YDTIRYSLwstDbEXO/0ArdGrQm79HQ8i/3ZbP2357myW
  2112  i15qd6gMJIgGHS4b8Hc7R1K8LQ9Gm1aLKBEWVNGZlPK/cpXThpVmoEyslN2DHCrc
  2113  fbMbjNZpXlTMa+/b9z7Fa4X8dY8u/ELzZuJXJv5Rmqtg29eopFFYDCl0Nkh1XAjo
  2114  QejEoHHUvYV8TThHZr6Z6Ib8CECgTehU4QvepkgDXNoNrKRZBG0JhLjkwxh2whZq
  2115  nvWBfALC2VuNOM6C0rDY+HmhMlVt0XeqnybD9MuQALMit7Z00Cw2CIjNsBI9xBqD
  2116  xKK9CjUb7gzRUWSpB9jGHsvpEMHOzIFhufvH2Bz1XJw+Cl7khw==
  2117  -----END CERTIFICATE-----`
  2118  
  2119  func TestAdditionFieldsInGeneralSubtree(t *testing.T) {
  2120  	// Very rarely, certificates can include additional fields in the
  2121  	// GeneralSubtree structure. This tests that such certificates can be
  2122  	// parsed.
  2123  	block, _ := pem.Decode([]byte(additionalGeneralSubtreePEM))
  2124  	if _, err := ParseCertificate(block.Bytes); err != nil {
  2125  		t.Fatalf("failed to parse certificate: %s", err)
  2126  	}
  2127  }
  2128  
  2129  func TestEmptySubject(t *testing.T) {
  2130  	template := x509.Certificate{
  2131  		SerialNumber: big.NewInt(1),
  2132  		DNSNames:     []string{"example.com"},
  2133  	}
  2134  
  2135  	derBytes, err := CreateCertificate(rand.Reader, &template, &template, &testPrivateKey.PublicKey, testPrivateKey)
  2136  	if err != nil {
  2137  		t.Fatalf("failed to create certificate: %s", err)
  2138  	}
  2139  
  2140  	cert, err := ParseCertificate(derBytes)
  2141  	if err != nil {
  2142  		t.Fatalf("failed to parse certificate: %s", err)
  2143  	}
  2144  
  2145  	for _, ext := range cert.Extensions {
  2146  		if ext.Id.Equal(oidExtensionSubjectAltName) {
  2147  			if !ext.Critical {
  2148  				t.Fatal("SAN extension is not critical")
  2149  			}
  2150  			return
  2151  		}
  2152  	}
  2153  
  2154  	t.Fatal("SAN extension is missing")
  2155  }
  2156  
  2157  // multipleURLsInCRLDPPEM contains two URLs in a single CRL DistributionPoint
  2158  // structure. It is taken from https://crt.sh/?id=12721534.
  2159  const multipleURLsInCRLDPPEM = `
  2160  -----BEGIN CERTIFICATE-----
  2161  MIIF4TCCBMmgAwIBAgIQc+6uFePfrahUGpXs8lhiTzANBgkqhkiG9w0BAQsFADCB
  2162  8zELMAkGA1UEBhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2Vy
  2163  dGlmaWNhY2lvIChOSUYgUS0wODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1
  2164  YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYDVQQLEyxWZWdldSBodHRwczovL3d3
  2165  dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UECxMsSmVyYXJxdWlh
  2166  IEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMTBkVD
  2167  LUFDQzAeFw0xNDA5MTgwODIxMDBaFw0zMDA5MTgwODIxMDBaMIGGMQswCQYDVQQG
  2168  EwJFUzEzMDEGA1UECgwqQ09OU09SQ0kgQURNSU5JU1RSQUNJTyBPQkVSVEEgREUg
  2169  Q0FUQUxVTllBMSowKAYDVQQLDCFTZXJ2ZWlzIFDDumJsaWNzIGRlIENlcnRpZmlj
  2170  YWNpw7MxFjAUBgNVBAMMDUVDLUNpdXRhZGFuaWEwggEiMA0GCSqGSIb3DQEBAQUA
  2171  A4IBDwAwggEKAoIBAQ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0GCSqGSIb3DQEBCwUA
  2187  A4IBAQChqFTjlAH5PyIhLjLgEs68CyNNC1+vDuZXRhy22TI83JcvGmQrZosPvVIL
  2188  PsUXx+C06Pfqmh48Q9S89X9K8w1SdJxP/rZeGEoRiKpwvQzM4ArD9QxyC8jirxex
  2189  3Umg9Ai/sXQ+1lBf6xw4HfUUr1WIp7pNHj0ZWLo106urqktcdeAFWme+/klis5fu
  2190  labCSVPuT/QpwakPrtqOhRms8vgpKiXa/eLtL9ZiA28X/Mker0zlAeTA7Z7uAnp6
  2191  oPJTlZu1Gg1ZDJueTWWsLlO+P+Wzm3MRRIbcgdRzm4mdO7ubu26SzX/aQXDhuih+
  2192  eVxXDTCfs7GUlxnjOp5j559X/N0A
  2193  -----END CERTIFICATE-----
  2194  `
  2195  
  2196  func TestMultipleURLsInCRLDP(t *testing.T) {
  2197  	block, _ := pem.Decode([]byte(multipleURLsInCRLDPPEM))
  2198  	cert, err := ParseCertificate(block.Bytes)
  2199  	if err != nil {
  2200  		t.Fatalf("failed to parse certificate: %s", err)
  2201  	}
  2202  
  2203  	want := []string{
  2204  		"http://epscd.catcert.net/crl/ec-acc.crl",
  2205  		"http://epscd2.catcert.net/crl/ec-acc.crl",
  2206  	}
  2207  	if got := cert.CRLDistributionPoints; !reflect.DeepEqual(got, want) {
  2208  		t.Errorf("CRL distribution points = %#v, want #%v", got, want)
  2209  	}
  2210  }
  2211  
  2212  func TestCreateRevocationList(t *testing.T) {
  2213  	ec256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  2214  	if err != nil {
  2215  		t.Fatalf("Failed to generate ECDSA P256 key: %s", err)
  2216  	}
  2217  	sm2Priv, err := sm2.GenerateKey(rand.Reader)
  2218  	if err != nil {
  2219  		t.Fatalf("Failed to generate SM2 key: %s", err)
  2220  	}
  2221  	_, ed25519Priv, err := ed25519.GenerateKey(rand.Reader)
  2222  	if err != nil {
  2223  		t.Fatalf("Failed to generate Ed25519 key: %s", err)
  2224  	}
  2225  
  2226  	// Generation command:
  2227  	// openssl req -x509 -newkey rsa -keyout key.pem -out cert.pem -days 365 -nodes -subj '/C=US/ST=California/L=San Francisco/O=Internet Widgets, Inc./OU=WWW/CN=Root/emailAddress=admin@example.com' -sha256 -addext basicConstraints=CA:TRUE -addext "keyUsage = digitalSignature, keyEncipherment, dataEncipherment, cRLSign, keyCertSign" -utf8
  2228  	utf8CAStr := "MIIEITCCAwmgAwIBAgIUXHXy7NdtDv+ClaHvIvlwCYiI4a4wDQYJKoZIhvcNAQELBQAwgZoxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMR8wHQYDVQQKDBZJbnRlcm5ldCBXaWRnZXRzLCBJbmMuMQwwCgYDVQQLDANXV1cxDTALBgNVBAMMBFJvb3QxIDAeBgkqhkiG9w0BCQEWEWFkbWluQGV4YW1wbGUuY29tMB4XDTIyMDcwODE1MzgyMFoXDTIzMDcwODE1MzgyMFowgZoxCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxpZm9ybmlhMRYwFAYDVQQHDA1TYW4gRnJhbmNpc2NvMR8wHQYDVQQKDBZJbnRlcm5ldCBXaWRnZXRzLCBJbmMuMQwwCgYDVQQLDANXV1cxDTALBgNVBAMMBFJvb3QxIDAeBgkqhkiG9w0BCQEWEWFkbWluQGV4YW1wbGUuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmXvp0WNjsZzySWT7Ce5zewQNKq8ujeZGphJ44Vdrwut/b6TcC4iYENds5+7/3PYwBllp3K5TRpCcafSxdhJsvA7/zWlHHNRcJhJLNt9qsKWP6ukI2Iw6OmFMg6kJQ8f67RXkT8HR3v0UqE+lWrA0g+oRuj4erLtfOtSpnl4nsE/Rs2qxbELFWAf7F5qMqH4dUyveWKrNT8eI6YQN+wBg0MAjoKRvDJnBhuo+IvvXX8Aq1QWUcBGPK3or/Ehxy5f/gEmSUXyEU1Ht/vATt2op+eRaEEpBdGRvO+DrKjlcQV2XMN18A9LAX6hCzH43sGye87dj7RZ9yj+waOYNaM7kFQIDAQABo10wWzAdBgNVHQ4EFgQUtbSlrW4hGL2kNjviM6wcCRwvOEEwHwYDVR0jBBgwFoAUtbSlrW4hGL2kNjviM6wcCRwvOEEwDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAbYwDQYJKoZIhvcNAQELBQADggEBAAko82YNNI2n/45L3ya21vufP6nZihIOIxgcRPUMX+IDJZk16qsFdcLgH3KAP8uiVLn8sULuCj35HpViR4IcAk2d+DqfG11l8kY+e5P7nYsViRfy0AatF59/sYlWf+3RdmPXfL70x4mE9OqlMdDm0kR2obps8rng83VLDNvj3R5sBnQwdw6LKLGzaE+RiCTmkH0+P6vnbOJ33su9+9al1+HvJUg3UM1Xq5Bw7TE8DQTetMV3c2Q35RQaJB9pQ4blJOnW9hfnt8yQzU6TU1bU4mRctTm1o1f8btPqUpi+/blhi5MUJK0/myj1XD00pmyfp8QAFl1EfqmTMIBMLg633A0="
  2229  	utf8CABytes, _ := base64.StdEncoding.DecodeString(utf8CAStr)
  2230  	utf8CA, _ := ParseCertificate(utf8CABytes)
  2231  
  2232  	utf8KeyStr := "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCZe+nRY2OxnPJJZPsJ7nN7BA0qry6N5kamEnjhV2vC639vpNwLiJgQ12zn7v/c9jAGWWncrlNGkJxp9LF2Emy8Dv/NaUcc1FwmEks232qwpY/q6QjYjDo6YUyDqQlDx/rtFeRPwdHe/RSoT6VasDSD6hG6Ph6su1861KmeXiewT9GzarFsQsVYB/sXmoyofh1TK95Yqs1Px4jphA37AGDQwCOgpG8MmcGG6j4i+9dfwCrVBZRwEY8reiv8SHHLl/+ASZJRfIRTUe3+8BO3ain55FoQSkF0ZG874OsqOVxBXZcw3XwD0sBfqELMfjewbJ7zt2PtFn3KP7Bo5g1ozuQVAgMBAAECggEAIscjKiD9PA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kZNgTW27yyr+Nhs4/cMdrg1AYTB0+6ItQWSDmYLs7JEbBE/8L8fdD1irIcygjIHE9nJh96TgZCt61kVGLE8758lOdmoB2rZOpGwi16QIhdQb+IyozYqfX+lQUojL/W0="
  2233  	utf8KeyBytes, _ := base64.StdEncoding.DecodeString(utf8KeyStr)
  2234  	utf8KeyRaw, _ := ParsePKCS8PrivateKey(utf8KeyBytes)
  2235  	utf8Key := utf8KeyRaw.(crypto.Signer)
  2236  
  2237  	tests := []struct {
  2238  		name          string
  2239  		key           crypto.Signer
  2240  		issuer        *x509.Certificate
  2241  		template      *x509.RevocationList
  2242  		expectedError string
  2243  	}{
  2244  		{
  2245  			name:          "nil template",
  2246  			key:           sm2Priv,
  2247  			issuer:        nil,
  2248  			template:      nil,
  2249  			expectedError: "x509: template can not be nil",
  2250  		},
  2251  		{
  2252  			name:          "nil issuer",
  2253  			key:           sm2Priv,
  2254  			issuer:        nil,
  2255  			template:      &x509.RevocationList{},
  2256  			expectedError: "x509: issuer can not be nil",
  2257  		},
  2258  		{
  2259  			name: "issuer doesn't have crlSign key usage bit set",
  2260  			key:  sm2Priv,
  2261  			issuer: &x509.Certificate{
  2262  				KeyUsage: KeyUsageCertSign,
  2263  			},
  2264  			template:      &x509.RevocationList{},
  2265  			expectedError: "x509: issuer must have the crlSign key usage bit set",
  2266  		},
  2267  		{
  2268  			name: "issuer missing SubjectKeyId",
  2269  			key:  sm2Priv,
  2270  			issuer: &x509.Certificate{
  2271  				KeyUsage: KeyUsageCRLSign,
  2272  			},
  2273  			template:      &x509.RevocationList{},
  2274  			expectedError: "x509: issuer certificate doesn't contain a subject key identifier",
  2275  		},
  2276  		{
  2277  			name: "nextUpdate before thisUpdate",
  2278  			key:  sm2Priv,
  2279  			issuer: &x509.Certificate{
  2280  				KeyUsage: KeyUsageCRLSign,
  2281  				Subject: pkix.Name{
  2282  					CommonName: "testing",
  2283  				},
  2284  				SubjectKeyId: []byte{1, 2, 3},
  2285  			},
  2286  			template: &x509.RevocationList{
  2287  				ThisUpdate: time.Time{}.Add(time.Hour),
  2288  				NextUpdate: time.Time{},
  2289  			},
  2290  			expectedError: "x509: template.ThisUpdate is after template.NextUpdate",
  2291  		},
  2292  		{
  2293  			name: "nil Number",
  2294  			key:  sm2Priv,
  2295  			issuer: &x509.Certificate{
  2296  				KeyUsage: KeyUsageCRLSign,
  2297  				Subject: pkix.Name{
  2298  					CommonName: "testing",
  2299  				},
  2300  				SubjectKeyId: []byte{1, 2, 3},
  2301  			},
  2302  			template: &x509.RevocationList{
  2303  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2304  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2305  			},
  2306  			expectedError: "x509: template contains nil Number field",
  2307  		},
  2308  		{
  2309  			name: "long Number",
  2310  			key:  sm2Priv,
  2311  			issuer: &x509.Certificate{
  2312  				KeyUsage: KeyUsageCRLSign,
  2313  				Subject: pkix.Name{
  2314  					CommonName: "testing",
  2315  				},
  2316  				SubjectKeyId: []byte{1, 2, 3},
  2317  			},
  2318  			template: &x509.RevocationList{
  2319  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2320  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2321  				Number:     big.NewInt(0).SetBytes(append([]byte{1}, make([]byte, 20)...)),
  2322  			},
  2323  			expectedError: "x509: CRL number exceeds 20 octets",
  2324  		},
  2325  		{
  2326  			name: "long Number (20 bytes, MSB set)",
  2327  			key:  sm2Priv,
  2328  			issuer: &x509.Certificate{
  2329  				KeyUsage: KeyUsageCRLSign,
  2330  				Subject: pkix.Name{
  2331  					CommonName: "testing",
  2332  				},
  2333  				SubjectKeyId: []byte{1, 2, 3},
  2334  			},
  2335  			template: &x509.RevocationList{
  2336  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2337  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2338  				Number:     big.NewInt(0).SetBytes(append([]byte{255}, make([]byte, 19)...)),
  2339  			},
  2340  			expectedError: "x509: CRL number exceeds 20 octets",
  2341  		},
  2342  		{
  2343  			name: "invalid signature algorithm",
  2344  			key:  sm2Priv,
  2345  			issuer: &x509.Certificate{
  2346  				KeyUsage: KeyUsageCRLSign,
  2347  				Subject: pkix.Name{
  2348  					CommonName: "testing",
  2349  				},
  2350  				SubjectKeyId: []byte{1, 2, 3},
  2351  			},
  2352  			template: &x509.RevocationList{
  2353  				SignatureAlgorithm: SHA256WithRSA,
  2354  				RevokedCertificates: []pkix.RevokedCertificate{
  2355  					{
  2356  						SerialNumber:   big.NewInt(2),
  2357  						RevocationTime: time.Time{}.Add(time.Hour),
  2358  					},
  2359  				},
  2360  				Number:     big.NewInt(5),
  2361  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2362  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2363  			},
  2364  			expectedError: "x509: requested SignatureAlgorithm does not match private key type",
  2365  		},
  2366  		{
  2367  			name: "valid",
  2368  			key:  sm2Priv,
  2369  			issuer: &x509.Certificate{
  2370  				KeyUsage: KeyUsageCRLSign,
  2371  				Subject: pkix.Name{
  2372  					CommonName: "testing",
  2373  				},
  2374  				SubjectKeyId: []byte{1, 2, 3},
  2375  			},
  2376  			template: &x509.RevocationList{
  2377  				RevokedCertificates: []pkix.RevokedCertificate{
  2378  					{
  2379  						SerialNumber:   big.NewInt(2),
  2380  						RevocationTime: time.Time{}.Add(time.Hour),
  2381  					},
  2382  				},
  2383  				Number:     big.NewInt(5),
  2384  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2385  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2386  			},
  2387  		},
  2388  		{
  2389  			name: "valid, Ed25519 key",
  2390  			key:  ed25519Priv,
  2391  			issuer: &x509.Certificate{
  2392  				KeyUsage: KeyUsageCRLSign,
  2393  				Subject: pkix.Name{
  2394  					CommonName: "testing",
  2395  				},
  2396  				SubjectKeyId: []byte{1, 2, 3},
  2397  			},
  2398  			template: &x509.RevocationList{
  2399  				RevokedCertificates: []pkix.RevokedCertificate{
  2400  					{
  2401  						SerialNumber:   big.NewInt(2),
  2402  						RevocationTime: time.Time{}.Add(time.Hour),
  2403  					},
  2404  				},
  2405  				Number:     big.NewInt(5),
  2406  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2407  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2408  			},
  2409  		},
  2410  		{
  2411  			name: "valid, non-default signature algorithm",
  2412  			key:  ec256Priv,
  2413  			issuer: &x509.Certificate{
  2414  				KeyUsage: KeyUsageCRLSign,
  2415  				Subject: pkix.Name{
  2416  					CommonName: "testing",
  2417  				},
  2418  				SubjectKeyId: []byte{1, 2, 3},
  2419  			},
  2420  			template: &x509.RevocationList{
  2421  				SignatureAlgorithm: ECDSAWithSHA512,
  2422  				RevokedCertificates: []pkix.RevokedCertificate{
  2423  					{
  2424  						SerialNumber:   big.NewInt(2),
  2425  						RevocationTime: time.Time{}.Add(time.Hour),
  2426  					},
  2427  				},
  2428  				Number:     big.NewInt(5),
  2429  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2430  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2431  			},
  2432  		},
  2433  		{
  2434  			name: "valid, extra extension",
  2435  			key:  sm2Priv,
  2436  			issuer: &x509.Certificate{
  2437  				KeyUsage: KeyUsageCRLSign,
  2438  				Subject: pkix.Name{
  2439  					CommonName: "testing",
  2440  				},
  2441  				SubjectKeyId: []byte{1, 2, 3},
  2442  			},
  2443  			template: &x509.RevocationList{
  2444  				RevokedCertificates: []pkix.RevokedCertificate{
  2445  					{
  2446  						SerialNumber:   big.NewInt(2),
  2447  						RevocationTime: time.Time{}.Add(time.Hour),
  2448  					},
  2449  				},
  2450  				Number:     big.NewInt(5),
  2451  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2452  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2453  				ExtraExtensions: []pkix.Extension{
  2454  					{
  2455  						Id:    []int{2, 5, 29, 99},
  2456  						Value: []byte{5, 0},
  2457  					},
  2458  				},
  2459  			},
  2460  		},
  2461  		{
  2462  			name: "valid, empty list",
  2463  			key:  sm2Priv,
  2464  			issuer: &x509.Certificate{
  2465  				KeyUsage: KeyUsageCRLSign,
  2466  				Subject: pkix.Name{
  2467  					CommonName: "testing",
  2468  				},
  2469  				SubjectKeyId: []byte{1, 2, 3},
  2470  			},
  2471  			template: &x509.RevocationList{
  2472  				Number:     big.NewInt(5),
  2473  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2474  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2475  			},
  2476  		},
  2477  		{
  2478  			name:   "valid CA with utf8 Subject fields including Email, empty list",
  2479  			key:    utf8Key,
  2480  			issuer: utf8CA.asX509(),
  2481  			template: &x509.RevocationList{
  2482  				Number:     big.NewInt(5),
  2483  				ThisUpdate: time.Time{}.Add(time.Hour * 24),
  2484  				NextUpdate: time.Time{}.Add(time.Hour * 48),
  2485  			},
  2486  		},
  2487  	}
  2488  
  2489  	for _, tc := range tests {
  2490  		t.Run(tc.name, func(t *testing.T) {
  2491  			var issuer *Certificate
  2492  			if tc.issuer != nil {
  2493  				issuer = (*Certificate)(tc.issuer)
  2494  			}
  2495  			crl, err := CreateRevocationList(rand.Reader, tc.template, issuer, tc.key)
  2496  			if err != nil && tc.expectedError == "" {
  2497  				t.Fatalf("CreateRevocationList failed unexpectedly: %s", err)
  2498  			} else if err != nil && tc.expectedError != err.Error() {
  2499  				t.Fatalf("CreateRevocationList failed unexpectedly, wanted: %s, got: %s", tc.expectedError, err)
  2500  			} else if err == nil && tc.expectedError != "" {
  2501  				t.Fatalf("CreateRevocationList didn't fail, expected: %s", tc.expectedError)
  2502  			}
  2503  			if tc.expectedError != "" {
  2504  				return
  2505  			}
  2506  
  2507  			parsedCRL, err := ParseDERCRL(crl)
  2508  			if err != nil {
  2509  				t.Fatalf("Failed to parse generated CRL: %s", err)
  2510  			}
  2511  
  2512  			if tc.template.SignatureAlgorithm != UnknownSignatureAlgorithm &&
  2513  				parsedCRL.SignatureAlgorithm.Algorithm.Equal(signatureAlgorithmDetails[tc.template.SignatureAlgorithm].oid) {
  2514  				t.Fatalf("SignatureAlgorithm mismatch: got %v; want %v.", parsedCRL.SignatureAlgorithm,
  2515  					tc.template.SignatureAlgorithm)
  2516  			}
  2517  
  2518  			if !reflect.DeepEqual(parsedCRL.TBSCertList.RevokedCertificates, tc.template.RevokedCertificates) {
  2519  				t.Fatalf("RevokedCertificates mismatch: got %v; want %v.",
  2520  					parsedCRL.TBSCertList.RevokedCertificates, tc.template.RevokedCertificates)
  2521  			}
  2522  
  2523  			if len(parsedCRL.TBSCertList.Extensions) != 2+len(tc.template.ExtraExtensions) {
  2524  				t.Fatalf("Generated CRL has wrong number of extensions, wanted: %d, got: %d", 2+len(tc.template.ExtraExtensions), len(parsedCRL.TBSCertList.Extensions))
  2525  			}
  2526  			expectedAKI, err := asn1.Marshal(authKeyId{Id: tc.issuer.SubjectKeyId})
  2527  			if err != nil {
  2528  				t.Fatalf("asn1.Marshal failed: %s", err)
  2529  			}
  2530  			akiExt := pkix.Extension{
  2531  				Id:    oidExtensionAuthorityKeyId,
  2532  				Value: expectedAKI,
  2533  			}
  2534  			if !reflect.DeepEqual(parsedCRL.TBSCertList.Extensions[0], akiExt) {
  2535  				t.Fatalf("Unexpected first extension: got %v, want %v",
  2536  					parsedCRL.TBSCertList.Extensions[0], akiExt)
  2537  			}
  2538  			expectedNum, err := asn1.Marshal(tc.template.Number)
  2539  			if err != nil {
  2540  				t.Fatalf("asn1.Marshal failed: %s", err)
  2541  			}
  2542  			crlExt := pkix.Extension{
  2543  				Id:    oidExtensionCRLNumber,
  2544  				Value: expectedNum,
  2545  			}
  2546  			if !reflect.DeepEqual(parsedCRL.TBSCertList.Extensions[1], crlExt) {
  2547  				t.Fatalf("Unexpected second extension: got %v, want %v",
  2548  					parsedCRL.TBSCertList.Extensions[1], crlExt)
  2549  			}
  2550  			if len(parsedCRL.TBSCertList.Extensions[2:]) == 0 && len(tc.template.ExtraExtensions) == 0 {
  2551  				// If we don't have anything to check return early so we don't
  2552  				// hit a [] != nil false positive below.
  2553  				return
  2554  			}
  2555  			if !reflect.DeepEqual(parsedCRL.TBSCertList.Extensions[2:], tc.template.ExtraExtensions) {
  2556  				t.Fatalf("Extensions mismatch: got %v; want %v.",
  2557  					parsedCRL.TBSCertList.Extensions[2:], tc.template.ExtraExtensions)
  2558  			}
  2559  		})
  2560  	}
  2561  }
  2562  
  2563  func TestRSAPSAParameters(t *testing.T) {
  2564  	generateParams := func(hashFunc crypto.Hash) []byte {
  2565  		var hashOID asn1.ObjectIdentifier
  2566  
  2567  		switch hashFunc {
  2568  		case crypto.SHA256:
  2569  			hashOID = oidSHA256
  2570  		case crypto.SHA384:
  2571  			hashOID = oidSHA384
  2572  		case crypto.SHA512:
  2573  			hashOID = oidSHA512
  2574  		}
  2575  
  2576  		params := pssParameters{
  2577  			Hash: pkix.AlgorithmIdentifier{
  2578  				Algorithm:  hashOID,
  2579  				Parameters: asn1.NullRawValue,
  2580  			},
  2581  			MGF: pkix.AlgorithmIdentifier{
  2582  				Algorithm: oidMGF1,
  2583  			},
  2584  			SaltLength:   hashFunc.Size(),
  2585  			TrailerField: 1,
  2586  		}
  2587  
  2588  		mgf1Params := pkix.AlgorithmIdentifier{
  2589  			Algorithm:  hashOID,
  2590  			Parameters: asn1.NullRawValue,
  2591  		}
  2592  
  2593  		var err error
  2594  		params.MGF.Parameters.FullBytes, err = asn1.Marshal(mgf1Params)
  2595  		if err != nil {
  2596  			t.Fatalf("failed to marshal MGF parameters: %s", err)
  2597  		}
  2598  
  2599  		serialized, err := asn1.Marshal(params)
  2600  		if err != nil {
  2601  			t.Fatalf("failed to marshal parameters: %s", err)
  2602  		}
  2603  
  2604  		return serialized
  2605  	}
  2606  
  2607  	for _, detail := range signatureAlgorithmDetails {
  2608  		if !detail.isRSAPSS {
  2609  			continue
  2610  		}
  2611  		generated := generateParams(detail.hash)
  2612  		if !bytes.Equal(detail.params.FullBytes, generated) {
  2613  			t.Errorf("hardcoded parameters for %s didn't match generated parameters: got (generated) %x, wanted (hardcoded) %x", detail.hash, generated, detail.params.FullBytes)
  2614  		}
  2615  	}
  2616  }
  2617  
  2618  func TestUnknownExtKey(t *testing.T) {
  2619  	const errorContains = "unknown extended key usage"
  2620  
  2621  	template := &x509.Certificate{
  2622  		SerialNumber: big.NewInt(10),
  2623  		DNSNames:     []string{"foo"},
  2624  		ExtKeyUsage:  []ExtKeyUsage{ExtKeyUsage(-1)},
  2625  	}
  2626  	signer, err := rsa.GenerateKey(rand.Reader, 1024)
  2627  	if err != nil {
  2628  		t.Errorf("failed to generate key for TestUnknownExtKey")
  2629  	}
  2630  
  2631  	_, err = CreateCertificate(rand.Reader, template, template, signer.Public(), signer)
  2632  	if !strings.Contains(err.Error(), errorContains) {
  2633  		t.Errorf("expected error containing %q, got %s", errorContains, err)
  2634  	}
  2635  }
  2636  
  2637  func TestIA5SANEnforcement(t *testing.T) {
  2638  	k, err := sm2.GenerateKey(rand.Reader)
  2639  	if err != nil {
  2640  		t.Fatalf("ecdsa.GenerateKey failed: %s", err)
  2641  	}
  2642  
  2643  	testURL, err := url.Parse("https://example.com/")
  2644  	if err != nil {
  2645  		t.Fatalf("url.Parse failed: %s", err)
  2646  	}
  2647  	testURL.RawQuery = "∞"
  2648  
  2649  	marshalTests := []struct {
  2650  		name          string
  2651  		template      *x509.Certificate
  2652  		expectedError string
  2653  	}{
  2654  		{
  2655  			name: "marshal: unicode dNSName",
  2656  			template: &x509.Certificate{
  2657  				SerialNumber: big.NewInt(0),
  2658  				DNSNames:     []string{"∞"},
  2659  			},
  2660  			expectedError: "x509: \"∞\" cannot be encoded as an IA5String",
  2661  		},
  2662  		{
  2663  			name: "marshal: unicode rfc822Name",
  2664  			template: &x509.Certificate{
  2665  				SerialNumber:   big.NewInt(0),
  2666  				EmailAddresses: []string{"∞"},
  2667  			},
  2668  			expectedError: "x509: \"∞\" cannot be encoded as an IA5String",
  2669  		},
  2670  		{
  2671  			name: "marshal: unicode uniformResourceIdentifier",
  2672  			template: &x509.Certificate{
  2673  				SerialNumber: big.NewInt(0),
  2674  				URIs:         []*url.URL{testURL},
  2675  			},
  2676  			expectedError: "x509: \"https://example.com/?∞\" cannot be encoded as an IA5String",
  2677  		},
  2678  	}
  2679  
  2680  	for _, tc := range marshalTests {
  2681  		t.Run(tc.name, func(t *testing.T) {
  2682  			_, err := CreateCertificate(rand.Reader, tc.template, tc.template, k.Public(), k)
  2683  			if err == nil {
  2684  				t.Errorf("expected CreateCertificate to fail with template: %v", tc.template)
  2685  			} else if err.Error() != tc.expectedError {
  2686  				t.Errorf("unexpected error: got %q, want %q", err.Error(), tc.expectedError)
  2687  			}
  2688  		})
  2689  	}
  2690  
  2691  	unmarshalTests := []struct {
  2692  		name          string
  2693  		cert          string
  2694  		expectedError string
  2695  	}{
  2696  		{
  2697  			name:          "unmarshal: unicode dNSName",
  2698  			cert:          "308201083081aea003020102020100300a06082a8648ce3d04030230003022180f30303031303130313030303030305a180f30303031303130313030303030305a30003059301306072a8648ce3d020106082a8648ce3d0301070342000424bcc48180d8d9db794028f2575ebe3cac79f04d7b0d0151c5292e588aac3668c495f108c626168462e0668c9705e08a211dd103a659d2684e0adf8c2bfd47baa315301330110603551d110101ff040730058203e2889e300a06082a8648ce3d04030203490030460221008ac7827ac326a6ee0fa70b2afe99af575ec60b975f820f3c25f60fff43fbccd0022100bffeed93556722d43d13e461d5b3e33efc61f6349300327d3a0196cb6da501c2",
  2699  			expectedError: "x509: SAN dNSName is malformed",
  2700  		},
  2701  		{
  2702  			name:          "unmarshal: unicode rfc822Name",
  2703  			cert:          "308201083081aea003020102020100300a06082a8648ce3d04030230003022180f30303031303130313030303030305a180f30303031303130313030303030305a30003059301306072a8648ce3d020106082a8648ce3d0301070342000405cb4c4ba72aac980f7b11b0285191425e29e196ce7c5df1c83f56886566e517f196657cc1b73de89ab84ce503fd634e2f2af88fde24c63ca536dc3a5eed2665a315301330110603551d110101ff040730058103e2889e300a06082a8648ce3d0403020349003046022100ed1431cd4b9bb03d88d1511a0ec128a51204375764c716280dc36e2a60142c8902210088c96d25cfaf97eea851ff17d87bb6fe619d6546656e1739f35c3566051c3d0f",
  2704  			expectedError: "x509: SAN rfc822Name is malformed",
  2705  		},
  2706  		{
  2707  			name:          "unmarshal: unicode uniformResourceIdentifier",
  2708  			cert:          "3082011b3081c3a003020102020100300a06082a8648ce3d04030230003022180f30303031303130313030303030305a180f30303031303130313030303030305a30003059301306072a8648ce3d020106082a8648ce3d03010703420004ce0a79b511701d9188e1ea76bcc5907f1db51de6cc1a037b803f256e8588145ca409d120288bfeb4e38f3088104674d374b35bb91fc80d768d1d519dbe2b0b5aa32a302830260603551d110101ff041c301a861868747470733a2f2f6578616d706c652e636f6d2f3fe2889e300a06082a8648ce3d0403020347003044022044f4697779fd1dae1e382d2452413c5c5ca67851e267d6bc64a8d164977c172c0220505015e657637aa1945d46e7650b6f59b968fc1508ca8b152c99f782446dfc81",
  2709  			expectedError: "x509: SAN uniformResourceIdentifier is malformed",
  2710  		},
  2711  	}
  2712  
  2713  	for _, tc := range unmarshalTests {
  2714  		der, err := hex.DecodeString(tc.cert)
  2715  		if err != nil {
  2716  			t.Fatalf("failed to decode test cert: %s", err)
  2717  		}
  2718  		_, err = ParseCertificate(der)
  2719  		if err == nil {
  2720  			t.Error("expected CreateCertificate to fail")
  2721  		} else if err.Error() != tc.expectedError {
  2722  			t.Errorf("unexpected error: got %q, want %q", err.Error(), tc.expectedError)
  2723  		}
  2724  	}
  2725  }
  2726  
  2727  type brokenSigner struct {
  2728  	pub crypto.PublicKey
  2729  }
  2730  
  2731  func (bs *brokenSigner) Public() crypto.PublicKey {
  2732  	return bs.pub
  2733  }
  2734  
  2735  func (bs *brokenSigner) Sign(_ io.Reader, _ []byte, _ crypto.SignerOpts) ([]byte, error) {
  2736  	return []byte{1, 2, 3}, nil
  2737  }
  2738  
  2739  func TestCreateCertificateBrokenSigner(t *testing.T) {
  2740  	template := &x509.Certificate{
  2741  		SerialNumber: big.NewInt(10),
  2742  		DNSNames:     []string{"example.com"},
  2743  	}
  2744  	expectedErr := "signature returned by signer is invalid"
  2745  	_, err := CreateCertificate(rand.Reader, template, template, testPrivateKey.Public(), &brokenSigner{testPrivateKey.Public()})
  2746  	if err == nil {
  2747  		t.Fatal("expected CreateCertificate to fail with a broken signer")
  2748  	} else if !strings.Contains(err.Error(), expectedErr) {
  2749  		t.Fatalf("CreateCertificate returned an unexpected error: got %q, want %q", err, expectedErr)
  2750  	}
  2751  }
  2752  
  2753  func TestCreateCertificateLegacy(t *testing.T) {
  2754  	sigAlg := MD5WithRSA
  2755  	template := &Certificate{
  2756  		SerialNumber:       big.NewInt(10),
  2757  		DNSNames:           []string{"example.com"},
  2758  		SignatureAlgorithm: sigAlg,
  2759  	}
  2760  	_, err := CreateCertificate(rand.Reader, template, template, testPrivateKey.Public(), &brokenSigner{testPrivateKey.Public()})
  2761  	if err == nil {
  2762  		t.Fatal("CreateCertificate didn't fail when SignatureAlgorithm = MD5WithRSA")
  2763  	}
  2764  }
  2765  
  2766  func (s *CertPool) mustCert(t *testing.T, n int) *Certificate {
  2767  	c, err := s.lazyCerts[n].getCert()
  2768  	if err != nil {
  2769  		t.Fatalf("failed to load cert %d: %v", n, err)
  2770  	}
  2771  	return c
  2772  }
  2773  
  2774  func allCerts(t *testing.T, p *CertPool) []*Certificate {
  2775  	all := make([]*Certificate, p.len())
  2776  	for i := range all {
  2777  		all[i] = p.mustCert(t, i)
  2778  	}
  2779  	return all
  2780  }
  2781  
  2782  // certPoolEqual reports whether a and b are equal, except for the
  2783  // function pointers.
  2784  func certPoolEqual(a, b *CertPool) bool {
  2785  	if (a != nil) != (b != nil) {
  2786  		return false
  2787  	}
  2788  	if a == nil {
  2789  		return true
  2790  	}
  2791  	if !reflect.DeepEqual(a.byName, b.byName) ||
  2792  		len(a.lazyCerts) != len(b.lazyCerts) {
  2793  		return false
  2794  	}
  2795  	for i := range a.lazyCerts {
  2796  		la, lb := a.lazyCerts[i], b.lazyCerts[i]
  2797  		if !bytes.Equal(la.rawSubject, lb.rawSubject) {
  2798  			return false
  2799  		}
  2800  		ca, err := la.getCert()
  2801  		if err != nil {
  2802  			panic(err)
  2803  		}
  2804  		cb, err := la.getCert()
  2805  		if err != nil {
  2806  			panic(err)
  2807  		}
  2808  		if !ca.Equal(cb) {
  2809  			return false
  2810  		}
  2811  	}
  2812  
  2813  	return true
  2814  }
  2815  
  2816  func TestCertificateRequestRoundtripFields(t *testing.T) {
  2817  	urlA, err := url.Parse("https://example.com/_")
  2818  	if err != nil {
  2819  		t.Fatal(err)
  2820  	}
  2821  	urlB, err := url.Parse("https://example.org/_")
  2822  	if err != nil {
  2823  		t.Fatal(err)
  2824  	}
  2825  	in := &x509.CertificateRequest{
  2826  		DNSNames:       []string{"example.com", "example.org"},
  2827  		EmailAddresses: []string{"a@example.com", "b@example.com"},
  2828  		IPAddresses:    []net.IP{net.IPv4(192, 0, 2, 0), net.IPv6loopback},
  2829  		URIs:           []*url.URL{urlA, urlB},
  2830  	}
  2831  	out := marshalAndParseCSR(t, in)
  2832  
  2833  	if !reflect.DeepEqual(in.DNSNames, out.DNSNames) {
  2834  		t.Fatalf("Unexpected DNSNames: got %v, want %v", out.DNSNames, in.DNSNames)
  2835  	}
  2836  	if !reflect.DeepEqual(in.EmailAddresses, out.EmailAddresses) {
  2837  		t.Fatalf("Unexpected EmailAddresses: got %v, want %v", out.EmailAddresses, in.EmailAddresses)
  2838  	}
  2839  	if len(in.IPAddresses) != len(out.IPAddresses) ||
  2840  		!in.IPAddresses[0].Equal(out.IPAddresses[0]) ||
  2841  		!in.IPAddresses[1].Equal(out.IPAddresses[1]) {
  2842  		t.Fatalf("Unexpected IPAddresses: got %v, want %v", out.IPAddresses, in.IPAddresses)
  2843  	}
  2844  	if !reflect.DeepEqual(in.URIs, out.URIs) {
  2845  		t.Fatalf("Unexpected URIs: got %v, want %v", out.URIs, in.URIs)
  2846  	}
  2847  }
  2848  
  2849  func TestParseCertificateRawEquals(t *testing.T) {
  2850  	p, _ := pem.Decode([]byte(pemCertificate))
  2851  	cert, err := ParseCertificate(p.Bytes)
  2852  	if err != nil {
  2853  		t.Fatalf("failed to parse certificate: %s", err)
  2854  	}
  2855  	if !bytes.Equal(p.Bytes, cert.Raw) {
  2856  		t.Fatalf("unexpected Certificate.Raw\ngot: %x\nwant: %x\n", cert.Raw, p.Bytes)
  2857  	}
  2858  }
  2859  
  2860  // mismatchingSigAlgIDPEM contains a certificate where the Certificate
  2861  // signatureAlgorithm and the TBSCertificate signature contain
  2862  // mismatching OIDs
  2863  const mismatchingSigAlgIDPEM = `-----BEGIN CERTIFICATE-----
  2864  MIIBBzCBrqADAgECAgEAMAoGCCqGSM49BAMCMAAwIhgPMDAwMTAxMDEwMDAwMDBa
  2865  GA8wMDAxMDEwMTAwMDAwMFowADBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABOqV
  2866  EDuVXxwZgIU3+dOwv1SsMu0xuV48hf7xmK8n7sAMYgllB+96DnPqBeboJj4snYnx
  2867  0AcE0PDVQ1l4Z3YXsQWjFTATMBEGA1UdEQEB/wQHMAWCA2FzZDAKBggqhkjOPQQD
  2868  AwNIADBFAiBi1jz/T2HT5nAfrD7zsgR+68qh7Erc6Q4qlxYBOgKG4QIhAOtjIn+Q
  2869  tA+bq+55P3ntxTOVRq0nv1mwnkjwt9cQR9Fn
  2870  -----END CERTIFICATE-----`
  2871  
  2872  // mismatchingSigAlgParamPEM contains a certificate where the Certificate
  2873  // signatureAlgorithm and the TBSCertificate signature contain
  2874  // mismatching parameters
  2875  const mismatchingSigAlgParamPEM = `-----BEGIN CERTIFICATE-----
  2876  MIIBCTCBrqADAgECAgEAMAoGCCqGSM49BAMCMAAwIhgPMDAwMTAxMDEwMDAwMDBa
  2877  GA8wMDAxMDEwMTAwMDAwMFowADBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABOqV
  2878  EDuVXxwZgIU3+dOwv1SsMu0xuV48hf7xmK8n7sAMYgllB+96DnPqBeboJj4snYnx
  2879  0AcE0PDVQ1l4Z3YXsQWjFTATMBEGA1UdEQEB/wQHMAWCA2FzZDAMBggqhkjOPQQD
  2880  AgUAA0gAMEUCIGLWPP9PYdPmcB+sPvOyBH7ryqHsStzpDiqXFgE6AobhAiEA62Mi
  2881  f5C0D5ur7nk/ee3FM5VGrSe/WbCeSPC31xBH0Wc=
  2882  -----END CERTIFICATE-----`
  2883  
  2884  func TestSigAlgMismatch(t *testing.T) {
  2885  	for _, certPEM := range []string{mismatchingSigAlgIDPEM, mismatchingSigAlgParamPEM} {
  2886  		b, _ := pem.Decode([]byte(certPEM))
  2887  		if b == nil {
  2888  			t.Fatalf("couldn't decode test certificate")
  2889  		}
  2890  		_, err := ParseCertificate(b.Bytes)
  2891  		if err == nil {
  2892  			t.Fatalf("expected ParseCertificate to fail")
  2893  		}
  2894  		expected := "x509: inner and outer signature algorithm identifiers don't match"
  2895  		if err.Error() != expected {
  2896  			t.Errorf("unexpected error from ParseCertificate: got %q, want %q", err.Error(), expected)
  2897  		}
  2898  	}
  2899  }
  2900  
  2901  const optionalAuthKeyIDPEM = `-----BEGIN CERTIFICATE-----
  2902  MIIFEjCCBHugAwIBAgICAQwwDQYJKoZIhvcNAQEFBQAwgbsxJDAiBgNVBAcTG1Zh
  2903  bGlDZXJ0IFZhbGlkYXRpb24gTmV0d29yazEXMBUGA1UEChMOVmFsaUNlcnQsIElu
  2904  Yy4xNTAzBgNVBAsTLFZhbGlDZXJ0IENsYXNzIDIgUG9saWN5IFZhbGlkYXRpb24g
  2905  QXV0aG9yaXR5MSEwHwYDVQQDExhodHRwOi8vd3d3LnZhbGljZXJ0LmNvbS8xIDAe
  2906  BgkqhkiG9w0BCQEWEWluZm9AdmFsaWNlcnQuY29tMB4XDTA0MDYyOTE3MzkxNloX
  2907  DTI0MDYyOTE3MzkxNlowaDELMAkGA1UEBhMCVVMxJTAjBgNVBAoTHFN0YXJmaWVs
  2908  ZCBUZWNobm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0ZWNoLmNvbS9yZXBvc2l0b3J5L3Jvb3QuY3Js
  2924  MFEGA1UdIARKMEgwRgYEVR0gADA+MDwGCCsGAQUFBwIBFjBodHRwOi8vY2VydGlm
  2925  aWNhdGVzLnN0YXJmaWVsZHRlY2guY29tL3JlcG9zaXRvcnkwDgYDVR0PAQH/BAQD
  2926  AgEGMA0GCSqGSIb3DQEBBQUAA4GBAKVi8afCXSWlcD284ipxs33kDTcdVWptobCr
  2927  mADkhWBKIMuh8D1195TaQ39oXCUIuNJ9MxB73HZn8bjhU3zhxoNbKXuNSm8uf0So
  2928  GkVrMgfHeMpkksK0hAzc3S1fTbvdiuo43NlmouxBulVtWmQ9twPMHOKRUJ7jCUSV
  2929  FxdzPcwl
  2930  -----END CERTIFICATE-----`
  2931  
  2932  func TestAuthKeyIdOptional(t *testing.T) {
  2933  	b, _ := pem.Decode([]byte(optionalAuthKeyIDPEM))
  2934  	if b == nil {
  2935  		t.Fatalf("couldn't decode test certificate")
  2936  	}
  2937  	_, err := ParseCertificate(b.Bytes)
  2938  	if err != nil {
  2939  		t.Fatalf("ParseCertificate to failed to parse certificate with optional authority key identifier fields: %s", err)
  2940  	}
  2941  }
  2942  
  2943  const largeOIDPEM = `
  2944  Certificate:
  2945      Data:
  2946          Version: 3 (0x2)
  2947          Serial Number:
  2948              da:ba:53:19:1b:09:4b:82:b2:89:26:7d:c7:6f:a0:02
  2949          Signature Algorithm: sha256WithRSAEncryption
  2950          Issuer: O = Acme Co
  2951          Validity
  2952              Not Before: Dec 21 16:59:27 2021 GMT
  2953              Not After : Dec 21 16:59:27 2022 GMT
  2954          Subject: O = Acme Co
  2955          Subject Public Key Info:
  2956              Public Key Algorithm: rsaEncryption
  2957                  RSA Public-Key: (2048 bit)
  2958                  Modulus:
  2959                      00:bf:17:16:d8:bc:29:9c:16:e5:76:b4:93:15:78:
  2960                      ad:6e:45:c5:4a:63:46:a1:b2:76:71:65:51:9c:14:
  2961                      c4:ea:74:13:e4:34:df:2f:2c:65:11:e8:56:52:69:
  2962                      11:f9:0e:fc:77:bb:63:a8:7c:1a:c6:a1:7b:6e:6c:
  2963                      e7:18:25:25:c9:e8:fb:06:7f:a2:a9:98:fe:2a:bc:
  2964                      8a:b3:75:b6:b8:7d:b6:c9:6b:29:08:32:22:10:cb:
  2965                      8d:d6:60:c8:83:ad:f5:58:91:d6:11:e8:55:56:fb:
  2966                      8f:a3:a2:9f:48:cb:79:e4:65:4a:8c:a6:52:64:9f:
  2967                      99:38:35:d4:d5:ac:6f:cf:a0:cb:42:8c:07:eb:21:
  2968                      17:31:3a:eb:91:7b:62:43:a4:75:5f:ef:a7:2f:94:
  2969                      f8:69:0b:d4:ec:09:e6:00:c0:8c:dd:07:63:0b:e4:
  2970                      77:aa:60:18:3c:a0:e0:ae:0a:ea:0e:52:3b:b4:fa:
  2971                      6a:30:1b:50:62:21:73:53:33:01:60:a1:6b:99:58:
  2972                      00:f3:77:c6:0f:46:19:ca:c2:5d:cd:f5:e2:52:4d:
  2973                      84:94:23:d3:32:2f:ae:5f:da:43:a1:19:95:d2:17:
  2974                      dd:49:14:b4:d9:48:1c:08:13:93:8e:d5:09:43:21:
  2975                      b6:ce:52:e8:87:bb:d2:60:0d:c6:4e:bf:c5:93:6a:
  2976                      c6:bf
  2977                  Exponent: 65537 (0x10001)
  2978          X509v3 extensions:
  2979              X509v3 Key Usage: critical
  2980                  Digital Signature, Key Encipherment
  2981              X509v3 Extended Key Usage:
  2982                  TLS Web Server Authentication
  2983              X509v3 Basic Constraints: critical
  2984                  CA:FALSE
  2985              X509v3 Subject Alternative Name:
  2986                  DNS:longOID.example
  2987              X509v3 Certificate Policies:
  2988                  Policy: 1.3.6.1.4.1.311.21.8.1492336001
  2989      Signature Algorithm: sha256WithRSAEncryption
  2990           72:77:8b:de:48:fb:6d:9a:94:b1:be:d4:90:7d:4c:e6:d3:79:
  2991           fa:fb:fc:3e:d5:3d:e9:a0:ce:28:2b:2f:94:77:3f:87:f8:9c:
  2992           9f:91:1c:f3:f6:58:91:15:6b:24:b9:ca:ae:9f:ee:ca:c8:31:
  2993           db:1a:3d:bb:6b:83:6d:bc:81:8b:a1:79:d5:3e:bb:dd:93:fe:
  2994           35:3e:b7:99:e0:d6:eb:58:0c:fd:42:73:dc:49:da:e2:b7:ae:
  2995           15:ee:e6:cc:aa:ef:91:41:9a:18:46:8d:4a:39:65:a2:85:3c:
  2996           7f:0c:41:f8:0b:9c:e8:1f:35:36:60:8d:8c:e0:8e:18:b1:06:
  2997           57:d0:4e:c4:c3:cd:8f:6f:e7:76:02:52:da:03:43:61:2b:b3:
  2998           bf:19:fd:73:0d:6a:0b:b4:b6:cb:a9:6f:70:4e:53:2a:54:07:
  2999           b3:74:fd:85:49:57:5b:23:8d:8c:6b:53:2b:09:e8:41:a5:80:
  3000           3f:69:1b:11:d1:6b:13:35:2e:f9:d6:50:15:d9:91:38:42:43:
  3001           e9:17:af:67:d9:96:a4:d1:6a:4f:cc:b4:a7:8e:48:1f:00:72:
  3002           69:de:4d:f1:73:a4:47:12:67:e9:f9:07:3e:79:75:90:42:b8:
  3003           d4:b5:fd:d1:7e:35:04:f7:00:04:cf:f1:36:be:0f:27:81:1f:
  3004           a6:ba:88:6c
  3005  -----BEGIN CERTIFICATE-----
  3006  MIIDHTCCAgWgAwIBAgIRANq6UxkbCUuCsokmfcdvoAIwDQYJKoZIhvcNAQELBQAw
  3007  EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0yMTEyMjExNjU5MjdaFw0yMjEyMjExNjU5
  3008  MjdaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
  3009  ggEKAoIBAQC/FxbYvCmcFuV2tJMVeK1uRcVKY0ahsnZxZVGcFMTqdBPkNN8vLGUR
  3010  6FZSaRH5Dvx3u2OofBrGoXtubOcYJSXJ6PsGf6KpmP4qvIqzdba4fbbJaykIMiIQ
  3011  y43WYMiDrfVYkdYR6FVW+4+jop9Iy3nkZUqMplJkn5k4NdTVrG/PoMtCjAfrIRcx
  3012  OuuRe2JDpHVf76cvlPhpC9TsCeYAwIzdB2ML5HeqYBg8oOCuCuoOUju0+mowG1Bi
  3013  IXNTMwFgoWuZWADzd8YPRhnKwl3N9eJSTYSUI9MyL65f2kOhGZXSF91JFLTZSBwI
  3014  E5OO1QlDIbbOUuiHu9JgDcZOv8WTasa/AgMBAAGjbjBsMA4GA1UdDwEB/wQEAwIF
  3015  oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBoGA1UdEQQTMBGC
  3016  D2xvbmdPSUQuZXhhbXBsZTAbBgNVHSAEFDASMBAGDisGAQQBgjcVCIXHzPsBMA0G
  3017  CSqGSIb3DQEBCwUAA4IBAQByd4veSPttmpSxvtSQfUzm03n6+/w+1T3poM4oKy+U
  3018  dz+H+JyfkRzz9liRFWskucqun+7KyDHbGj27a4NtvIGLoXnVPrvdk/41PreZ4Nbr
  3019  WAz9QnPcSdrit64V7ubMqu+RQZoYRo1KOWWihTx/DEH4C5zoHzU2YI2M4I4YsQZX
  3020  0E7Ew82Pb+d2AlLaA0NhK7O/Gf1zDWoLtLbLqW9wTlMqVAezdP2FSVdbI42Ma1Mr
  3021  CehBpYA/aRsR0WsTNS751lAV2ZE4QkPpF69n2Zak0WpPzLSnjkgfAHJp3k3xc6RH
  3022  Emfp+Qc+eXWQQrjUtf3RfjUE9wAEz/E2vg8ngR+muohs
  3023  -----END CERTIFICATE-----`
  3024  
  3025  func TestLargeOID(t *testing.T) {
  3026  	// See Issue 49678.
  3027  	b, _ := pem.Decode([]byte(largeOIDPEM))
  3028  	if b == nil {
  3029  		t.Fatalf("couldn't decode test certificate")
  3030  	}
  3031  	_, err := ParseCertificate(b.Bytes)
  3032  	if err != nil {
  3033  		t.Fatalf("ParseCertificate to failed to parse certificate with large OID: %s", err)
  3034  	}
  3035  }
  3036  
  3037  const uniqueIDPEM = `-----BEGIN CERTIFICATE-----
  3038  MIIFsDCCBJigAwIBAgIIrOyC1ydafZMwDQYJKoZIhvcNAQEFBQAwgY4xgYswgYgG
  3039  A1UEAx6BgABNAGkAYwByAG8AcwBvAGYAdAAgAEYAbwByAGUAZgByAG8AbgB0ACAA
  3040  VABNAEcAIABIAFQAVABQAFMAIABJAG4AcwBwAGUAYwB0AGkAbwBuACAAQwBlAHIA
  3041  dABpAGYAaQBjAGEAdABpAG8AbgAgAEEAdQB0AGgAbwByAGkAdAB5MB4XDTE0MDEx
  3042  ODAwNDEwMFoXDTE1MTExNTA5Mzc1NlowgZYxCzAJBgNVBAYTAklEMRAwDgYDVQQI
  3043  EwdqYWthcnRhMRIwEAYDVQQHEwlJbmRvbmVzaWExHDAaBgNVBAoTE3N0aG9ub3Jl
  3044  aG90ZWxyZXNvcnQxHDAaBgNVBAsTE3N0aG9ub3JlaG90ZWxyZXNvcnQxJTAjBgNV
  3045  BAMTHG1haWwuc3Rob25vcmVob3RlbHJlc29ydC5jb20wggEiMA0GCSqGSIb3DQEB
  3046  AQUAA4IBDwAwggEKAoIBAQCvuu0qpI+Ko2X84Twkf84cRD/rgp6vpgc5Ebejx/D4
  3047  PEVON5edZkazrMGocK/oQqIlRxx/lefponN/chlGcllcVVPWTuFjs8k+Aat6T1qp
  3048  4iXxZekAqX+U4XZMIGJD3PckPL6G2RQSlF7/LhGCsRNRdKpMWSTbou2Ma39g52Kf
  3049  gsl3SK/GwLiWpxpcSkNQD1hugguEIsQYLxbeNwpcheXZtxbBGguPzQ7rH8c5vuKU
  3050  BkMOzaiNKLzHbBdFSrua8KWwCJg76Vdq/q36O9GlW6YgG3i+A4pCJjXWerI1lWwX
  3051  Ktk5V+SvUHGey1bkDuZKJ6myMk2pGrrPWCT7jP7WskChAgMBAAGBCQBCr1dgEleo
  3052  cKOCAfswggH3MIHDBgNVHREEgbswgbiCHG1haWwuc3Rob25vcmVob3RlbHJlc29y
  3053  dC5jb22CIGFzaGNoc3ZyLnN0aG9ub3JlaG90ZWxyZXNvcnQuY29tgiRBdXRvRGlz
  3054  Y292ZXIuc3Rob25vcmVob3RlbHJlc29ydC5jb22CHEF1dG9EaXNjb3Zlci5ob3Rl
  3055  bHJlc29ydC5jb22CCEFTSENIU1ZSghdzdGhvbm9yZWhvdGVscmVzb3J0LmNvbYIP
  3056  aG90ZWxyZXNvcnQuY29tMCEGCSsGAQQBgjcUAgQUHhIAVwBlAGIAUwBlAHIAdgBl
  3057  AHIwHQYDVR0OBBYEFMAC3UR4FwAdGekbhMgnd6lMejtbMAsGA1UdDwQEAwIFoDAT
  3058  BgNVHSUEDDAKBggrBgEFBQcDATAJBgNVHRMEAjAAMIG/BgNVHQEEgbcwgbSAFGfF
  3059  6xihk+gJJ5TfwvtWe1UFnHLQoYGRMIGOMYGLMIGIBgNVBAMegYAATQBpAGMAcgBv
  3060  AHMAbwBmAHQAIABGAG8AcgBlAGYAcgBvAG4AdAAgAFQATQBHACAASABUAFQAUABT
  3061  ACAASQBuAHMAcABlAGMAdABpAG8AbgAgAEMAZQByAHQAaQBmAGkAYwBhAHQAaQBv
  3062  AG4AIABBAHUAdABoAG8AcgBpAHQAeYIIcKhXEmBXr0IwDQYJKoZIhvcNAQEFBQAD
  3063  ggEBABlSxyCMr3+ANr+WmPSjyN5YCJBgnS0IFCwJAzIYP87bcTye/U8eQ2+E6PqG
  3064  Q7Huj7nfHEw9qnGo+HNyPp1ad3KORzXDb54c6xEoi+DeuPzYHPbn4c3hlH49I0aQ
  3065  eWW2w4RslSWpLvO6Y7Lboyz2/Thk/s2kd4RHxkkWpH2ltPqJuYYg3X6oM5+gIFHJ
  3066  WGnh+ojZ5clKvS5yXh3Wkj78M6sb32KfcBk0Hx6NkCYPt60ODYmWtvqwtw6r73u5
  3067  TnTYWRNvo2svX69TriL+CkHY9O1Hkwf2It5zHl3gNiKTJVaak8AuEz/CKWZneovt
  3068  yYLwhUhg3PX5Co1VKYE+9TxloiE=
  3069  -----END CERTIFICATE-----`
  3070  
  3071  func TestParseUniqueID(t *testing.T) {
  3072  	b, _ := pem.Decode([]byte(uniqueIDPEM))
  3073  	if b == nil {
  3074  		t.Fatalf("couldn't decode test certificate")
  3075  	}
  3076  	cert, err := ParseCertificate(b.Bytes)
  3077  	if err != nil {
  3078  		t.Fatalf("ParseCertificate to failed to parse certificate with unique identifier id: %s", err)
  3079  	}
  3080  	if len(cert.Extensions) != 7 {
  3081  		t.Fatalf("unexpected number of extensions (probably because the extension section was not parsed): got %d, want 7", len(cert.Extensions))
  3082  	}
  3083  }
  3084  
  3085  func TestDisableSHA1ForCertOnly(t *testing.T) {
  3086  	defer func(old bool) { debugAllowSHA1 = old }(debugAllowSHA1)
  3087  	debugAllowSHA1 = false
  3088  
  3089  	tmpl := &Certificate{
  3090  		SerialNumber:          big.NewInt(1),
  3091  		NotBefore:             time.Now().Add(-time.Hour),
  3092  		NotAfter:              time.Now().Add(time.Hour),
  3093  		SignatureAlgorithm:    SHA1WithRSA,
  3094  		BasicConstraintsValid: true,
  3095  		IsCA:                  true,
  3096  		KeyUsage:              KeyUsageCertSign | KeyUsageCRLSign,
  3097  	}
  3098  	certDER, err := CreateCertificate(rand.Reader, tmpl, tmpl, rsaPrivateKey.Public(), rsaPrivateKey)
  3099  	if err != nil {
  3100  		t.Fatalf("failed to generate test cert: %s", err)
  3101  	}
  3102  	cert, err := ParseCertificate(certDER)
  3103  	if err != nil {
  3104  		t.Fatalf("failed to parse test cert: %s", err)
  3105  	}
  3106  
  3107  	err = cert.CheckSignatureFrom(cert)
  3108  	if err == nil {
  3109  		t.Error("expected CheckSignatureFrom to fail")
  3110  	} else if _, ok := err.(x509.InsecureAlgorithmError); !ok {
  3111  		t.Errorf("expected InsecureAlgorithmError error, got %T", err)
  3112  	}
  3113  
  3114  	crlDER, err := CreateRevocationList(rand.Reader, &x509.RevocationList{
  3115  		SignatureAlgorithm: SHA1WithRSA,
  3116  		Number:             big.NewInt(1),
  3117  		ThisUpdate:         time.Now().Add(-time.Hour),
  3118  		NextUpdate:         time.Now().Add(time.Hour),
  3119  	}, cert, rsaPrivateKey)
  3120  	if err != nil {
  3121  		t.Fatalf("failed to generate test CRL: %s", err)
  3122  	}
  3123  	// TODO(rolandshoemaker): this should be ParseRevocationList once it lands
  3124  	crl, err := ParseCRL(crlDER)
  3125  	if err != nil {
  3126  		t.Fatalf("failed to parse test CRL: %s", err)
  3127  	}
  3128  
  3129  	if err = cert.CheckCRLSignature(crl); err != nil {
  3130  		t.Errorf("unexpected error: %s", err)
  3131  	}
  3132  
  3133  	// This is an unrelated OCSP response, which will fail signature verification
  3134  	// but shouldn't return a InsecureAlgorithmError, since SHA1 should be allowed
  3135  	// for OCSP.
  3136  	ocspTBSHex := "30819fa2160414884451ff502a695e2d88f421bad90cf2cecbea7c180f32303133303631383037323434335a30743072304a300906052b0e03021a0500041448b60d38238df8456e4ee5843ea394111802979f0414884451ff502a695e2d88f421bad90cf2cecbea7c021100f78b13b946fc9635d8ab49de9d2148218000180f32303133303631383037323434335aa011180f32303133303632323037323434335a"
  3137  	ocspTBS, err := hex.DecodeString(ocspTBSHex)
  3138  	if err != nil {
  3139  		t.Fatalf("failed to decode OCSP response TBS hex: %s", err)
  3140  	}
  3141  
  3142  	err = cert.CheckSignature(SHA1WithRSA, ocspTBS, nil)
  3143  	if err != rsa.ErrVerification {
  3144  		t.Errorf("unexpected error: %s", err)
  3145  	}
  3146  }
  3147  
  3148  func TestOmitEmptyExtensions(t *testing.T) {
  3149  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  3150  	if err != nil {
  3151  		t.Fatal(err)
  3152  	}
  3153  	tmpl := &Certificate{
  3154  		SerialNumber: big.NewInt(1),
  3155  		Subject: pkix.Name{
  3156  			CommonName: ":)",
  3157  		},
  3158  		NotAfter:  time.Now().Add(time.Hour),
  3159  		NotBefore: time.Now().Add(-time.Hour),
  3160  	}
  3161  	der, err := CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  3162  	if err != nil {
  3163  		t.Fatal(err)
  3164  	}
  3165  
  3166  	emptyExtSeq := []byte{0xA3, 0x02, 0x30, 0x00}
  3167  	if bytes.Contains(der, emptyExtSeq) {
  3168  		t.Error("DER encoding contains the an empty extensions SEQUENCE")
  3169  	}
  3170  }
  3171  
  3172  var negativeSerialCert = `-----BEGIN CERTIFICATE-----
  3173  MIIBBTCBraADAgECAgH/MAoGCCqGSM49BAMCMA0xCzAJBgNVBAMTAjopMB4XDTIy
  3174  MDQxNDIzNTYwNFoXDTIyMDQxNTAxNTYwNFowDTELMAkGA1UEAxMCOikwWTATBgcq
  3175  hkjOPQIBBggqhkjOPQMBBwNCAAQ9ezsIsj+q17K87z/PXE/rfGRN72P/Wyn5d6oo
  3176  5M0ZbSatuntMvfKdX79CQxXAxN4oXk3Aov4jVSG12AcDI8ShMAoGCCqGSM49BAMC
  3177  A0cAMEQCIBzfBU5eMPT6m5lsR6cXaJILpAaiD9YxOl4v6dT3rzEjAiBHmjnHmAss
  3178  RqUAyJKFzqZxOlK2q4j2IYnuj5+LrLGbQA==
  3179  -----END CERTIFICATE-----`
  3180  
  3181  func TestParseNegativeSerial(t *testing.T) {
  3182  	pemBlock, _ := pem.Decode([]byte(negativeSerialCert))
  3183  	_, err := ParseCertificate(pemBlock.Bytes)
  3184  	if err != nil {
  3185  		t.Fatalf("failed to parse certificate: %s", err)
  3186  	}
  3187  }
  3188  
  3189  func TestCreateNegativeSerial(t *testing.T) {
  3190  	k, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  3191  	if err != nil {
  3192  		t.Fatal(err)
  3193  	}
  3194  	tmpl := &Certificate{
  3195  		SerialNumber: big.NewInt(-1),
  3196  		Subject: pkix.Name{
  3197  			CommonName: ":)",
  3198  		},
  3199  		NotAfter:  time.Now().Add(time.Hour),
  3200  		NotBefore: time.Now().Add(-time.Hour),
  3201  	}
  3202  	expectedErr := "x509: serial number must be positive"
  3203  	_, err = CreateCertificate(rand.Reader, tmpl, tmpl, k.Public(), k)
  3204  	if err == nil || err.Error() != expectedErr {
  3205  		t.Errorf("CreateCertificate returned unexpected error: want %q, got %q", expectedErr, err)
  3206  	}
  3207  }
  3208  
  3209  const dupExtCert = `-----BEGIN CERTIFICATE-----
  3210  MIIBrjCCARegAwIBAgIBATANBgkqhkiG9w0BAQsFADAPMQ0wCwYDVQQDEwR0ZXN0
  3211  MCIYDzAwMDEwMTAxMDAwMDAwWhgPMDAwMTAxMDEwMDAwMDBaMA8xDTALBgNVBAMT
  3212  BHRlc3QwgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJAoGBAMiFchnHms9l9NninAIz
  3213  SkY9acwl9Bk2AtmJrNCenFpiA17AcOO5q8DJYwdXi6WPKlVgcyH+ysW8XMWkq+CP
  3214  yhtF/+LMzl9odaUF2iUy3vgTC5gxGLWH5URVssx21Und2Pm2f4xyou5IVxbS9dxy
  3215  jLvV9PEY9BIb0H+zFthjhihDAgMBAAGjFjAUMAgGAioDBAIFADAIBgIqAwQCBQAw
  3216  DQYJKoZIhvcNAQELBQADgYEAlhQ4TQQKIQ8GUyzGiN/75TCtQtjhMGemxc0cNgre
  3217  d9rmm4DjydH0t7/sMCB56lQrfhJNplguzsbjFW4l245KbNKHfLiqwEGUgZjBNKur
  3218  ot6qX/skahLtt0CNOaFIge75HVKe/69OrWQGdp18dkay/KS4Glu8YMKIjOhfrUi1
  3219  NZA=
  3220  -----END CERTIFICATE-----`
  3221  
  3222  func TestDuplicateExtensionsCert(t *testing.T) {
  3223  	b, _ := pem.Decode([]byte(dupExtCert))
  3224  	if b == nil {
  3225  		t.Fatalf("couldn't decode test certificate")
  3226  	}
  3227  	_, err := ParseCertificate(b.Bytes)
  3228  	if err == nil {
  3229  		t.Fatal("ParseCertificate should fail when parsing certificate with duplicate extensions")
  3230  	}
  3231  }
  3232  
  3233  const dupExtCSR = `-----BEGIN CERTIFICATE REQUEST-----
  3234  MIIBczCB3QIBADAPMQ0wCwYDVQQDEwR0ZXN0MIGfMA0GCSqGSIb3DQEBAQUAA4GN
  3235  ADCBiQKBgQC5PbxMGVJ8aLF9lq/EvGObXTRMB7ieiZL9N+DJZg1n/ECCnZLIvYrr
  3236  ZmmDV7YZsClgxKGfjJB0RQFFyZElFM9EfHEs8NJdidDKCRdIhDXQWRyhXKevHvdm
  3237  CQNKzUeoxvdHpU/uscSkw6BgUzPyLyTx9A6ye2ix94z8Y9hGOBO2DQIDAQABoCUw
  3238  IwYJKoZIhvcNAQkOMRYwFDAIBgIqAwQCBQAwCAYCKgMEAgUAMA0GCSqGSIb3DQEB
  3239  CwUAA4GBAHROEsE7URk1knXmBnQtIHwoq663vlMcX3Hes58pUy020rWP8QkocA+X
  3240  VF18/phg3p5ILlS4fcbbP2bEeV0pePo2k00FDPsJEKCBAX2LKxbU7Vp2OuV2HM2+
  3241  VLOVx0i+/Q7fikp3hbN1JwuMTU0v2KL/IKoUcZc02+5xiYrnOIt5
  3242  -----END CERTIFICATE REQUEST-----`
  3243  
  3244  func TestDuplicateExtensionsCSR(t *testing.T) {
  3245  	b, _ := pem.Decode([]byte(dupExtCSR))
  3246  	if b == nil {
  3247  		t.Fatalf("couldn't decode test CSR")
  3248  	}
  3249  	_, err := ParseCertificateRequest(b.Bytes)
  3250  	if err == nil {
  3251  		t.Fatal("ParseCertificateRequest should fail when parsing CSR with duplicate extensions")
  3252  	}
  3253  }
  3254  
  3255  const dupAttCSR = `-----BEGIN CERTIFICATE REQUEST-----
  3256  MIIBbDCB1gIBADAPMQ0wCwYDVQQDEwR0ZXN0MIGfMA0GCSqGSIb3DQEBAQUAA4GN
  3257  ADCBiQKBgQCj5Po3PKO/JNuxr+B+WNfMIzqqYztdlv+mTQhT0jOR5rTkUvxeeHH8
  3258  YclryES2dOISjaUOTmOAr5GQIIdQl4Ql33Cp7ZR/VWcRn+qvTak0Yow+xVsDo0n4
  3259  7IcvvP6CJ7FRoYBUakVczeXLxCjLwdyK16VGJM06eRzDLykPxpPwLQIDAQABoB4w
  3260  DQYCKgMxBwwFdGVzdDEwDQYCKgMxBwwFdGVzdDIwDQYJKoZIhvcNAQELBQADgYEA
  3261  UJ8hsHxtnIeqb2ufHnQFJO+wEJhx2Uxm/BTuzHOeffuQkwATez4skZ7SlX9exgb7
  3262  6jRMRilqb4F7f8w+uDoqxRrA9zc8mwY16zPsyBhRet+ZGbj/ilgvGmtZ21qZZ/FU
  3263  0pJFJIVLM3l49Onr5uIt5+hCWKwHlgE0nGpjKLR3cMg=
  3264  -----END CERTIFICATE REQUEST-----`
  3265  
  3266  func TestDuplicateAttributesCSR(t *testing.T) {
  3267  	b, _ := pem.Decode([]byte(dupAttCSR))
  3268  	if b == nil {
  3269  		t.Fatalf("couldn't decode test CSR")
  3270  	}
  3271  	_, err := ParseCertificateRequest(b.Bytes)
  3272  	if err != nil {
  3273  		t.Fatal("ParseCertificateRequest should succeed when parsing CSR with duplicate attributes")
  3274  	}
  3275  }
  3276  
  3277  func TestRejectCriticalAKI(t *testing.T) {
  3278  	template := Certificate{
  3279  		SerialNumber: big.NewInt(1),
  3280  		Subject:      pkix.Name{CommonName: "Cert"},
  3281  		NotBefore:    time.Unix(1000, 0),
  3282  		NotAfter:     time.Unix(100000, 0),
  3283  		ExtraExtensions: []pkix.Extension{
  3284  			{
  3285  				Id:       asn1.ObjectIdentifier{2, 5, 29, 35},
  3286  				Critical: true,
  3287  				Value:    []byte{1, 2, 3},
  3288  			},
  3289  		},
  3290  	}
  3291  	certDER, err := CreateCertificate(rand.Reader, &template, &template, rsaPrivateKey.Public(), rsaPrivateKey)
  3292  	if err != nil {
  3293  		t.Fatalf("CreateCertificate() unexpected error: %v", err)
  3294  	}
  3295  	expectedErr := "x509: authority key identifier incorrectly marked critical"
  3296  	_, err = ParseCertificate(certDER)
  3297  	if err == nil || err.Error() != expectedErr {
  3298  		t.Fatalf("ParseCertificate() unexpected error: %v, want: %s", err, expectedErr)
  3299  	}
  3300  }
  3301  
  3302  func TestRejectCriticalAIA(t *testing.T) {
  3303  	template := Certificate{
  3304  		SerialNumber: big.NewInt(1),
  3305  		Subject:      pkix.Name{CommonName: "Cert"},
  3306  		NotBefore:    time.Unix(1000, 0),
  3307  		NotAfter:     time.Unix(100000, 0),
  3308  		ExtraExtensions: []pkix.Extension{
  3309  			{
  3310  				Id:       asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 1, 1},
  3311  				Critical: true,
  3312  				Value:    []byte{1, 2, 3},
  3313  			},
  3314  		},
  3315  	}
  3316  	certDER, err := CreateCertificate(rand.Reader, &template, &template, rsaPrivateKey.Public(), rsaPrivateKey)
  3317  	if err != nil {
  3318  		t.Fatalf("CreateCertificate() unexpected error: %v", err)
  3319  	}
  3320  	expectedErr := "x509: authority info access incorrectly marked critical"
  3321  	_, err = ParseCertificate(certDER)
  3322  	if err == nil || err.Error() != expectedErr {
  3323  		t.Fatalf("ParseCertificate() unexpected error: %v, want: %s", err, expectedErr)
  3324  	}
  3325  }
  3326  
  3327  func TestRejectCriticalSKI(t *testing.T) {
  3328  	template := Certificate{
  3329  		SerialNumber: big.NewInt(1),
  3330  		Subject:      pkix.Name{CommonName: "Cert"},
  3331  		NotBefore:    time.Unix(1000, 0),
  3332  		NotAfter:     time.Unix(100000, 0),
  3333  		ExtraExtensions: []pkix.Extension{
  3334  			{
  3335  				Id:       asn1.ObjectIdentifier{2, 5, 29, 14},
  3336  				Critical: true,
  3337  				Value:    []byte{1, 2, 3},
  3338  			},
  3339  		},
  3340  	}
  3341  	certDER, err := CreateCertificate(rand.Reader, &template, &template, rsaPrivateKey.Public(), rsaPrivateKey)
  3342  	if err != nil {
  3343  		t.Fatalf("CreateCertificate() unexpected error: %v", err)
  3344  	}
  3345  	expectedErr := "x509: subject key identifier incorrectly marked critical"
  3346  	_, err = ParseCertificate(certDER)
  3347  	if err == nil || err.Error() != expectedErr {
  3348  		t.Fatalf("ParseCertificate() unexpected error: %v, want: %s", err, expectedErr)
  3349  	}
  3350  }