PEM Encode And Parse Public Keys

Wrap a PKIX public key into a PEM block, then decode and parse it back into a typed ECDSA key for configuration or transport.

GoConfig Management

Code

snippet
package main

import (
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"fmt"
)

func main() {
	// 生成 P-256 密钥并导出 PKIX 公钥 DER
	key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	if err != nil {
		fmt.Println("key generation failed:", err)
		return
	}
	der, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
	if err != nil {
		fmt.Println("marshal failed:", err)
		return
	}

	// PEM = base64 正文 + 首尾标签,可直接存文件或配置
	block := &pem.Block{Type: "PUBLIC KEY", Bytes: der}
	encoded := pem.EncodeToMemory(block)
	fmt.Println("pem bytes:", len(encoded))
	fmt.Println(string(encoded[:40]) + "...")

	// 解码回 DER,再解析为具体公钥类型
	parsed, rest := pem.Decode(encoded)
	fmt.Println("type:", parsed.Type, "| trailing bytes:", len(rest))

	pub, err := x509.ParsePKIXPublicKey(parsed.Bytes)
	if err != nil {
		fmt.Println("parse failed:", err)
		return
	}
	ecdsaPub, ok := pub.(*ecdsa.PublicKey)
	fmt.Println("is ecdsa:", ok, "| curve:", ecdsaPub.Curve.Params().Name)
	fmt.Println("same x:", ecdsaPub.X.Cmp(key.PublicKey.X) == 0)
}

How the snippet works

PEM Encode And Parse Public Keys comes down to the function main.

Nothing falls through silently — 3 checkpoints test err != nil on the way through.

Using it

The run emits 7 labeled sections — key generation failed:, marshal failed:, pem bytes:, type:, parse failed:, is ecdsa:, same x: — one per step.

Key statements

if err != nil {
	fmt.Println("key generation failed:", err)
	return
}
if err != nil {
	fmt.Println("marshal failed:", err)
	return
}
if err != nil {
	fmt.Println("parse failed:", err)
	return
}

Interactive Tools for This Topic

FAQ

What does PEM Encode And Parse Public Keys print when run?
No setup needed: run the file and look for labeled lines like `key generation failed:`, `marshal failed:`, `pem bytes:` in the output.