/
ecdsaParser.go
65 lines (52 loc) · 1.35 KB
/
ecdsaParser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/*
ecdsaParser.go
Created by Dragos-Costin Mandu on 03/09/2021.
*/
package ecdsaParser
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io/ioutil"
)
// Returns an ecdsa private key from a given file path, or error.
func ParsePrivateKeyFromFile(filePath string) (*ecdsa.PrivateKey, error) {
block, err := getPemBlockFromFile(filePath)
if err != nil {
return nil, err
}
privKey, err := x509.ParseECPrivateKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse private key: %v", err)
}
return privKey, nil
}
// Returns an ecdsa public key from a given file path, or error.
func ParsePublicKeyFromFile(filePath string) (*ecdsa.PublicKey, error) {
block, err := getPemBlockFromFile(filePath)
if err != nil {
return nil, err
}
pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return nil, fmt.Errorf("failed to parse public key: %v", err)
}
switch pubKey := pubKey.(type) {
case *ecdsa.PublicKey:
return pubKey, nil
default:
return nil, fmt.Errorf("invalid public key type")
}
}
func getPemBlockFromFile(filePath string) (*pem.Block, error) {
data, err := ioutil.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("failed to read %s: %v", filePath, err)
}
block, _ := pem.Decode(data)
if block == nil {
return nil, fmt.Errorf("failed to decode block")
}
return block, nil
}