Created
August 16, 2016 15:47
-
-
Save ericchiang/5f7cdede680ffd1771b6cc895a21f168 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package tls | |
import ( | |
"crypto/tls" | |
"crypto/x509" | |
"io/ioutil" | |
"net" | |
"testing" | |
) | |
func TestCert(t *testing.T) { | |
cert, err := tls.LoadX509KeyPair("cert.pem", "key.pem") | |
if err != nil { | |
t.Fatalf("failed to load certificate: %v", err) | |
} | |
listenConfig := &tls.Config{Certificates: []tls.Certificate{cert}} | |
listener, err := tls.Listen("tcp", "127.0.0.1:0", listenConfig) | |
if err != nil { | |
t.Fatalf("failed to listen: %v", err) | |
} | |
go func() { | |
for { | |
conn, err := listener.Accept() | |
if err != nil { | |
return | |
} | |
conn.Write([]byte("hello world")) | |
conn.Close() | |
} | |
}() | |
defer listener.Close() | |
_, listenerPort, err := net.SplitHostPort(listener.Addr().String()) | |
if err != nil { | |
t.Fatalf("failed to find which port listener is on: %v", err) | |
} | |
data, err := ioutil.ReadFile("cert.pem") | |
if err != nil { | |
t.Fatal(err) | |
} | |
pool := x509.NewCertPool() | |
if !pool.AppendCertsFromPEM(data) { | |
t.Fatal("no certificates found in cert.pem") | |
} | |
dialConfig := &tls.Config{RootCAs: pool} | |
conn, err := tls.Dial("tcp", "kcdev.tremolosecurity.com:"+listenerPort, dialConfig) | |
if err != nil { | |
t.Fatalf("dial failed: %v", err) | |
} | |
conn.Close() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment