From ceac86f155a809303abb34501f8fe5830bbc1472 Mon Sep 17 00:00:00 2001 From: jmug Date: Thu, 22 Oct 2026 16:27:02 -0700 Subject: [PATCH] feat: Utilities for key generation and marshalling. --- pkg/pki/key.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 pkg/pki/key.go diff --git a/pkg/pki/key.go b/pkg/pki/key.go new file mode 100644 index 0000000..58a6e3c --- /dev/null +++ b/pkg/pki/key.go @@ -0,0 +1,34 @@ +package pki + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "encoding/pem" + "fmt" +) + +// GenerateKey generates a secure ecdsa private key, +// or panics if it can't. +func GenerateKey() *ecdsa.PrivateKey { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + panic(fmt.Errorf("Generating key: %w", err)) + } + return key +} + +// MarshalKeyToPEM returns the bytes of a single encoded PEM block containing +// the given private key. Panics if it can't encode the key. +func MarshalKeyToPEM(key *ecdsa.PrivateKey) []byte { + der, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + panic(fmt.Errorf("Encoding key: %w", err)) + } + + return pem.EncodeToMemory(&pem.Block{ + Type: PEMTypePrivateKey, + Bytes: der, + }) +}