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
+12.4k Golang : Pass database connection to function called from another package and HTTP Handler
+7.1k Golang : alternative to os.Exit() function
+5.7k Golang : Shuffle array of list
+10.5k Android Studio : Checkbox for user to select options example
+51.1k Golang : Check if item is in slice/array
+15k Golang : How to get Unix file descriptor for console and file
+9.9k Golang : Use regular expression to get all upper case or lower case characters example
+10k Golang : Embed secret text string into binary(executable) file
+8.6k Golang : Random integer with rand.Seed() within a given range
+25.5k Golang : How to read integer value from standard input ?
+9.5k Golang : Sort and reverse sort a slice of floats
+13.4k Generate salted password with OpenSSL example