When making HTTPS requests to servers with custom certificates, it's essential to verify their authenticity to ensure secure communication.
In one such scenario, an application running on a separate port was encountering an SSL error when attempting to access a REST API hosted on HTTPS. The cause of this error was an unrecognized certificate authority.
To address this issue, adding the certificate authority to the transport during HTTPS requests is crucial. The following code snippet demonstrates how to achieve this:
package main import ( "crypto/tls" "io/ioutil" "log" "net/http" "crypto/x509" ) func main() { // Read the root CA certificate from file caCert, err := ioutil.ReadFile("rootCA.crt") if err != nil { log.Fatal(err) } // Create an X.509 certificate pool and add the CA certificate caCertPool := x509.NewCertPool() caCertPool.AppendCertsFromPEM(caCert) // Configure the TLS client to trust the CA tlsConfig := &tls.Config{ RootCAs: caCertPool, } // Create a new HTTP client with the modified TLS configuration client := &http.Client{ Transport: &http.Transport{ TLSClientConfig: tlsConfig, }, } // Make an HTTPS request using the client _, err = client.Get("https://secure.domain.com") if err != nil { panic(err) } }
Alternatively, if no pre-existing CA certificate is available, the solution suggests generating your own CA and issuing certificates signed by that CA. The following commands provide a step-by-step approach:
Generating CA:
openssl genrsa -out rootCA.key 4096 openssl req -x509 -new -key rootCA.key -days 3650 -out rootCA.crt
Generating Certificate for secure.domain.com Signed by CA:
openssl genrsa -out secure.domain.com.key 2048 openssl req -new -key secure.domain.com.key -out secure.domain.com.csr #In answer to question `Common Name (e.g. server FQDN or YOUR name) []:` you should set `secure.domain.com` (your real domain name) openssl x509 -req -in secure.domain.com.csr -CA rootCA.crt -CAkey rootCA.key -CAcreateserial -days 365 -out secure.domain.com.crt
The above is the detailed content of How to Verify HTTPS Certificates in Golang When Encountering SSL Errors?. For more information, please follow other related articles on the PHP Chinese website!