35 lines
765 B
Go
35 lines
765 B
Go
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,
|
|
})
|
|
}
|