selfcert/server/main.go

83 lines
2 KiB
Go
Raw Permalink Normal View History

2024-03-24 10:25:34 +00:00
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"flag"
"fmt"
"log"
"math/big"
"net/http"
"os"
"time"
)
func main() {
cFile := flag.String("o", "./cert.pem", "Path to write cert file to use in the client")
port := flag.String("p", "10453", "Server port")
flag.Parse()
cert, key, err := certs(*cFile)
if err != nil {
log.Fatalf("Cannot create certs: %v", err)
}
kp, err := tls.X509KeyPair(cert, key)
if err != nil {
log.Fatalf("Cannot create key pair: %v", err)
}
config := &tls.Config{
Certificates: []tls.Certificate{kp},
}
server := &http.Server{
Addr: ":" + *port,
ReadTimeout: time.Second,
WriteTimeout: time.Second,
TLSConfig: config,
}
server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Print("New Message")
w.Header().Set("Hello", "World")
w.WriteHeader(200)
})
server.ListenAndServeTLS("", "")
}
func certs(outCertFile string) (certOut []byte, keyOut []byte, err error) {
privateKey, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
return nil, nil, fmt.Errorf("generate private key: %w", err)
}
template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "localhost"},
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour * 24 * 365),
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
BasicConstraintsValid: true,
}
derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &privateKey.PublicKey, privateKey)
if err != nil {
return nil, nil, fmt.Errorf("create certificate: %w", err)
}
certOut = pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
keyOut = pem.EncodeToMemory(&pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)})
if len(outCertFile) > 0 {
os.WriteFile(outCertFile, certOut, 0400)
}
return
}