Skip to content

Instantly share code, notes, and snippets.

@bwesterb
Last active July 22, 2020 12:19
Show Gist options
  • Save bwesterb/621ac21e5f65ff9587ad6b00a2c41a99 to your computer and use it in GitHub Desktop.
Save bwesterb/621ac21e5f65ff9587ad6b00a2c41a99 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"circl/sign"
"crypto/rand"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io/ioutil"
"log"
"math/big"
"net"
"net/http"
"time"
)
func main() {
scheme := sign.EdDilithium3
caPk, caSk, _ := scheme.GenerateKey()
pk, sk, _ := scheme.GenerateKey()
caTemplate := x509.Certificate{
SerialNumber: big.NewInt(2019),
Subject: pkix.Name{
Organization: []string{"CA"},
},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(10, 0, 0),
IsCA: true,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth},
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Leaf"},
},
IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1), net.IPv6loopback},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour * 24 * 180),
SubjectKeyId: []byte{1, 2, 3, 4, 6},
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
}
derBytes, err := x509.CreateCertificate(rand.Reader, &caTemplate,
&caTemplate, caPk, caSk)
if err != nil {
panic(err)
}
out := &bytes.Buffer{}
pem.Encode(out, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
ioutil.WriteFile("cacert.pem", out.Bytes(), 0600)
out.Reset()
derBytes, err = x509.MarshalPKCS8PrivateKey(sk)
if err != nil {
panic(err)
}
pem.Encode(out, &pem.Block{Type: "PRIVATE KEY", Bytes: derBytes})
ioutil.WriteFile("cakey.pem", out.Bytes(), 0600)
derBytes, err = x509.CreateCertificate(rand.Reader, &template,
&caTemplate, pk, caSk)
if err != nil {
panic(err)
}
out = &bytes.Buffer{}
pem.Encode(out, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
certpool := x509.NewCertPool()
certpool.AppendCertsFromPEM(out.Bytes())
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{
RootCAs: certpool,
}
ioutil.WriteFile("cert.pem", out.Bytes(), 0600)
out.Reset()
derBytes, err = x509.MarshalPKCS8PrivateKey(sk)
if err != nil {
panic(err)
}
pem.Encode(out, &pem.Block{Type: "PRIVATE KEY", Bytes: derBytes})
ioutil.WriteFile("key.pem", out.Bytes(), 0600)
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi!")
})
go func() {
fmt.Printf("Starting server ... \n")
err := http.ListenAndServeTLS("127.0.0.1:40043", "cert.pem", "key.pem", nil)
if err != nil {
log.Fatal(err)
}
}()
fmt.Printf("Sending request ... \n")
resp, err := http.Get("https://127.0.0.1:40043/")
if err != nil {
panic(err)
}
fmt.Printf("Response: %v\n", resp)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment