Last active
January 21, 2022 07:24
-
-
Save shivakar/2bf558c27cef15112992 to your computer and use it in GitHub Desktop.
Self Signed TLS Server
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 main | |
import ( | |
"crypto/rand" | |
"crypto/rsa" | |
"crypto/x509" | |
"crypto/x509/pkix" | |
"encoding/pem" | |
"log" | |
"math/big" | |
"net/http" | |
"os" | |
"time" | |
) | |
// GenTLSCertificate generates the TLS certificate | |
func GenTLSCertificate() { | |
now := time.Now() | |
template := &x509.Certificate{ | |
SerialNumber: big.NewInt(now.Unix()), | |
Subject: pkix.Name{ | |
CommonName: "quickserve.example.com", | |
Country: []string{"USA"}, | |
Organization: []string{"example.com"}, | |
OrganizationalUnit: []string{"quickserve"}, | |
}, | |
NotBefore: now, | |
NotAfter: now.AddDate(0, 0, 1), // Valid for one day | |
SubjectKeyId: []byte{113, 117, 105, 99, 107, 115, 101, 114, 118, 101}, | |
BasicConstraintsValid: true, | |
IsCA: true, | |
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, | |
KeyUsage: x509.KeyUsageKeyEncipherment | | |
x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign, | |
} | |
priv, err := rsa.GenerateKey(rand.Reader, 2048) | |
if err != nil { | |
log.Fatalf("Failed to create private key: %s", err) | |
} | |
cert, err := x509.CreateCertificate(rand.Reader, template, template, | |
priv.Public(), priv) | |
if err != nil { | |
log.Fatalf("Failed to create certificate: %s", err) | |
} | |
certOut, err := os.Create("cert.pem") | |
if err != nil { | |
log.Fatalf("Failed to open cert.pem for writing: %s", err) | |
} | |
pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: cert}) | |
certOut.Close() | |
log.Println("Generated cert.pem...") | |
keyOut, err := os.OpenFile("key.pem", | |
os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) | |
if err != nil { | |
log.Fatalf("Failed to open key.pem for writing: %s", err) | |
} | |
pem.Encode(keyOut, &pem.Block{Type: "RSA PRIVATE KEY", | |
Bytes: x509.MarshalPKCS1PrivateKey(priv)}) | |
keyOut.Close() | |
log.Println("Generated key.pem...") | |
} | |
// Usage prints the usage string | |
func Usage() { | |
l := log.New(os.Stderr, "", 0) | |
l.Fatalf("Usage: %s <directory-to-serve>\n", os.Args[0]) | |
} | |
func main() { | |
if len(os.Args) < 2 { | |
Usage() | |
} | |
GenTLSCertificate() | |
mux := http.NewServeMux() | |
mux.Handle("/", http.FileServer(http.Dir(os.Args[1]))) | |
log.Println("Starting server at https://127.0.0.1:8080/") | |
err := http.ListenAndServeTLS("127.0.0.1:8080", "cert.pem", "key.pem", mux) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment