本文整理匯總了Golang中crypto/tls.LoadX509KeyPair函數的典型用法代碼示例。如果您正苦於以下問題:Golang LoadX509KeyPair函數的具體用法?Golang LoadX509KeyPair怎麽用?Golang LoadX509KeyPair使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了LoadX509KeyPair函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestWithClientCertificateAuthenticationMultipeCAsMultipleFiles
// TestWithClientCertificateAuthentication
// Use two CA:s in two different files and test that clients with client signed by either of them can connect
func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipeCAsMultipleFiles(c *check.C) {
cmd := exec.Command(traefikBinary, "--configFile=fixtures/https/clientca/https_2ca2config.toml")
err := cmd.Start()
c.Assert(err, checker.IsNil)
defer cmd.Process.Kill()
time.Sleep(500 * time.Millisecond)
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
ServerName: "snitest.com",
Certificates: []tls.Certificate{},
}
// Connection without client certificate should fail
conn, err := tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
// Connect with client signed by ca1
cert, err := tls.LoadX509KeyPair("fixtures/https/clientca/client1.crt", "fixtures/https/clientca/client1.key")
c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))
conn.Close()
// Connect with client signed by ca2
tlsConfig = &tls.Config{
InsecureSkipVerify: true,
ServerName: "snitest.com",
Certificates: []tls.Certificate{},
}
cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client2.crt", "fixtures/https/clientca/client2.key")
c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.IsNil, check.Commentf("failed to connect to server"))
conn.Close()
// Connect with client signed by ca3 should fail
tlsConfig = &tls.Config{
InsecureSkipVerify: true,
ServerName: "snitest.com",
Certificates: []tls.Certificate{},
}
cert, err = tls.LoadX509KeyPair("fixtures/https/clientca/client3.crt", "fixtures/https/clientca/client3.key")
c.Assert(err, checker.IsNil, check.Commentf("unable to load client certificate and key"))
tlsConfig.Certificates = append(tlsConfig.Certificates, cert)
conn, err = tls.Dial("tcp", "127.0.0.1:4443", tlsConfig)
c.Assert(err, checker.NotNil, check.Commentf("should not be allowed to connect to server"))
}
示例2: TestTLSTransport
func TestTLSTransport(t *testing.T) {
certFile := "./ssl-cert-snakeoil.pem"
keyFile := "./ssl-cert-snakeoil.key"
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
t.Fatalf("Cannot load TLS certificates: [%s]", err)
}
serverCfg := &tls.Config{
Certificates: []tls.Certificate{cert},
}
clientCfg := &tls.Config{
InsecureSkipVerify: true,
}
addr := getRandomAddr()
s := NewTLSServer(addr, echoHandler, serverCfg)
if err := s.Start(); err != nil {
t.Fatalf("Server.Start() failed: [%s]", err)
}
defer s.Stop()
c := NewTLSClient(addr, clientCfg)
c.Start()
defer c.Stop()
testIntClient(t, c)
}
示例3: setupTLSConfig
func setupTLSConfig(sslOpts *SslOptions) (*tls.Config, error) {
certPool := x509.NewCertPool()
// ca cert is optional
if sslOpts.CaPath != "" {
pem, err := ioutil.ReadFile(sslOpts.CaPath)
if err != nil {
return nil, fmt.Errorf("connectionpool: unable to open CA certs: %v", err)
}
if !certPool.AppendCertsFromPEM(pem) {
return nil, errors.New("connectionpool: failed parsing or CA certs")
}
}
mycert, err := tls.LoadX509KeyPair(sslOpts.CertPath, sslOpts.KeyPath)
if err != nil {
return nil, fmt.Errorf("connectionpool: unable to load X509 key pair: %v", err)
}
config := &tls.Config{
Certificates: []tls.Certificate{mycert},
RootCAs: certPool,
}
config.InsecureSkipVerify = !sslOpts.EnableHostVerification
return config, nil
}
示例4: NewTLSConfig
func NewTLSConfig(certFile, keyFile, caCertFile string) (*tls.Config, error) {
tlsCert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, fmt.Errorf("failed to load keypair: %s", err.Error())
}
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{tlsCert},
InsecureSkipVerify: false,
ClientAuth: tls.RequireAndVerifyClientCert,
MinVersion: tls.VersionTLS12,
}
if caCertFile != "" {
certBytes, err := ioutil.ReadFile(caCertFile)
if err != nil {
return nil, fmt.Errorf("failed read ca cert file: %s", err.Error())
}
caCertPool := x509.NewCertPool()
if ok := caCertPool.AppendCertsFromPEM(certBytes); !ok {
return nil, errors.New("Unable to load caCert")
}
tlsConfig.RootCAs = caCertPool
tlsConfig.ClientCAs = caCertPool
}
return tlsConfig, nil
}
示例5: openTLSClient
func openTLSClient(ipPort string) (*tls.Conn, error) {
// Note this loads standard x509 certificates, test keys can be
// generated with makecert.sh
log.Printf("Loading certificates from directory: %s\n", *certDir)
cert, err := tls.LoadX509KeyPair(*certDir+"/server.pem", *certDir+"/server.key")
if err != nil {
log.Fatalf("server: loadkeys: %s", err)
}
// InsecureSkipVerify required for unsigned certs with Go1 and later.
config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
conn, err := tls.Dial("tcp", ipPort, &config)
if err != nil {
log.Fatalf("client: dial: %s", err)
}
log.Println("client: connected to: ", conn.RemoteAddr())
// This shows the public key of the server, we will accept any key, but
// we could terminate the connection based on the public key if desired.
state := conn.ConnectionState()
for _, v := range state.PeerCertificates {
log.Printf("Client: Server public key is:\n%x\n", v.PublicKey.(*rsa.PublicKey).N)
}
// Lets verify behind the doubt that both ends of the connection
// have completed the handshake and negotiated a SSL connection
log.Println("client: handshake: ", state.HandshakeComplete)
log.Println("client: mutual: ", state.NegotiatedProtocolIsMutual)
// All TLS handling has completed, now to pass the connection off to
// go-rpcgen/protobuf/AddService
return conn, err
}
示例6: listenAndServeTLS
// Overridden version of net/http added so we can manage the listener.
func (s *Server) listenAndServeTLS(certFile, keyFile string) error {
addr := s.Server.Addr
if addr == "" {
addr = ":https"
}
config := &tls.Config{}
if s.Server.TLSConfig != nil {
*config = *s.Server.TLSConfig
}
if config.NextProtos == nil {
config.NextProtos = []string{"http/1.1"}
}
var err error
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
conn, err := net.Listen("tcp", addr)
if err != nil {
return err
}
tlsListener := tls.NewListener(conn, config)
s.listener = tlsListener
return s.Server.Serve(tlsListener)
}
示例7: NewSSLTestServer
func NewSSLTestServer(t testing.TB, protocol uint8) *TestServer {
pem, err := ioutil.ReadFile("testdata/pki/ca.crt")
certPool := x509.NewCertPool()
if !certPool.AppendCertsFromPEM(pem) {
t.Fatalf("Failed parsing or appending certs")
}
mycert, err := tls.LoadX509KeyPair("testdata/pki/cassandra.crt", "testdata/pki/cassandra.key")
if err != nil {
t.Fatalf("could not load cert")
}
config := &tls.Config{
Certificates: []tls.Certificate{mycert},
RootCAs: certPool,
}
listen, err := tls.Listen("tcp", "127.0.0.1:0", config)
if err != nil {
t.Fatal(err)
}
headerSize := 8
if protocol > protoVersion2 {
headerSize = 9
}
srv := &TestServer{
Address: listen.Addr().String(),
listen: listen,
t: t,
protocol: protocol,
headerSize: headerSize,
quit: make(chan struct{}),
}
go srv.serve()
return srv
}
示例8: New
// New Apn with cert_filename and key_filename.
func New(cert_filename string, key_filename string, server string, timeout time.Duration, buffer int) (*Apn, error) {
echan := make(chan error)
cert, err := tls.LoadX509KeyPair(cert_filename, key_filename)
if err != nil {
return nil, err
}
nameport := strings.Split(server, ":")
certificate := []tls.Certificate{cert}
conf := &tls.Config{
Certificates: certificate,
ServerName: nameport[0],
}
ret := &Apn{
ErrorChan: echan,
server: server,
conf: conf,
timeout: timeout,
sendChan: make(chan *sendArg),
errorChan: echan,
buffer: buffer,
sentChan: make(chan *sendArg, buffer),
}
go sendLoop(ret)
return ret, err
}
示例9: clientTLS
func clientTLS() *tls.Config {
tlsConfig := &tls.Config{}
cert, err := tls.LoadX509KeyPair("test/client0.crt", "test/client0.key")
if err != nil {
log.Fatalf("Can not load certificate: %s", err.Error())
}
tlsConfig.Certificates = []tls.Certificate{cert}
certPool := x509.NewCertPool()
pem, err := ioutil.ReadFile("test/ca.crt")
if err != nil {
log.Fatalf("Can not read CA for client tls: %s", err.Error())
}
ok := certPool.AppendCertsFromPEM(pem)
if !ok {
log.Fatalf("Can not append cert")
}
tlsConfig.RootCAs = certPool
return tlsConfig
}
示例10: NewTimeoutClient
// apps will set two OS variables:
// atscale_http_sslcert - location of the http ssl cert
// atscale_http_sslkey - location of the http ssl key
func NewTimeoutClient(cTimeout time.Duration, rwTimeout time.Duration, useClientCerts bool) *http.Client {
certLocation := os.Getenv("atscale_http_sslcert")
keyLocation := os.Getenv("atscale_http_sslkey")
caFile := os.Getenv("atscale_ca_file")
// default
tlsConfig := &tls.Config{InsecureSkipVerify: true}
if useClientCerts && len(certLocation) > 0 && len(keyLocation) > 0 {
// Load client cert if available
cert, err := tls.LoadX509KeyPair(certLocation, keyLocation)
if err == nil {
if len(caFile) > 0 {
caCertPool := x509.NewCertPool()
caCert, err := ioutil.ReadFile(caFile)
if err != nil {
fmt.Printf("Error setting up caFile [%s]:%v\n", caFile, err)
}
caCertPool.AppendCertsFromPEM(caCert)
tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true, RootCAs: caCertPool}
tlsConfig.BuildNameToCertificate()
} else {
tlsConfig = &tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
}
}
}
return &http.Client{
Transport: &http.Transport{
TLSClientConfig: tlsConfig,
Dial: timeoutDialer(cTimeout, rwTimeout),
},
}
}
示例11: TestGetTrustServiceTLSSuccess
// The rest of the functionality of getTrustService depends upon
// utils.ConfigureClientTLS, so this test just asserts that if successful,
// the correct tls.Config is returned based on all the configuration parameters
func TestGetTrustServiceTLSSuccess(t *testing.T) {
keypair, err := tls.LoadX509KeyPair(Cert, Key)
assert.NoError(t, err, "Unable to load cert and key for testing")
tlspart := fmt.Sprintf(`"tls_client_cert": "%s", "tls_client_key": "%s"`,
Cert, Key)
var registerCalled = 0
var fakeRegister = func(_ string, _ func() error, _ time.Duration) {
registerCalled++
}
var tlsConfig *tls.Config
var fakeNewSigner = func(_, _ string, c *tls.Config) *client.NotarySigner {
tlsConfig = c
return &client.NotarySigner{}
}
trust, algo, err := getTrustService(
configure(fmt.Sprintf(trustTLSConfigTemplate, tlspart)),
fakeNewSigner, fakeRegister)
assert.NoError(t, err)
assert.IsType(t, &client.NotarySigner{}, trust)
assert.Equal(t, "ecdsa", algo)
assert.Len(t, tlsConfig.Certificates, 1)
assert.True(t, reflect.DeepEqual(keypair, tlsConfig.Certificates[0]))
// health function registered
assert.Equal(t, 1, registerCalled)
}
示例12: reconnect
func (p *apnsPushService) reconnect(psp *PushServiceProvider) (net.Conn, error) {
name := psp.Name()
p.connLock.Lock()
defer p.connLock.Unlock()
if conn, ok := p.conns[name]; ok {
conn.Close()
}
cert, err := tls.LoadX509KeyPair(psp.FixedData["cert"], psp.FixedData["key"])
if err != nil {
return nil, NewBadPushServiceProviderWithDetails(psp, err.Error())
}
conf := &tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: true,
}
tlsconn, err := tls.Dial("tcp", psp.VolatileData["addr"], conf)
if err != nil {
return nil, NewConnectionError(err)
}
err = tlsconn.Handshake()
if err != nil {
return nil, NewConnectionError(err)
}
p.conns[name] = tlsconn
return tlsconn, nil
}
示例13: ListenTLS
// ListenTLS is a convenience method that creates an https listener using the
// provided cert and key files. Use this method if you need access to the
// listener object directly. When ready, pass it to the Serve method.
func (srv *Server) ListenTLS(certFile, keyFile string) (net.Listener, error) {
// Create the listener ourselves so we can control its lifetime
addr := srv.Addr
if addr == "" {
addr = ":https"
}
config := &tls.Config{}
if srv.TLSConfig != nil {
*config = *srv.TLSConfig
}
var err error
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return nil, err
}
conn, err := srv.newTCPListener(addr)
if err != nil {
return nil, err
}
srv.TLSConfig = config
tlsListener := tls.NewListener(conn, config)
return tlsListener, nil
}
示例14: listenTLS
func listenTLS(addr string) (net.Listener, error) {
host, _, err := net.SplitHostPort(addr)
if err != nil {
return nil, fmt.Errorf("Unable to split host and port for %v: %v\n", addr, err)
}
ctx := CertContext{
PKFile: "key.pem",
ServerCertFile: "cert.pem",
}
err = ctx.InitServerCert(host)
if err != nil {
return nil, fmt.Errorf("Unable to init server cert: %s\n", err)
}
tlsConfig := tlsdefaults.Server()
cert, err := tls.LoadX509KeyPair(ctx.ServerCertFile, ctx.PKFile)
if err != nil {
return nil, fmt.Errorf("Unable to load certificate and key from %s and %s: %s\n", ctx.ServerCertFile, ctx.PKFile, err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
listener, err := tls.Listen("tcp", addr, tlsConfig)
if err != nil {
return nil, fmt.Errorf("Unable to listen for tls connections at %s: %s\n", addr, err)
}
return listener, err
}
示例15: ListenAndServeTLS
// ListenAndServeTLS provides a graceful equivalent of net/http.Serve.ListenAndServeTLS.
func (s *GracefulServer) ListenAndServeTLS(certFile, keyFile string) error {
// direct lift from net/http/server.go
addr := s.Addr
if addr == "" {
addr = ":https"
}
config := &tls.Config{}
if s.TLSConfig != nil {
*config = *s.TLSConfig
}
if config.NextProtos == nil {
config.NextProtos = []string{"http/1.1"}
}
var err error
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
ln, err := net.Listen("tcp", addr)
if err != nil {
return err
}
return s.Serve(tls.NewListener(ln, config))
}