Simple Golang HTTPS/TLS Examples

Generate private key (.key)
# Key considerations for algorithm "RSA" ≥ 2048-bit
openssl genrsa -out server.key 2048

# Key considerations for algorithm "ECDSA" (X25519 || ≥ secp384r1)
# https://safecurves.cr.yp.to/
# List ECDSA the supported curves (openssl ecparam -list_curves)
openssl ecparam -genkey -name secp384r1 -out server.key
Generation of self-signed(x509) public key (PEM-encodings .pem|.crt) based on the private (.key)
openssl req -new -x509 -sha256 -key server.key -out server.crt -days 3650

Simple Golang HTTPS/TLS Server

package main

import (
    // "fmt"
    // "io"
    "net/http"
    "log"
)

func HelloServer(w http.ResponseWriter, req *http.Request) {
    w.Header().Set("Content-Type", "text/plain")
    w.Write([]byte("This is an example server.\n"))
    // fmt.Fprintf(w, "This is an example server.\n")
    // io.WriteString(w, "This is an example server.\n")
}

func main() {
    http.HandleFunc("/hello", HelloServer)
    err := http.ListenAndServeTLS(":443", "server.crt", "server.key", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

Hint: visit, please do not forget to use https begins, otherwise chrome will download a file as follows:

$ curl -sL https://localhost:443 | xxd
0000000: 1503 0100 0202 0a                        .......

TLS (transport layer security) — Server

package main

import (
    "log"
    "crypto/tls"
    "net"
    "bufio"
)

func main() {
    log.SetFlags(log.Lshortfile)

    cer, err := tls.LoadX509KeyPair("server.crt", "server.key")
    if err != nil {
        log.Println(err)
        return
    }

    config := &tls.Config{Certificates: []tls.Certificate{cer}}
    ln, err := tls.Listen("tcp", ":443", config) 
    if err != nil {
        log.Println(err)
        return
    }
    defer ln.Close()

    for {
        conn, err := ln.Accept()
        if err != nil {
            log.Println(err)
            continue
        }
        go handleConnection(conn)
    }
}

func handleConnection(conn net.Conn) {
    defer conn.Close()
    r := bufio.NewReader(conn)
    for {
        msg, err := r.ReadString('\n')
        if err != nil {
            log.Println(err)
            return
        }

        println(msg)

        n, err := conn.Write([]byte("world\n"))
        if err != nil {
            log.Println(n, err)
            return
        }
    }
}

TLS (transport layer security) — Client

package main

import (
    "log"
    "crypto/tls"
)

func main() {
    log.SetFlags(log.Lshortfile)

    conf := &tls.Config{
         //InsecureSkipVerify: true,
    }

    conn, err := tls.Dial("tcp", "127.0.0.1:443", conf)
    if err != nil {
        log.Println(err)
        return
    }
    defer conn.Close()

    n, err := conn.Write([]byte("hello\n"))
    if err != nil {
        log.Println(n, err)
        return
    }

    buf := make([]byte, 100)
    n, err = conn.Read(buf)
    if err != nil {
        log.Println(n, err)
        return
    }

    println(string(buf[:n]))
}
Perfect SSL Labs Score with Go
package main

import (
    "crypto/tls"
    "log"
    "net/http"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
        w.Header().Add("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
        w.Write([]byte("This is an example server.\n"))
    })
    cfg := &tls.Config{
        MinVersion:               tls.VersionTLS12,
        CurvePreferences:         []tls.CurveID{tls.CurveP521, tls.CurveP384, tls.CurveP256},
        PreferServerCipherSuites: true,
        CipherSuites: []uint16{
            tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
            tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA,
            tls.TLS_RSA_WITH_AES_256_GCM_SHA384,
            tls.TLS_RSA_WITH_AES_256_CBC_SHA,
        },
    }
    srv := &http.Server{
        Addr:         ":443",
        Handler:      mux,
        TLSConfig:    cfg,
        TLSNextProto: make(map[string]func(*http.Server, *tls.Conn, http.Handler), 0),
    }
    log.Fatal(srv.ListenAndServeTLS("tls.crt", "tls.key"))
}

Generation of self-sign a certificate with a private (.key) and public key (PEM-encodings .pem|.crt) in one command:

# ECDSA recommendation key ≥ secp384r1
# List ECDSA the supported curves (openssl ecparam -list_curves)
openssl req -x509 -nodes -newkey ec:secp384r1 -keyout server.ecdsa.key -out server.ecdsa.crt -days 3650
# openssl req -x509 -nodes -newkey ec:<(openssl ecparam -name secp384r1) -keyout server.ecdsa.key -out server.ecdsa.crt -days 3650
# -pkeyopt ec_paramgen_curve:… / ec:<(openssl ecparam -name …) / -newkey ec:…
ln -sf server.ecdsa.key server.key
ln -sf server.ecdsa.crt server.crt

# RSA recommendation key ≥ 2048-bit
openssl req -x509 -nodes -newkey rsa:2048 -keyout server.rsa.key -out server.rsa.crt -days 3650
ln -sf server.rsa.key server.key
ln -sf server.rsa.crt server.crt
  • .crt — Alternate synonymous most common among *nix systems .pem (pubkey).
  • .csr — Certficate Signing Requests (synonymous most common among *nix systems).
  • .cer — Microsoft alternate form of .crt, you can use MS to convert .crt to .cer (DER encoded .cer, or base64[PEM] encoded .cer).
  • .pem = The PEM extension is used for different types of X.509v3 files which contain ASCII (Base64) armored data prefixed with a «—– BEGIN …» line. These files may also bear the cer or the crt extension.
  • .der — The DER extension is used for binary DER encoded certificates.

Generating the Certficate Signing Request

openssl req -new -sha256 -key server.key -out server.csr
openssl x509 -req -sha256 -in server.csr -signkey server.key -out server.crt -days 3650

ECDSA & RSA — FAQ

  • Validate the elliptic curve parameters -check
  • List "ECDSA" the supported curves openssl ecparam -list_curves
  • Encoding to explicit "ECDSA" -param_enc explicit
  • Conversion form to compressed "ECDSA" -conv_form compressed
  • "EC" parameters and a private key -genkey

CA Bundle Path

Distro Package Path to CA
Fedora, RHEL, CentOS ca-certificates /etc/pki/tls/certs/ca-bundle.crt
Debian, Ubuntu, Gentoo, Arch Linux ca-certificates /etc/ssl/certs/ca-certificates.crt
SUSE, openSUSE ca-certificates /etc/ssl/ca-bundle.pem
FreeBSD ca_root_nss /usr/local/share/certs/ca-root-nss.crt
Cygwin - /usr/ssl/certs/ca-bundle.crt
macOS (MacPorts) curl-ca-bundle /opt/local/share/curl/curl-ca-bundle.crt
Default cURL CA bunde path (without --with-ca-bundle option) /usr/local/share/curl/curl-ca-bundle.crt
Really old RedHat? /usr/share/ssl/certs/ca-bundle.crt

Reference Link

Similar Resources

Simple-go-api - This porject deploys a simple go app inside a EKS Cluster

SimpleGoApp This porject deploys a simple go app inside a EKS Cluster Prerequisi

Jan 19, 2022

A simple Kubernetes Operator template that uses Golang, use it to build your own operators

A simple Kubernetes Operator template that uses Golang, use it to build your own operators

A simple programmatic Kubernetes Operator template. Use this to create your own Kubernetes operators with golang. Build with KIND (Kubernetes in Docke

May 13, 2022

Simple golang script for getting VK message statistics

vk-message-counter Simple golang script for getting VK message statistics Example package main import ( "fmt" "github.com/joho/godotenv" counter "

Apr 6, 2022

A deadly simple state machine for Golang

go-litefsm A deadly simple state machine for Golang, within 100 LOC. Example // Create accepted transitions transitions := NewTransitions() transition

Jul 13, 2022

Imaginarium - A simple golang image storage engine

Imaginarium A simple golang image storage engine. Used to create and store diffe

Jan 10, 2022

A Simple Orchestrator Service implemented using gRPC in Golang

Orchestrator Service The goal of this program is to build an orchestrator service that would read any request it receives and forwards it to other orc

Apr 5, 2022

A Simple to use golang masking tool to mask sensitive information from go-lang data-structures

Golang Masking Tool Golang Masking Tool is a simple utility of creating a masker tool which you can use to mask sensitive information. You can use a v

Dec 1, 2022

Using the Golang search the Marvel Characters. This project is a web based golang application that shows the information of superheroes using Marvel api.

Using the Golang search the Marvel Characters. This project is a web based golang application that shows the information of superheroes using Marvel api.

marvel-universe-web using the Golang search the Marvel Universe Characters About The Project This project is a web based golang application that shows

Oct 10, 2021

Golang-tutorials - This repository contains golang tutorials right from basic to advanced.

Golang-tutorials This repository contains golang tutorials right from basic to advanced. Go is a statically typed, compiled programming language desig

Jan 3, 2022
Comments
  • http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher

    http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher

    the tls config recommended for ssllab need some updates, i guess, otherwise the go server wont start with this error couldn't serve: http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher.

    see also https://github.com/golang/go/issues/34776

  • Doubt

    Doubt

    Greetings!

    Sorry, but which version of TLS is this? 1.1, 1.2?

    package main
    
    import (
        "log"
        "crypto/tls"
    )
    
    func main() {
        log.SetFlags(log.Lshortfile)
    
        conf := &tls.Config{
             //InsecureSkipVerify: true,
        }
    
        conn, err := tls.Dial("tcp", "127.0.0.1:443", conf)
        if err != nil {
            log.Println(err)
            return
        }
        defer conn.Close()
    
        n, err := conn.Write([]byte("hello\n"))
        if err != nil {
            log.Println(n, err)
            return
        }
    
        buf := make([]byte, 100)
        n, err = conn.Read(buf)
        if err != nil {
            log.Println(n, err)
            return
        }
    
        println(string(buf[:n]))
    }
    

    Thanks in advance!

  • Help (Whish list) with ed25519

    Help (Whish list) with ed25519

    Hi! In the tls server and client examples, what I need to do or change to use ed25519 on them?

    I m using go1.13, amd64 xubuntu 19.10 Linux

    Very Thanks for the examples and Patience ! []'s Dani.

Discover expired TLS certificates in the services of a kubernetes cluster

About verify-k8s-certs is a daemon (prometheus exporter) to discover expired TLS certificates in a kubernetes cluster. It exposes the informations as

Feb 1, 2022
Watch and react to changes in Kubernetes TLS Secrets

cert-watch Watch and react to change in Kubernetes TLS Secrets. What is cert-watch? Kubernetes has introduced a number of different ways to keep certi

Feb 4, 2022
fiber-air-docker development environment boilerplate, examples
fiber-air-docker development environment boilerplate, examples

ON AIR! fiber-air-docker development environment boilerplate TODO on air 세션 준비 fiber 유저 준비 gorm 외래키 준비 아키텍쳐 참고 https://blog.puppyloper.com/menus/Golan

Sep 14, 2022
Go serverless functions examples with most popular Cloud Providers

go-serverless Go serverless functions examples with most popular Cloud Providers Creating zip archive go mod download go build ./cmd/<aws|gcp> zip -

Nov 16, 2021
A cross platform CLI for Flyte. Written in Golang. Offers an intuitive interface to Flyte https://flytectl.readthedocs.io/en/latest/
A cross platform CLI for Flyte. Written in Golang. Offers an intuitive interface to Flyte https://flytectl.readthedocs.io/en/latest/

FlyteCTL Flyte's official command-line interface Documentation · Contribution Guide FlyteCTL was designed as a portable and lightweight command-line i

Nov 7, 2022
Prevent Kubernetes misconfigurations from ever making it (again 😤) to production! The CLI integration provides policy enforcement solution to run automatic checks for rule violations. Docs: https://hub.datree.io
Prevent Kubernetes misconfigurations from ever making it  (again 😤) to production! The CLI integration provides policy enforcement solution to run automatic checks for rule violations.  Docs: https://hub.datree.io

What is Datree? Datree helps to prevent Kubernetes misconfigurations from ever making it to production. The CLI integration can be used locally or in

Jan 1, 2023
The server-side reproduction, similar the one of https://popcat.click, improve the performance and speed.

PopCat Echo The server-side reproduction, similar the one of https://popcat.click, improve the performance and speed. Docker Image The docker image is

Dec 15, 2022
Deploy https certificates non-interactively to CDN services

certdeploy Deploy https certificates non-interactively to CDN services. Environment Variables CERT_PATH - Certificate file path, should contain certif

Nov 27, 2022
Poc rsa - A simple golang scaffolding to help me to create new api projects or workers with golang on k8s

go-scaffold A simple golang scaffolding to help me to create new api projects or

Feb 3, 2022
A simple project (which is visitor counter) on kubernetesA simple project (which is visitor counter) on kubernetes

k8s playground This project aims to deploy a simple project (which is visitor counter) on kubernetes. Deploy steps kubectl apply -f secret.yaml kubect

Dec 16, 2022