本文整理汇总了Golang中crypto/tls.LoadX509KeyPair函数的典型用法代码示例。如果您正苦于以下问题:Golang LoadX509KeyPair函数的具体用法?Golang LoadX509KeyPair怎么用?Golang LoadX509KeyPair使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了LoadX509KeyPair函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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"))
}
开发者ID:vdemeester,项目名称:traefik,代码行数:56,代码来源:https_test.go
示例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)
}
开发者ID:BobbWu,项目名称:gorpc,代码行数:27,代码来源:rpc_test.go
示例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
}
开发者ID:apaoww,项目名称:gocqltable,代码行数:28,代码来源:connectionpool.go
示例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
}
开发者ID:sunatthegilddotcom,项目名称:loggregator,代码行数:29,代码来源:tls_listener.go
示例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
}
开发者ID:kylelemons,项目名称:go-rpcgen,代码行数:32,代码来源:client.go
示例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)
}
开发者ID:GeertJohan,项目名称:etcd,代码行数:30,代码来源:server.go
示例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
}
开发者ID:robmccoll,项目名称:gocql,代码行数:35,代码来源:conn_test.go
示例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
}
开发者ID:codescrapper,项目名称:Go-Apns,代码行数:29,代码来源:apns.go
示例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
}
开发者ID:sisatech,项目名称:raft,代码行数:27,代码来源:raft_test.go
示例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),
},
}
}
开发者ID:mattbaird,项目名称:tableau4go,代码行数:34,代码来源:httputil.go
示例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)
}
开发者ID:NathanMcCauley,项目名称:notary,代码行数:32,代码来源:main_test.go
示例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
}
开发者ID:jritchie,项目名称:pushsrv,代码行数:27,代码来源:apns.go
示例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
}
开发者ID:stellar,项目名称:bridge-server,代码行数:32,代码来源:graceful.go
示例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
}
开发者ID:Nuos,项目名称:chained-server,代码行数:28,代码来源:tls.go
示例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))
}
开发者ID:cloudron-io,项目名称:mattermost,代码行数:29,代码来源:server.go
示例16: NewTLSServer
// NewTLSServer creates and starts a TLS-enabled testing server.
func NewTLSServer(bind string, containerChan chan<- *docker.Container, hook func(*http.Request), tlsConfig TLSConfig) (*DockerServer, error) {
listener, err := net.Listen("tcp", bind)
if err != nil {
return nil, err
}
defaultCertificate, err := tls.LoadX509KeyPair(tlsConfig.CertPath, tlsConfig.CertKeyPath)
if err != nil {
return nil, err
}
tlsServerConfig := new(tls.Config)
tlsServerConfig.Certificates = []tls.Certificate{defaultCertificate}
if tlsConfig.RootCAPath != "" {
rootCertPEM, err := ioutil.ReadFile(tlsConfig.RootCAPath)
if err != nil {
return nil, err
}
certsPool := x509.NewCertPool()
certsPool.AppendCertsFromPEM(rootCertPEM)
tlsServerConfig.RootCAs = certsPool
}
tlsListener := tls.NewListener(listener, tlsServerConfig)
server := buildDockerServer(tlsListener, containerChan, hook)
go http.Serve(tlsListener, server)
return server, nil
}
开发者ID:rawlingsj,项目名称:gofabric8,代码行数:26,代码来源:server.go
示例17: loadTLSConfig
// Load the TLS certificates/keys and, if verify is true, the CA.
func loadTLSConfig(ca, cert, key string, verify bool) (*tls.Config, error) {
c, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
return nil, fmt.Errorf("Couldn't load X509 key pair (%s, %s): %s. Key encrypted?",
cert, key, err)
}
config := &tls.Config{
Certificates: []tls.Certificate{c},
MinVersion: tls.VersionTLS10,
}
if verify {
certPool := x509.NewCertPool()
file, err := ioutil.ReadFile(ca)
if err != nil {
return nil, fmt.Errorf("Couldn't read CA certificate: %s", err)
}
certPool.AppendCertsFromPEM(file)
config.RootCAs = certPool
config.ClientAuth = tls.RequireAndVerifyClientCert
config.ClientCAs = certPool
} else {
// If --tlsverify is not supplied, disable CA validation.
config.InsecureSkipVerify = true
}
return config, nil
}
开发者ID:clinta,项目名称:swarm,代码行数:30,代码来源:manage.go
示例18: SetupTCP
func SetupTCP(useTls bool, address string) {
println("Setting Up TCP at:", address)
const connectedAndWaitingMax = 0
conChan := make(chan net.Conn, connectedAndWaitingMax)
halt := make(chan int)
var listener net.Listener
var err os.Error
if useTls {
certs := make([]tls.Certificate, 1)
c0, errx := tls.LoadX509KeyPair("cert/cert.pem", "cert/key.pem")
certs[0] = c0
fmt.Println(errx)
config := tls.Config{Certificates: certs, ServerName: "TestServer"}
listener, err = tls.Listen("tcp", ":6666", &config)
println("TLS")
} else {
listener, err = net.Listen("tcp", ":6666")
println("TCP")
}
if err != nil {
println(err)
}
go getConnections(listener, conChan, halt)
conChan2 := make(chan *LoggedIn, connectedAndWaitingMax)
go welcomTestLoop(conChan, conChan2)
go updateLoop(conChan2)
println("TCP Setup")
}
开发者ID:Craig-Macomber,项目名称:Go-MMO-Panda,代码行数:35,代码来源:control.go
示例19: startHttp
func startHttp() {
http.HandleFunc("/register", register)
http.HandleFunc("/unregister", unregister)
laddr := fmt.Sprintf(":%d", *port)
tlsConfig := tlsdefaults.Server()
_, _, err := keyman.StoredPKAndCert(PKFile, CertFile, "Lantern", "localhost")
if err != nil {
log.Fatalf("Unable to initialize private key and certificate: %v", err)
}
cert, err := tls.LoadX509KeyPair(CertFile, PKFile)
if err != nil {
log.Fatalf("Unable to load certificate and key from %s and %s: %s", CertFile, PKFile, err)
}
tlsConfig.Certificates = []tls.Certificate{cert}
log.Debugf("About to listen at %v", laddr)
l, err := tls.Listen("tcp", laddr, tlsConfig)
if err != nil {
log.Fatalf("Unable to listen for tls connections at %s: %s", laddr, err)
}
log.Debug("About to serve")
err = http.Serve(l, nil)
if err != nil {
log.Fatalf("Unable to serve: %s", err)
}
}
开发者ID:2722,项目名称:lantern,代码行数:28,代码来源:web.go
示例20: setupTls
func setupTls(cert, key, ca string, l net.Listener) (net.Listener, error) {
tlsCert, err := tls.LoadX509KeyPair(cert, key)
if err != nil {
return nil, fmt.Errorf("Couldn't load X509 key pair (%s, %s): %s. Key encrypted?",
cert, key, err)
}
tlsConfig := &tls.Config{
NextProtos: []string{"http/1.1"},
Certificates: []tls.Certificate{tlsCert},
// Avoid fallback on insecure SSL protocols
MinVersion: tls.VersionTLS10,
}
if ca != "" {
certPool := x509.NewCertPool()
file, err := ioutil.ReadFile(ca)
if err != nil {
return nil, fmt.Errorf("Couldn't read CA certificate: %s", err)
}
certPool.AppendCertsFromPEM(file)
tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
tlsConfig.ClientCAs = certPool
}
return tls.NewListener(l, tlsConfig), nil
}
开发者ID:pombredanne,项目名称:docker,代码行数:26,代码来源:server.go
注:本文中的crypto/tls.LoadX509KeyPair函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论