I'm setting up a https server in Go using the following function.
err := http.ListenAndServeTLS(":8080", key, cert, nil)
if err != nil {
log.Fatal("error...")
}
Where key and cert are respectively self-signed key and certificate files. My problem is that for security I need to validate they self-signed key to have a 2048 bits size (or more). How can I securely and cleanly check for this in Go?
package main
import (
"crypto/ecdsa"
"crypto/rsa"
"crypto/tls"
"log"
"net/http"
)
func main() {
certFile := "/tmp/cert.pem"
keyFile := "/tmp/key.pem"
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.Fatal(err)
}
var bitLen int
switch privKey := cert.PrivateKey.(type) {
case *rsa.PrivateKey:
bitLen = privKey.N.BitLen()
case *ecdsa.PrivateKey:
bitLen = privKey.Curve.Params().BitSize
default:
log.Fatal("unsupported private key")
}
if bitLen < 2048 {
log.Fatalf("private key length is too small (size: %d)
", bitLen)
}
tlsConfig := tls.Config{
Certificates: []tls.Certificate{cert},
}
server := http.Server{
Addr: ":8080",
TLSConfig: &tlsConfig,
}
if err := server.ListenAndServeTLS("", ""); err != nil {
log.Fatal(err)
}
}