forked from mmadfox/go-crx3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkeys.go
54 lines (50 loc) · 1.08 KB
/
keys.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
package crx
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"io/ioutil"
"os"
)
// NewPrivateKey returns a new private key.
func NewPrivateKey() (*rsa.PrivateKey, error) {
return rsa.GenerateKey(rand.Reader, 2048)
}
// SavePrivateKey saves private key to file.
func SavePrivateKey(filename string, key *rsa.PrivateKey) error {
if key == nil {
key, _ = NewPrivateKey()
}
fd, err := os.Create(filename)
if err != nil {
return err
}
defer fd.Close()
bytes, err := x509.MarshalPKCS8PrivateKey(key)
if err != nil {
return err
}
block := &pem.Block{
Type: "RSA PRIVATE KEY",
Bytes: bytes,
}
_, err = fd.Write(pem.EncodeToMemory(block))
return err
}
// LoadPrivateKey loads the private key from a file into memory.
func LoadPrivateKey(filename string) (*rsa.PrivateKey, error) {
buf, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
block, _ := pem.Decode(buf)
if block == nil {
return nil, ErrPrivateKeyNotFound
}
r, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return r.(*rsa.PrivateKey), nil
}