feat: Utilities for key generation and marshalling.
This commit is contained in:
1 parent
bf3ca1d0bf
commit
ceac86f155
1 file changed
+34
@@ -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,
|
||||||
|
})
|
||||||
|
}
|
||||||
Reference in new issue
Block a user