feat: Util to read private key from file.
This commit is contained in:
1 parent
068db76488
commit
5ba8ca9417
1 file changed
+30
-2
+30
-2
@@ -6,12 +6,14 @@ import (
|
||||
"crypto/rand"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
)
|
||||
|
||||
// GenerateKey generates a secure ecdsa private key,
|
||||
// NewKey generates a secure ecdsa private key,
|
||||
// or panics if it can't.
|
||||
func GenerateKey() *ecdsa.PrivateKey {
|
||||
func NewKey() *ecdsa.PrivateKey {
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("Generating key: %w", err))
|
||||
@@ -32,3 +34,29 @@ func MarshalKeyToPEM(key *ecdsa.PrivateKey) []byte {
|
||||
Bytes: der,
|
||||
})
|
||||
}
|
||||
|
||||
// ParseKeyFromFile retrieves a private key stored in PEM format from a file.
|
||||
func ParseKeyFromFile(fn string) (*ecdsa.PrivateKey, error) {
|
||||
pemBytes, err := os.ReadFile(fn)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
keyBlock, _ := pem.Decode(pemBytes)
|
||||
if keyBlock == nil || keyBlock.Type != PEMTypePrivateKey {
|
||||
return nil, fmt.Errorf("file was not PEM or first block wasn't %s", PEMTypePrivateKey)
|
||||
}
|
||||
|
||||
rawKey, err := x509.ParsePKCS8PrivateKey(keyBlock.Bytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var key *ecdsa.PrivateKey
|
||||
var ok bool
|
||||
key, ok = rawKey.(*ecdsa.PrivateKey)
|
||||
if !ok {
|
||||
return nil, errors.New("key was not ecdsa")
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
Reference in new issue
Block a user