Golang crypto/tls.LoadX509KeyPair function example

package crypto/tls

LoadX509KeyPair reads and parses a public/private key pair from a pair of files. The files must contain PEM encoded data.

The PEM and KEY files are generated with this command.

openssl req -new -nodes -x509 -out server.pem -keyout server.key -days 365

You should generate your own key pair properly to use in production servers!

Golang crypto/tls.LoadX509KeyPair function usage example

 package main

  import (
 "fmt"
 "os"
 "crypto/tls"
 "crypto/rand"
 "crypto/x509"
  )

  func main() {

 certificate, err := tls.LoadX509KeyPair("server.pem", "server.key")

 if err != nil {
 fmt.Println(err)
 os.Exit(1)
 }

 // certificate
 var cert_byte [][]byte
 cert_byte = certificate.Certificate
 fmt.Printf("Server.pem file content :\n%s\n", cert_byte)


 // private key
 fmt.Printf("Server.key(Private Key) \n%x\n", certificate.PrivateKey)


 // OCSPStaple
 var ocsp []byte
 ocsp = certificate.OCSPStaple
 fmt.Printf("OCSPStaple : \n%x\n", ocsp)

 // Leaf
 var lf *x509.Certificate

 fmt.Printf("Leaf \n%x\n", &lf)

  }

Example output :

Server.pem file content : 0E1�0�� *�H��0 0 UAU10U Some-State1!0U ......�js���k ]

Server.key(Private Key) &{{d5........7099762d3dfc4 []}}

OCSPStaple : nil

Leaf c208042020

  See also : Golang crypto/tls.X509KeyPair function example

Advertisement