-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathkey.go
61 lines (51 loc) · 1.14 KB
/
key.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
package certify
import (
"bytes"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"fmt"
)
// PrivateKey hold private key
type PrivateKey struct {
*ecdsa.PrivateKey
}
// GetPrivateKey returns struct PrivateKey containing the private key
func GetPrivateKey() (*PrivateKey, error) {
pkey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
if err != nil {
return &PrivateKey{}, err
}
return &PrivateKey{
pkey,
}, nil
}
// String returns string of private key in pem encoded format
func (p *PrivateKey) String() string {
b, err := x509.MarshalECPrivateKey(p.PrivateKey)
if err != nil {
return ""
}
var w bytes.Buffer
if err := pem.Encode(&w, &pem.Block{
Type: "EC PRIVATE KEY",
Bytes: b,
}); err != nil {
return ""
}
return w.String()
}
// ParsePrivatekey parse given []byte private key to struct *ecdsa.PrivateKey
func ParsePrivateKey(pkey []byte) (*ecdsa.PrivateKey, error) {
b, _ := pem.Decode(pkey)
if b == nil {
return &ecdsa.PrivateKey{}, fmt.Errorf("no pem data found")
}
u, err := x509.ParseECPrivateKey(b.Bytes)
if err != nil {
return &ecdsa.PrivateKey{}, err
}
return u, nil
}