Walkthrough a PEM file in Go

A few months ago, I posted how to create a PKI in Go. Today I’d like to add share a useful function (at least from my point of view) that I found myself to write.

The problem arose when I had a function that required as input a *pem.Block of the public key, but all I had was the PEM file containing, as you can imagine:

  • the Private Key
  • the Public Key
  • the CA Public Key

I think this is a typical situation, and for this, I’d like to share a function I wrote to extract it. I know that it’s probably not perfect, but it could be a good starting point for many of you, and if you have suggestions, please leave a comment down below or send me an email, and I’ll update the post!

The idea behind this implementation is basically to iterate on the PEM file (in []byte form) and read one PEM block every time until we find one of type CERTIFICATE or we end the file. Since we are going to return a pointer to a pem.Block, if you don’t find the desired block before the end of the file, we are going to return a nil.

So here is the implementation:

func pemFirstCertificate(PEMRest []byte) *pem.Block {
    for {
        block, rest := pem.Decode(PEMRest)
        if block == nil {
        if block.Type == "CERTIFICATE" {
            return block
        if len(rest) == 0 { 
        PEMRest = rest
    return nil 

As you might imagine, you’ll need to import encoding/pem, if you are not already doing it:

import (

As you can notice, Go makes this very simple and the Go code is straightforward to read so that it makes the steps reasonably clear.