...
Run Format

Source file src/crypto/tls/example_test.go

Documentation: crypto/tls

     1  // Copyright 2014 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package tls_test
     6  
     7  import (
     8  	"crypto/tls"
     9  	"crypto/x509"
    10  	"log"
    11  	"net/http"
    12  	"net/http/httptest"
    13  	"os"
    14  	"time"
    15  )
    16  
    17  // zeroSource is an io.Reader that returns an unlimited number of zero bytes.
    18  type zeroSource struct{}
    19  
    20  func (zeroSource) Read(b []byte) (n int, err error) {
    21  	for i := range b {
    22  		b[i] = 0
    23  	}
    24  
    25  	return len(b), nil
    26  }
    27  
    28  func ExampleDial() {
    29  	// Connecting with a custom root-certificate set.
    30  
    31  	const rootPEM = `
    32  -----BEGIN CERTIFICATE-----
    33  MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT
    34  MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i
    35  YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG
    36  EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy
    37  bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB
    38  AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP
    39  VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv
    40  h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE
    41  ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ
    42  EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC
    43  DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7
    44  qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD
    45  VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g
    46  K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI
    47  KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n
    48  ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB
    49  BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY
    50  /iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/
    51  zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza
    52  HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto
    53  WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6
    54  yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx
    55  -----END CERTIFICATE-----`
    56  
    57  	// First, create the set of root certificates. For this example we only
    58  	// have one. It's also possible to omit this in order to use the
    59  	// default root set of the current operating system.
    60  	roots := x509.NewCertPool()
    61  	ok := roots.AppendCertsFromPEM([]byte(rootPEM))
    62  	if !ok {
    63  		panic("failed to parse root certificate")
    64  	}
    65  
    66  	conn, err := tls.Dial("tcp", "mail.google.com:443", &tls.Config{
    67  		RootCAs: roots,
    68  	})
    69  	if err != nil {
    70  		panic("failed to connect: " + err.Error())
    71  	}
    72  	conn.Close()
    73  }
    74  
    75  func ExampleConfig_keyLogWriter() {
    76  	// Debugging TLS applications by decrypting a network traffic capture.
    77  
    78  	// WARNING: Use of KeyLogWriter compromises security and should only be
    79  	// used for debugging.
    80  
    81  	// Dummy test HTTP server for the example with insecure random so output is
    82  	// reproducible.
    83  	server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {}))
    84  	server.TLS = &tls.Config{
    85  		Rand: zeroSource{}, // for example only; don't do this.
    86  	}
    87  	server.StartTLS()
    88  	defer server.Close()
    89  
    90  	// Typically the log would go to an open file:
    91  	// w, err := os.OpenFile("tls-secrets.txt", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
    92  	w := os.Stdout
    93  
    94  	client := &http.Client{
    95  		Transport: &http.Transport{
    96  			TLSClientConfig: &tls.Config{
    97  				KeyLogWriter: w,
    98  
    99  				Rand:               zeroSource{}, // for reproducible output; don't do this.
   100  				InsecureSkipVerify: true,         // test server certificate is not trusted.
   101  			},
   102  		},
   103  	}
   104  	resp, err := client.Get(server.URL)
   105  	if err != nil {
   106  		log.Fatalf("Failed to get URL: %v", err)
   107  	}
   108  	resp.Body.Close()
   109  
   110  	// The resulting file can be used with Wireshark to decrypt the TLS
   111  	// connection by setting (Pre)-Master-Secret log filename in SSL Protocol
   112  	// preferences.
   113  
   114  	// Output:
   115  	// CLIENT_RANDOM 0000000000000000000000000000000000000000000000000000000000000000 baca0df460a688e44ce018b025183cc2353ae01f89755ef766eedd3ecc302888ee3b3a22962e45f48c20df15a98c0e80
   116  }
   117  
   118  func ExampleLoadX509KeyPair() {
   119  	cert, err := tls.LoadX509KeyPair("testdata/example-cert.pem", "testdata/example-key.pem")
   120  	if err != nil {
   121  		log.Fatal(err)
   122  	}
   123  	cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
   124  	listener, err := tls.Listen("tcp", ":2000", cfg)
   125  	if err != nil {
   126  		log.Fatal(err)
   127  	}
   128  	_ = listener
   129  }
   130  
   131  func ExampleX509KeyPair() {
   132  	certPem := []byte(`-----BEGIN CERTIFICATE-----
   133  MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
   134  DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
   135  EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
   136  7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
   137  5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
   138  BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
   139  NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
   140  Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
   141  6MF9+Yw1Yy0t
   142  -----END CERTIFICATE-----`)
   143  	keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----
   144  MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
   145  AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
   146  EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
   147  -----END EC PRIVATE KEY-----`)
   148  	cert, err := tls.X509KeyPair(certPem, keyPem)
   149  	if err != nil {
   150  		log.Fatal(err)
   151  	}
   152  	cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
   153  	listener, err := tls.Listen("tcp", ":2000", cfg)
   154  	if err != nil {
   155  		log.Fatal(err)
   156  	}
   157  	_ = listener
   158  }
   159  
   160  func ExampleX509KeyPair_httpServer() {
   161  	certPem := []byte(`-----BEGIN CERTIFICATE-----
   162  MIIBhTCCASugAwIBAgIQIRi6zePL6mKjOipn+dNuaTAKBggqhkjOPQQDAjASMRAw
   163  DgYDVQQKEwdBY21lIENvMB4XDTE3MTAyMDE5NDMwNloXDTE4MTAyMDE5NDMwNlow
   164  EjEQMA4GA1UEChMHQWNtZSBDbzBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABD0d
   165  7VNhbWvZLWPuj/RtHFjvtJBEwOkhbN/BnnE8rnZR8+sbwnc/KhCk3FhnpHZnQz7B
   166  5aETbbIgmuvewdjvSBSjYzBhMA4GA1UdDwEB/wQEAwICpDATBgNVHSUEDDAKBggr
   167  BgEFBQcDATAPBgNVHRMBAf8EBTADAQH/MCkGA1UdEQQiMCCCDmxvY2FsaG9zdDo1
   168  NDUzgg4xMjcuMC4wLjE6NTQ1MzAKBggqhkjOPQQDAgNIADBFAiEA2zpJEPQyz6/l
   169  Wf86aX6PepsntZv2GYlA5UpabfT2EZICICpJ5h/iI+i341gBmLiAFQOyTDT+/wQc
   170  6MF9+Yw1Yy0t
   171  -----END CERTIFICATE-----`)
   172  	keyPem := []byte(`-----BEGIN EC PRIVATE KEY-----
   173  MHcCAQEEIIrYSSNQFaA2Hwf1duRSxKtLYX5CB04fSeQ6tF1aY/PuoAoGCCqGSM49
   174  AwEHoUQDQgAEPR3tU2Fta9ktY+6P9G0cWO+0kETA6SFs38GecTyudlHz6xvCdz8q
   175  EKTcWGekdmdDPsHloRNtsiCa697B2O9IFA==
   176  -----END EC PRIVATE KEY-----`)
   177  	cert, err := tls.X509KeyPair(certPem, keyPem)
   178  	if err != nil {
   179  		log.Fatal(err)
   180  	}
   181  	cfg := &tls.Config{Certificates: []tls.Certificate{cert}}
   182  	srv := &http.Server{
   183  		TLSConfig:    cfg,
   184  		ReadTimeout:  time.Minute,
   185  		WriteTimeout: time.Minute,
   186  	}
   187  	log.Fatal(srv.ListenAndServeTLS("", ""))
   188  }
   189  

View as plain text