本文整理汇总了Golang中crypto/tls.X509KeyPair函数的典型用法代码示例。如果您正苦于以下问题:Golang X509KeyPair函数的具体用法?Golang X509KeyPair怎么用?Golang X509KeyPair使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了X509KeyPair函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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()
}
示例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
}
示例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())
}
示例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
}
示例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)
}
示例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
}
示例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
}
示例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))
}
}
示例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
}
示例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
}
示例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)
}
}
示例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()
}
示例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
}
示例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
}
示例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
}