Golang : Secure(TLS) connection between server and client
This is additional tutorial for the previous tutorial on creating simple client-server program with Golang. In this tutorial, we will learn how to established secure(TLS - Transport Layer Security) connection between a server and client.
Before executing the code below, please generate 2 sets of certificates - one set for server and one set for client.
To keep this tutorial simple, we will use these commands :
>openssl req -new -nodes -x509 -out server.pem -keyout server.key -days 365
>openssl req -new -nodes -x509 -out client.pem -keyout client.key -days 365
just leave everything to the default value by pressing enter until the end.
Execute the server.go program below as a background process. Modify the port number or IP address to fit your own requirement.
server.go
package main
import (
"crypto/rand"
"crypto/tls"
"fmt"
"log"
"net"
)
func handleConnection(c net.Conn) {
log.Printf("Client(TLS) %v connected via secure channel.", c.RemoteAddr())
// stuff to do... like read data from client, process it, write back to client
// see what you can do with (c net.Conn) at
// http://golang.org/pkg/net/#Conn
// buffer := make([]byte, 4096)
//for {
// n, err := c.Read(buffer)
// if err != nil || n == 0 {
// c.Close()
// break
// }
// n, err = c.Write(buffer[0:n])
// if err != nil {
// c.Close()
// break
// }
// }
log.Printf("Connection from %v closed.", c.RemoteAddr())
}
func main() {
cert, err := tls.LoadX509KeyPair("server.pem", "server.key")
if err != nil {
log.Fatal(err)
}
config := tls.Config{Certificates: []tls.Certificate{cert}, ClientAuth: tls.RequireAnyClientCert
}
config.Rand = rand.Reader
ln, err := tls.Listen("tcp", ":6600", &config)
if err != nil {
log.Fatal(err)
}
fmt.Println("Server(TLS) up and listening on port 6600")
for {
conn, err := ln.Accept()
if err != nil {
log.Println(err)
continue
}
go handleConnection(conn)
}
}
and on a separate machine. Run the client.go program
client.go
package main
import (
"crypto/tls"
"log"
)
func main() {
cert, err := tls.LoadX509KeyPair("client.pem", "client.key")
if err != nil {
log.Fatal(err)
}
hostName := "example.com" // change this
portNum := "6600"
log.Printf("Connecting to %s\n", hostName)
config := tls.Config{Certificates: []tls.Certificate{cert}, InsecureSkipVerify: true}
conn, err := tls.Dial("tcp", hostName+":"+portNum, &config)
if err != nil {
log.Fatal(err)
}
defer conn.Close()
log.Printf("Connection established between %s and localhost.\n", conn.RemoteAddr().String())
log.Println("Bye...")
}
Sample output :
./client-dial-tls
2015/05/09 22:04:58 Connecting to socketloop.com
./server
Server(TLS) up and listening on port 6600
2015/05/09 10:04:59 Client(TLS) 14.192.213.197:2547 connected via secure channel.
2015/05/09 10:04:59 Connection from 14.192.213.197:2547 closed.
One of the few things that you might want to add to this tutorial is to send data from client to server and get the server to echo back to the client. I leave this to you as exercise ;-)
References :
http://en.wikipedia.org/wiki/TransportLayerSecurity
https://www.socketloop.com/tutorials/golang-simple-client-server-example
See also : Golang : Simple client server example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+7.9k Golang : HTTP Server Example
+7.9k Golang : Auto-generate reply email with text/template package
+14.2k Golang : Reset buffer example
+17.5k Golang : Login and logout a user after password verification and redirect example
+7.9k Golang : Get final or effective URL with Request.URL example
+45.6k Golang : Read tab delimited file with encoding/csv package
+18.2k Golang : Example for RSA package functions
+18.9k Mac OSX : Homebrew and Golang
+27.8k Golang : Connect to database (MySQL/MariaDB) server
+21.3k SSL : How to check if current certificate is sha1 or sha2
+12.4k Golang : Pass database connection to function called from another package and HTTP Handler