Golang encoding/pem.Decode() function example

package encoding/pem

Decode will find the next PEM formatted block (certificate, private key etc) in the input. It returns that block and the remainder of the input. If no PEM data is found, p (1st return variable) is nil and the whole of the input is returned in rest ( 2nd return variable) .

Golang encoding/pem.Decode() function usage example

 // Load PEM
 pemfile, err := os.Open("private.pem")

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

 // need to convert pemfile to []byte for decoding

 pemfileinfo, _ := pemfile.Stat()
 var size int64 = pemfileinfo.Size()
 pembytes := make([]byte,size)

 // read pemfile content into pembytes
 buffer := bufio.NewReader(pemfile)
 _, err = buffer.Read(pembytes)


 // proper decoding now
 data, _ := pem.Decode([]byte(pembytes))

See https://www.socketloop.com/tutorials/golang-tutorial-on-loading-gob-and-pem-files for full example

Reference :

http://golang.org/pkg/encoding/pem/#Decode

Advertisement