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.
Code
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
X.509 PEM Certificate DecoderDecode X.509 PEM certificates in pure JavaScript using ASN.1 DER parsing to inspect subject, issuer, SANs, key usage, and SHA-256 fingerprints.cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.