Search code examples
gopem

How do I decode a PEM-encoded PKIX public key?


The example given in Go's official documentation for x509.ParsePKIXPublicKey encounters a runtime error because the Block that pem.Decode() returns is nil. (Playground example)

However, the example in the official documentation for pem.Decode() runs just fine. (Playground example)

The only difference I've spotted between the two examples is the the way the public key is initialized and they way it is used in pem.Decode().

First example:

const pubPEM = `
    -----BEGIN PUBLIC KEY-----
    ...
    -----END PUBLIC KEY-----`
block, _ := pem.Decode([]byte(pubPEM))

Second example:

var pubPEMData = []byte(`
    -----BEGIN PUBLIC KEY-----
    ...
    -----END PUBLIC KEY-----`)
block, rest := pem.Decode(pubPEMData)

I've edited the first example so that it is done in the same way as the second, but this did not change the outcome. (Playground example)

What is causing the first to fail but not the second?


Solution

  • You have spaces in your string, remove them and it will work: fixed example