-
Notifications
You must be signed in to change notification settings - Fork 0
/
ecdsapem.go
131 lines (93 loc) · 2.41 KB
/
ecdsapem.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
package cryptoutils
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/pem"
"fmt"
"io"
"strings"
)
// WriteECDSAKeys writes the private key onto _w_ using the PEM format.
//
// If _public_ is set to `true`, it will include public as well.
func ECDSAPrivateKeyToPEM(w io.Writer, key *ecdsa.PrivateKey, public bool) error {
if key == nil {
return fmt.Errorf("must specify private key to write")
}
privateKeyBytes, err := x509.MarshalECPrivateKey(key)
if err != nil {
return err
}
privateKeyBlock := &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: privateKeyBytes,
}
if err := pem.Encode(w, privateKeyBlock); err != nil {
return err
}
if public {
publicKeyBytes, err := x509.MarshalPKIXPublicKey(&key.PublicKey)
if err != nil {
return err
}
publicKeyBlock := &pem.Block{
Type: "EC PUBLIC KEY",
Bytes: publicKeyBytes,
}
if err = pem.Encode(w, publicKeyBlock); err != nil {
return err
}
}
return nil
}
// WriteECDSAPublicKey writes the public key onto the _w_ `io.Writer`.
func ECDSAPublicKeyToPEM(w io.Writer, key *ecdsa.PublicKey) error {
if key == nil {
return fmt.Errorf("must specify public key to write")
}
publicKeyBytes, err := x509.MarshalPKIXPublicKey(key)
if err != nil {
return err
}
publicKeyBlock := &pem.Block{
Type: "EC PUBLIC KEY",
Bytes: publicKeyBytes,
}
if err = pem.Encode(w, publicKeyBlock); err != nil {
return err
}
return nil
}
func PEMToECDSAPrivateKey(data []byte) (key *ecdsa.PrivateKey, err error) {
var keys []interface{}
keys, err = PEMToKey("", data,
func(fqPath string, block *pem.Block) (key interface{}, stop bool, err error) {
var k interface{}
if strings.HasPrefix(block.Type, "EC") {
if k, err = x509.ParseECPrivateKey(block.Bytes); err == nil {
key = k
stop = true
}
} else {
if k, err = x509.ParsePKCS8PrivateKey(block.Bytes); err == nil {
key = k
stop = true
}
}
return
}, "PRIVATE KEY", "EC PRIVATE KEY")
return keys[0].(*ecdsa.PrivateKey), err
}
func PEMToECDSAPublicKey(data []byte) (key *ecdsa.PublicKey, err error) {
var keys []interface{}
keys, err = PEMToKey("", data,
func(fqPath string, block *pem.Block) (key interface{}, stop bool, err error) {
var k interface{}
if k, err = x509.ParsePKIXPublicKey(block.Bytes); err == nil {
key = k
stop = true
}
return
}, "PUBLIC KEY", "EC PUBLIC KEY")
return keys[0].(*ecdsa.PublicKey), err
}