Skip to content

Instantly share code, notes, and snippets.

@SoftwareDevPro
Created November 6, 2020 03:26
Show Gist options
  • Select an option

  • Save SoftwareDevPro/756660c5f9ffb859c5cc1438f76d7f58 to your computer and use it in GitHub Desktop.

Select an option

Save SoftwareDevPro/756660c5f9ffb859c5cc1438f76d7f58 to your computer and use it in GitHub Desktop.
Validation of SSL Certificates with Go
package main
// Checking for an SSL certificate
import (
"crypto/tls"
)
func main() {
// Error Example
_, err := tls.Dial("tcp", "example.com:80", nil)
if err != nil {
panic("Server doesn't support SSL certificate err: " + err.Error())
}
// Valid Example
_, err = tls.Dial("tcp", "microsoft.com:443", nil)
if err != nil {
panic("Server doesn't support SSL certificate err: " + err.Error())
}
}
package main
// Checking the hostname against the SSL certificate
import (
"crypto/tls"
)
func main() {
conn, err := tls.Dial("tcp", "microsoft.com:443", nil)
if err != nil {
panic("Server doesn't support SSL certificate err: " + err.Error())
}
// Error Example
err = conn.VerifyHostname("microsoftz")
if err != nil {
panic("Hostname doesn't match with certificate: " + err.Error())
}
// Valid Example
err = conn.VerifyHostname("microsoft.com")
if err != nil {
panic("Hostname doesn't match with certificate: " + err.Error())
}
}
package main
// Checking the expiration date of an SSL certificate
import (
"crypto/tls"
"fmt"
"time"
)
func main() {
conn, err := tls.Dial("tcp", "microsoft.com:443", nil)
if err != nil {
panic("Server doesn't support SSL certificate err: " + err.Error())
}
err = conn.VerifyHostname("microsoft.com")
if err != nil {
panic("Hostname doesn't match with certificate: " + err.Error())
}
expiry := conn.ConnectionState().PeerCertificates[0].NotAfter
fmt.Printf("Issuer: %s\nExpiry: %v\n", conn.ConnectionState().PeerCertificates[0].Issuer, expiry.Format(time.RFC850))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment