1 // Copyright 2009 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.
5 // This package partially implements the TLS 1.1 protocol, as specified in RFC 4346.
18 func Server(conn net
.Conn
, config
*Config
) *Conn
{
19 return &Conn
{conn
: conn
, config
: config
}
22 func Client(conn net
.Conn
, config
*Config
) *Conn
{
23 return &Conn
{conn
: conn
, config
: config
, isClient
: true}
26 type Listener
struct {
31 func (l
*Listener
) Accept() (c net
.Conn
, err os
.Error
) {
32 c
, err
= l
.listener
.Accept()
36 c
= Server(c
, l
.config
)
40 func (l
*Listener
) Close() os
.Error
{ return l
.listener
.Close() }
42 func (l
*Listener
) Addr() net
.Addr
{ return l
.listener
.Addr() }
44 // NewListener creates a Listener which accepts connections from an inner
45 // Listener and wraps each connection with Server.
46 // The configuration config must be non-nil and must have
47 // at least one certificate.
48 func NewListener(listener net
.Listener
, config
*Config
) (l
*Listener
) {
55 func Listen(network
, laddr
string, config
*Config
) (net
.Listener
, os
.Error
) {
56 if config
== nil ||
len(config
.Certificates
) == 0 {
57 return nil, os
.NewError("tls.Listen: no certificates in configuration")
59 l
, err
:= net
.Listen(network
, laddr
)
63 return NewListener(l
, config
), nil
66 func Dial(network
, laddr
, raddr
string) (net
.Conn
, os
.Error
) {
67 c
, err
:= net
.Dial(network
, laddr
, raddr
)
72 colonPos
:= strings
.LastIndex(raddr
, ":")
76 hostname
:= raddr
[:colonPos
]
78 config
:= defaultConfig()
79 config
.ServerName
= hostname
80 conn
:= Client(c
, config
)
81 err
= conn
.Handshake()
89 // LoadX509KeyPair reads and parses a public/private key pair from a pair of
90 // files. The files must contain PEM encoded data.
91 func LoadX509KeyPair(certFile
string, keyFile
string) (cert Certificate
, err os
.Error
) {
92 certPEMBlock
, err
:= ioutil
.ReadFile(certFile
)
97 certDERBlock
, _
:= pem
.Decode(certPEMBlock
)
98 if certDERBlock
== nil {
99 err
= os
.ErrorString("crypto/tls: failed to parse certificate PEM data")
103 cert
.Certificate
= [][]byte{certDERBlock
.Bytes
}
105 keyPEMBlock
, err
:= ioutil
.ReadFile(keyFile
)
110 keyDERBlock
, _
:= pem
.Decode(keyPEMBlock
)
111 if keyDERBlock
== nil {
112 err
= os
.ErrorString("crypto/tls: failed to parse key PEM data")
116 key
, err
:= x509
.ParsePKCS1PrivateKey(keyDERBlock
.Bytes
)
118 err
= os
.ErrorString("crypto/tls: failed to parse key")
122 cert
.PrivateKey
= key
124 // We don't need to parse the public key for TLS, but we so do anyway
125 // to check that it looks sane and matches the private key.
126 x509Cert
, err
:= x509
.ParseCertificate(certDERBlock
.Bytes
)
131 if x509Cert
.PublicKeyAlgorithm
!= x509
.RSA || x509Cert
.PublicKey
.(*rsa
.PublicKey
).N
.Cmp(key
.PublicKey
.N
) != 0 {
132 err
= os
.ErrorString("crypto/tls: private key does not match public key")