diff options
Diffstat (limited to 'encoding/pem/read.go')
-rw-r--r-- | encoding/pem/read.go | 61 |
1 files changed, 61 insertions, 0 deletions
diff --git a/encoding/pem/read.go b/encoding/pem/read.go new file mode 100644 index 0000000..dbf2f73 --- /dev/null +++ b/encoding/pem/read.go | |||
@@ -0,0 +1,61 @@ | |||
1 | package pem | ||
2 | |||
3 | import ( | ||
4 | "crypto/ecdsa" | ||
5 | "crypto/x509" | ||
6 | "encoding/pem" | ||
7 | "fmt" | ||
8 | "os" | ||
9 | ) | ||
10 | |||
11 | func LoadECPrivateKey(filename string) (*ecdsa.PrivateKey, error) { | ||
12 | pb, err := os.ReadFile(filename) | ||
13 | if err != nil { | ||
14 | return nil, err | ||
15 | } | ||
16 | |||
17 | block, _ := pem.Decode(pb) | ||
18 | if block == nil { | ||
19 | return nil, fmt.Errorf("failed to decode pem bytes") | ||
20 | } | ||
21 | |||
22 | key, err := x509.ParseECPrivateKey(block.Bytes) | ||
23 | if err != nil { | ||
24 | return nil, err | ||
25 | } | ||
26 | |||
27 | return key, nil | ||
28 | } | ||
29 | |||
30 | func CertificateFromPemData(data []byte) (*x509.Certificate, error) { | ||
31 | block, _ := pem.Decode(data) | ||
32 | if block == nil { | ||
33 | return nil, fmt.Errorf("Unable to decode PEM") | ||
34 | } | ||
35 | |||
36 | crt, err := x509.ParseCertificate(block.Bytes) | ||
37 | if err != nil { | ||
38 | return nil, err | ||
39 | } | ||
40 | |||
41 | return crt, nil | ||
42 | } | ||
43 | |||
44 | func CertificateRequestFromPemDataRaw(data []byte) (*x509.CertificateRequest, []byte, error) { | ||
45 | block, _ := pem.Decode(data) | ||
46 | if block == nil { | ||
47 | return nil, nil, fmt.Errorf("Unable to decode PEM") | ||
48 | } | ||
49 | |||
50 | csr, err := x509.ParseCertificateRequest(block.Bytes) | ||
51 | if err != nil { | ||
52 | return nil, nil, err | ||
53 | } | ||
54 | |||
55 | return csr, block.Bytes, nil | ||
56 | } | ||
57 | |||
58 | func CertificateRequestFromPemData(data []byte) (*x509.CertificateRequest, error) { | ||
59 | csr, _, err := CertificateRequestFromPemDataRaw(data) | ||
60 | return csr, err | ||
61 | } | ||