Skip to content

Instantly share code, notes, and snippets.

@anxiousmodernman
Created February 5, 2016 17:54
Show Gist options
  • Save anxiousmodernman/826b91bdb8fa4690635e to your computer and use it in GitHub Desktop.
Save anxiousmodernman/826b91bdb8fa4690635e to your computer and use it in GitHub Desktop.
golang openssl example
// NewOpenSSLTransport returns a TCP connection establish with OpenSSL.
func NewOpenSSLTransport(trustPath, certPath, keyPath, host, port string, dialOpts *OpenSSLDialOptions) (*openssl.Conn, error) {
// Default to flag 0
if dialOpts == nil {
dialOpts = &OpenSSLDialOptions{}
}
ctx, err := openssl.NewCtx()
if err != nil {
return nil, err
}
ctx.SetOptions(openssl.CipherServerPreference)
ctx.SetOptions(openssl.NoSSLv3)
err = ctx.LoadVerifyLocations(trustPath, "")
if err != nil {
return nil, err
}
certBytes, err := ioutil.ReadFile(certPath)
if err != nil {
return nil, err
}
cert, err := openssl.LoadCertificateFromPEM(certBytes)
if err != nil {
return nil, err
}
ctx.UseCertificate(cert)
keyBytes, err := ioutil.ReadFile(keyPath)
if err != nil {
return nil, err
}
privKey, err := openssl.LoadPrivateKeyFromPEM(keyBytes)
if err != nil {
return nil, err
}
ctx.UsePrivateKey(privKey)
addr := host + ":" + port
// New context from files?
context, err := openssl.NewCtxFromFiles(certPath, keyPath)
if err != nil {
return nil, err
}
_ = context.LoadVerifyLocations(trustPath, "")
ctx = context
conn, err := openssl.Dial("tcp", addr, ctx, dialOpts.Flags)
if err != nil {
log.Println("Error making openssl conn!")
return nil, err
}
return conn, nil
}
@anxiousmodernman
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment