本文整理汇总了Golang中crypto/tls.X509KeyPair函数的典型用法代码示例。如果您正苦于以下问题:Golang X509KeyPair函数的具体用法?Golang X509KeyPair怎么用?Golang X509KeyPair使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了X509KeyPair函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: init
func init() {
// If running the tests takes a bizarrely long amount of time,
// this code may be the problem. See
// http://code.google.com/p/go/issues/detail?id=6626 .
// As this slowness doesn't seem to affect real crypto (just key loading,
// not key use),and the tests really need this, well... I guess
// we'll just pay. In the meantime, for testing, I've cut this down
// to 1024-bit keys, to reduce the wait time. Since these are
// public anyhow, why use lots of bits?
var wg sync.WaitGroup
wg.Add(4)
go func() {
signing1, _ = tls.X509KeyPair(signing1_cert, signing1_key)
wg.Done()
}()
go func() {
node1_1, _ = tls.X509KeyPair(node1_1_cert, node1_1_key)
wg.Done()
}()
go func() {
node2_1, _ = tls.X509KeyPair(node2_1_cert, node2_1_key)
wg.Done()
}()
go func() {
node3_1, _ = tls.X509KeyPair(node3_1_cert, node3_1_key)
wg.Done()
}()
wg.Wait()
}
开发者ID:edwardt,项目名称:reign,代码行数:31,代码来源:certs_test.go
示例2: Read
// Read will read a TLS cert and key from the given paths
func (k *KeyReadWriter) Read() ([]byte, []byte, error) {
k.mu.Lock()
defer k.mu.Unlock()
keyBlock, err := k.readKey()
if err != nil {
return nil, nil, err
}
if version, ok := keyBlock.Headers[versionHeader]; ok {
if versionInt, err := strconv.ParseUint(version, 10, 64); err == nil {
k.kekData.Version = versionInt
}
}
delete(keyBlock.Headers, versionHeader)
if k.headersObj != nil {
newHeaders, err := k.headersObj.UnmarshalHeaders(keyBlock.Headers, k.kekData)
if err != nil {
return nil, nil, errors.Wrap(err, "unable to read TLS key headers")
}
k.headersObj = newHeaders
}
keyBytes := pem.EncodeToMemory(keyBlock)
cert, err := ioutil.ReadFile(k.paths.Cert)
// The cert is written to a temporary file first, then the key, and then
// the cert gets renamed - so, if interrupted, it's possible to end up with
// a cert that only exists in the temporary location.
switch {
case err == nil:
_, err = tls.X509KeyPair(cert, keyBytes)
case os.IsNotExist(err): //continue to try temp location
break
default:
return nil, nil, err
}
// either the cert doesn't exist, or it doesn't match the key - try the temp file, if it exists
if err != nil {
var tempErr error
tmpPaths := k.genTempPaths()
cert, tempErr = ioutil.ReadFile(tmpPaths.Cert)
if tempErr != nil {
return nil, nil, err // return the original error
}
if _, tempErr := tls.X509KeyPair(cert, keyBytes); tempErr != nil {
os.RemoveAll(tmpPaths.Cert) // nope, it doesn't match either - remove and return the original error
return nil, nil, err
}
os.Rename(tmpPaths.Cert, k.paths.Cert) // try to move the temp cert back to the regular location
}
return cert, keyBytes, nil
}
开发者ID:harche,项目名称:docker,代码行数:56,代码来源:keyreadwriter.go
示例3: verifyCertificates
func verifyCertificates() error {
_, err := tls.X509KeyPair([]byte(CACert), []byte(CAKey))
if err != nil {
return fmt.Errorf("bad CA cert key pair: %v", err)
}
_, err = tls.X509KeyPair([]byte(ServerCert), []byte(ServerKey))
if err != nil {
return fmt.Errorf("bad server cert key pair: %v", err)
}
return cert.Verify([]byte(ServerCert), []byte(CACert), time.Now())
}
开发者ID:johnvilsack,项目名称:golang-stuff,代码行数:11,代码来源:cert.go
示例4: serverMethodSelected
func serverMethodSelected(method uint8, conn net.Conn) (net.Conn, error) {
switch method {
case MethodTLS:
var cert tls.Certificate
var err error
if len(CertFile) == 0 || len(KeyFile) == 0 {
cert, err = tls.X509KeyPair([]byte(rawCert), []byte(rawKey))
} else {
cert, err = tls.LoadX509KeyPair(CertFile, KeyFile)
}
if err != nil {
return nil, err
}
conn = tls.Server(conn, &tls.Config{Certificates: []tls.Certificate{cert}})
if err := svrTLSAuth(conn); err != nil {
return nil, err
}
case MethodAES128, MethodAES192, MethodAES256,
MethodDES, MethodBF, MethodCAST5, MethodRC4MD5, MethodRC4, MethodTable:
cipher, err := shadowsocks.NewCipher(Methods[method], Password)
if err != nil {
return nil, err
}
conn = shadowsocks.NewConn(conn, cipher)
case gosocks5.MethodNoAcceptable:
return nil, gosocks5.ErrBadMethod
}
return conn, nil
}
开发者ID:gitHubOffical,项目名称:gost,代码行数:32,代码来源:socks5.go
示例5: startHttpsServer
func startHttpsServer(t *testing.T) {
if httpsAddr != "" {
return
}
var err error
pk, err = keyman.GeneratePK(2048)
if err != nil {
t.Fatalf("Unable to generate key: %s", err)
}
// Generate self-signed certificate
cert, err = pk.TLSCertificateFor("tlsdialer", "localhost", time.Now().Add(1*time.Hour), true, nil)
if err != nil {
t.Fatalf("Unable to generate cert: %s", err)
}
keypair, err := tls.X509KeyPair(cert.PEMEncoded(), pk.PEMEncoded())
if err != nil {
t.Fatalf("Unable to generate x509 key pair: %s", err)
}
l, err := tls.Listen("tcp", "localhost:0", &tls.Config{
Certificates: []tls.Certificate{keypair},
})
if err != nil {
t.Fatalf("HTTP unable to listen: %v", err)
}
httpsAddr = l.Addr().String()
doStartServer(t, l)
}
开发者ID:shizhh,项目名称:lantern,代码行数:33,代码来源:conn_test.go
示例6: newServer
func newServer(s *state.State, lis *net.TCPListener, cfg ServerConfig) (_ *Server, err error) {
tlsCert, err := tls.X509KeyPair(cfg.Cert, cfg.Key)
if err != nil {
return nil, err
}
// TODO(rog) check that *srvRoot is a valid type for using
// as an RPC server.
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{tlsCert},
MinVersion: tls.VersionTLS10,
}
srv := &Server{
state: s,
statePool: state.NewStatePool(s),
lis: newChangeCertListener(lis, cfg.CertChanged, tlsConfig),
tag: cfg.Tag,
dataDir: cfg.DataDir,
logDir: cfg.LogDir,
limiter: utils.NewLimiter(loginRateLimit),
validator: cfg.Validator,
adminApiFactories: map[int]adminApiFactory{
3: newAdminApiV3,
},
}
srv.authCtxt, err = newAuthContext(s)
if err != nil {
return nil, errors.Trace(err)
}
go srv.run()
return srv, nil
}
开发者ID:AlexisBruemmer,项目名称:juju,代码行数:31,代码来源:apiserver.go
示例7: newServer
func newServer(s *state.State, lis *net.TCPListener, cfg ServerConfig) (_ *Server, err error) {
tlsCert, err := tls.X509KeyPair(cfg.Cert, cfg.Key)
if err != nil {
return nil, err
}
stPool := cfg.StatePool
if stPool == nil {
stPool = state.NewStatePool(s)
}
srv := &Server{
clock: cfg.Clock,
newObserver: cfg.NewObserver,
state: s,
statePool: stPool,
lis: newChangeCertListener(lis, cfg.CertChanged, tlsCert),
tag: cfg.Tag,
dataDir: cfg.DataDir,
logDir: cfg.LogDir,
limiter: utils.NewLimiter(loginRateLimit),
validator: cfg.Validator,
adminAPIFactories: map[int]adminAPIFactory{
3: newAdminAPIV3,
},
}
srv.authCtxt, err = newAuthContext(s)
if err != nil {
return nil, errors.Trace(err)
}
go srv.run()
return srv, nil
}
开发者ID:kat-co,项目名称:juju,代码行数:32,代码来源:apiserver.go
示例8: checkRouteCertificate
func checkRouteCertificate(r diagnosticReporter, route routes.Route) {
r.Debug("AGL0330", fmt.Sprintf("Checking certificate for route '%s'...", route.ObjectMeta.Name))
block, _ := pem.Decode([]byte(route.Spec.TLS.Certificate))
//verify hostname
if block != nil {
cert, err := x509.ParseCertificate(block.Bytes)
if err != nil {
r.Error("AGL0335", err, fmt.Sprintf("Unable to parse the certificate for route '%s': %s", route.ObjectMeta.Name, err))
return
}
r.Debug("AGL0340", fmt.Sprintf("Cert CommonName: '%s' Cert DNSNames: '%s'", cert.Subject.CommonName, cert.DNSNames))
if err := cert.VerifyHostname(route.Spec.Host); err != nil {
r.Error("AGL0345", err, fmt.Sprintf("Route '%[1]s' certficate does not include route host '%[2]s'"+routeCertMissingHostName, route.ObjectMeta.Name, route.Spec.Host))
}
} else {
r.Error("AGL0350", errors.New("Unable to decode the TLS Certificate"), "Unable to decode the TLS Certificate")
}
//verify key matches cert
r.Debug("AGL0355", fmt.Sprintf("Checking certificate matches key for route '%s'", route.ObjectMeta.Name))
_, err := tls.X509KeyPair([]byte(route.Spec.TLS.Certificate), []byte(route.Spec.TLS.Key))
if err != nil {
r.Error("AGL0365", err, fmt.Sprintf("Route '%s' key and certificate do not match: %s. The router will be unable to pass traffic using this route.", route.ObjectMeta.Name, err))
}
}
开发者ID:LalatenduMohanty,项目名称:origin,代码行数:25,代码来源:routes.go
示例9: TLSConfigFor
// TLSConfigFor returns a tls.Config that will provide the transport level security defined
// by the provided Config. Will return nil if no transport level security is requested.
func TLSConfigFor(c *Config) (*tls.Config, error) {
if !(c.HasCA() || c.HasCertAuth() || c.TLS.Insecure) {
return nil, nil
}
if c.HasCA() && c.TLS.Insecure {
return nil, fmt.Errorf("specifying a root certificates file with the insecure flag is not allowed")
}
if err := loadTLSFiles(c); err != nil {
return nil, err
}
tlsConfig := &tls.Config{
// Change default from SSLv3 to TLSv1.0 (because of POODLE vulnerability)
MinVersion: tls.VersionTLS10,
InsecureSkipVerify: c.TLS.Insecure,
}
if c.HasCA() {
tlsConfig.RootCAs = rootCertPool(c.TLS.CAData)
}
if c.HasCertAuth() {
cert, err := tls.X509KeyPair(c.TLS.CertData, c.TLS.KeyData)
if err != nil {
return nil, err
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
return tlsConfig, nil
}
开发者ID:CNDonny,项目名称:scope,代码行数:33,代码来源:transport.go
示例10: GetTLSConfigMem
func GetTLSConfigMem(tlsClientCert string, tlsClientKey string, tlsRemoteCertPEM string) (*tls.Config, error) {
tlsConfig := initTLSConfig()
// Client authentication
if tlsClientCert != "" && tlsClientKey != "" {
cert, err := tls.X509KeyPair([]byte(tlsClientCert), []byte(tlsClientKey))
if err != nil {
return nil, err
}
tlsConfig.Certificates = []tls.Certificate{cert}
}
var tlsRemoteCert *x509.Certificate
if tlsRemoteCertPEM != "" {
// Ignore any content outside of the PEM bytes we care about
certBlock, _ := pem.Decode([]byte(tlsRemoteCertPEM))
var err error
tlsRemoteCert, err = x509.ParseCertificate(certBlock.Bytes)
if err != nil {
return nil, err
}
}
finalizeTLSConfig(tlsConfig, tlsRemoteCert)
return tlsConfig, nil
}
开发者ID:jameinel,项目名称:lxd,代码行数:27,代码来源:network.go
示例11: TestTLSTimeout
func TestTLSTimeout(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Fatalf("Listen failed: %v", err)
}
defer ln.Close()
cert, err := tls.X509KeyPair(localhostCert, localhostKey)
if err != nil {
t.Fatalf("Cert load failed: %v", err)
}
server := &smtpd.Server{
TLSConfig: &tls.Config{
Certificates: []tls.Certificate{cert},
},
ReadTimeout: time.Second * 2,
WriteTimeout: time.Second * 2,
}
go func() {
server.Serve(ln)
}()
c, err := smtp.Dial(ln.Addr().String())
if err != nil {
t.Fatalf("Dial failed: %v", err)
}
if err := c.StartTLS(&tls.Config{InsecureSkipVerify: true}); err != nil {
t.Fatalf("STARTTLS failed: %v", err)
}
time.Sleep(time.Second)
if err := c.Mail("[email protected]"); err != nil {
t.Fatalf("MAIL failed: %v", err)
}
time.Sleep(time.Second)
if err := c.Rcpt("[email protected]"); err != nil {
t.Fatalf("RCPT failed: %v", err)
}
time.Sleep(time.Second)
if err := c.Rcpt("[email protected]"); err != nil {
t.Fatalf("RCPT failed: %v", err)
}
time.Sleep(time.Second)
if err := c.Quit(); err != nil {
t.Fatalf("Quit failed: %v", err)
}
}
开发者ID:dieucao,项目名称:notifications,代码行数:60,代码来源:smtpd_test.go
示例12: TestTLSDial
func TestTLSDial(t *testing.T) {
if testing.Short() {
t.Skip("skipping syslog test during -short")
}
certificate, err := tls.X509KeyPair([]byte(cert), []byte(key))
caCert := x509.NewCertPool()
ok := caCert.AppendCertsFromPEM([]byte(caPem))
if !ok {
t.Fatalf("failed to parse root certificate")
}
srvCfg := &tls.Config{InsecureSkipVerify: true, Certificates: []tls.Certificate{certificate}, RootCAs: caCert}
clientCfg := &tls.Config{ClientCAs: caCert, InsecureSkipVerify: true}
done := make(chan string)
addr, sock, srvWG := startServer("tcp", "", done, srvCfg)
defer srvWG.Wait()
defer sock.Close()
f, err := Dial("tcp", addr, (LOG_LOCAL7|LOG_DEBUG)+1, "syslog_test", clientCfg)
if f != nil {
t.Fatalf("Should have trapped bad priority")
}
f, err = Dial("tcp", addr, -1, "syslog_test", clientCfg)
if f != nil {
t.Fatalf("Should have trapped bad priority")
}
l, err := Dial("tcp", addr, LOG_USER|LOG_ERR, "syslog_test", clientCfg)
if err != nil {
t.Fatalf("Dial() failed: %s", err)
}
l.Close()
}
开发者ID:juju,项目名称:syslog,代码行数:32,代码来源:syslog_common_test.go
示例13: createTLSClient
func createTLSClient(socket net.Conn, config *APNSConfig) (net.Conn, error) {
x509Cert, err := tls.X509KeyPair(config.CertificateBytes, config.KeyBytes)
if err != nil {
//failed to validate key pair
return nil, err
}
tlsConf := &tls.Config{
Certificates: []tls.Certificate{x509Cert},
ServerName: config.GatewayHost,
InsecureSkipVerify: config.UseInsecureSkipVerify,
}
tlsSocket := tls.Client(socket, tlsConf)
tlsSocket.SetDeadline(time.Now().Add(time.Duration(config.TlsTimeout) * time.Second))
err = tlsSocket.Handshake()
if err != nil {
//failed to handshake with tls information
return nil, err
}
//hooray! we're connected
//reset the deadline so it doesn't fail subsequent writes
tlsSocket.SetDeadline(time.Time{})
return tlsSocket, nil
}
开发者ID:soundcloud,项目名称:go-libapns,代码行数:27,代码来源:connection.go
示例14: Certificate
func (t *RawCertificate) Certificate() (*tls.Certificate, error) {
if t.IsNil() {
return nil, errors.New("nil certificate")
}
cert, err := tls.X509KeyPair(t.Cert, t.Key)
return &cert, err
}
开发者ID:kjplatz,项目名称:vic,代码行数:7,代码来源:virtual_container_host.go
示例15: newServerTLSConfig
// newServerTLSConfig creates a server TLSConfig from the supplied byte strings containing
// - the certificate of this node (should be signed by the CA),
// - the private key of this node.
// - the certificate of the cluster CA,
func newServerTLSConfig(certPEM, keyPEM, caPEM []byte) (*tls.Config, error) {
cert, err := tls.X509KeyPair(certPEM, keyPEM)
if err != nil {
return nil, err
}
certPool := x509.NewCertPool()
if ok := certPool.AppendCertsFromPEM(caPEM); !ok {
err = util.Error("failed to parse PEM data to pool")
return nil, err
}
return &tls.Config{
Certificates: []tls.Certificate{cert},
// Verify client certs if passed.
ClientAuth: tls.VerifyClientCertIfGiven,
RootCAs: certPool,
ClientCAs: certPool,
// Use the default cipher suite from golang (RC4 is going away in 1.5).
// Prefer the server-specified suite.
PreferServerCipherSuites: true,
// TLS 1.1 and 1.2 support is crappy out there. Let's use 1.0.
MinVersion: tls.VersionTLS10,
// Should we disable session resumption? This may break forward secrecy.
// SessionTicketsDisabled: true,
}, nil
}
开发者ID:Gardenya,项目名称:cockroach,代码行数:35,代码来源:tls.go
示例16: newServer
func newServer(s *state.State, lis *net.TCPListener, cfg ServerConfig) (_ *Server, err error) {
logger.Infof("listening on %q", lis.Addr())
srv := &Server{
state: s,
statePool: state.NewStatePool(s),
addr: lis.Addr().(*net.TCPAddr), // cannot fail
tag: cfg.Tag,
dataDir: cfg.DataDir,
logDir: cfg.LogDir,
limiter: utils.NewLimiter(loginRateLimit),
validator: cfg.Validator,
adminApiFactories: map[int]adminApiFactory{
0: newAdminApiV0,
1: newAdminApiV1,
2: newAdminApiV2,
},
}
srv.authCtxt = newAuthContext(srv)
tlsCert, err := tls.X509KeyPair(cfg.Cert, cfg.Key)
if err != nil {
return nil, err
}
// TODO(rog) check that *srvRoot is a valid type for using
// as an RPC server.
tlsConfig := tls.Config{
Certificates: []tls.Certificate{tlsCert},
}
changeCertListener := newChangeCertListener(lis, cfg.CertChanged, tlsConfig)
go srv.run(changeCertListener)
return srv, nil
}
开发者ID:snailwalker,项目名称:juju,代码行数:31,代码来源:apiserver.go
示例17: listenForCoordinator
func listenForCoordinator() {
tlsCert, tlsKey := metadataValue("tls-cert"), metadataValue("tls-key")
if (tlsCert == "") != (tlsKey == "") {
log.Fatalf("tls-cert and tls-key must both be supplied, or neither.")
}
log.Printf("Listening on %s ...", *listenAddr)
ln, err := net.Listen("tcp", *listenAddr)
if err != nil {
log.Fatalf("Failed to listen on %s: %v", *listenAddr, err)
}
ln = tcpKeepAliveListener{ln.(*net.TCPListener)}
var srv http.Server
if tlsCert != "" {
cert, err := tls.X509KeyPair([]byte(tlsCert), []byte(tlsKey))
if err != nil {
log.Fatalf("TLS cert error: %v", err)
}
tlsConf := &tls.Config{
Certificates: []tls.Certificate{cert},
}
ln = tls.NewListener(ln, tlsConf)
}
log.Fatalf("Serve: %v", srv.Serve(ln))
}
开发者ID:way-2-go,项目名称:build,代码行数:27,代码来源:buildlet.go
示例18: Init
func Init(listenAddr string, supervisorPort uint16, cpuIncr, memIncr uint, resDuration time.Duration) error {
var err error
err = LoadEnvs()
if err != nil {
return err
}
CPUSharesIncrement = cpuIncr
MemoryLimitIncrement = memIncr
atlantis.Tracker.ResultDuration = resDuration
// init rpc stuff here
lAddr = listenAddr
lPort = strings.Split(lAddr, ":")[1]
supervisor.Init(fmt.Sprintf("%d", supervisorPort))
manager.Init(lPort)
manager := new(ManagerRPC)
server = rpc.NewServer()
server.Register(manager)
config := &tls.Config{}
config.InsecureSkipVerify = true
config.Certificates = make([]tls.Certificate, 1)
config.Certificates[0], err = tls.X509KeyPair(crypto.SERVER_CERT, crypto.SERVER_KEY)
l, err = tls.Listen("tcp", lAddr, config)
return err
}
开发者ID:irregular,项目名称:atlantis-manager,代码行数:25,代码来源:rpc.go
示例19: getTLSConfig
func getTLSConfig(clientCertPEMData, clientKeyPEMData []byte) (*tls.Config, error) {
certPool := x509.NewCertPool()
certChainPath := os.Getenv("ORCHARD_HOST_CA")
if certChainPath != "" {
certChainData, err := ioutil.ReadFile(certChainPath)
if err != nil {
return nil, err
}
certPool.AppendCertsFromPEM(certChainData)
} else {
certPool.AppendCertsFromPEM([]byte(orchardCerts))
}
clientCert, err := tls.X509KeyPair(clientCertPEMData, clientKeyPEMData)
if err != nil {
return nil, err
}
config := new(tls.Config)
config.RootCAs = certPool
config.Certificates = []tls.Certificate{clientCert}
config.BuildNameToCertificate()
return config, nil
}
开发者ID:BillTheBest,项目名称:libswarm,代码行数:26,代码来源:orchard.go
示例20: wsListener
// If http.ListenandServe return an error,
// it will throws a panic.
func wsListener() {
if err := func() error {
httpServeMux := http.NewServeMux()
httpServeMux.Handle("/pub", websocket.Handler(WsHandle))
var (
l net.Listener
err error
)
if Conf.Tls {
tlsConf := new(tls.Config)
tlsConf.Certificates = make([]tls.Certificate, 1)
tlsConf.Certificates[0], err = tls.X509KeyPair(Conf.Cert, Conf.Key)
if err != nil {
return err
}
l, err = tls.Listen("tcp", Conf.WebSocket_addr, tlsConf)
if err != nil {
return err
}
return http.Serve(l, httpServeMux)
} else {
return http.ListenAndServe(Conf.WebSocket_addr, httpServeMux)
}
}(); err != nil {
panic(err)
}
}
开发者ID:henrydh,项目名称:quick-know,代码行数:29,代码来源:ws.go
注:本文中的crypto/tls.X509KeyPair函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论