forked from go-acme/lego
-
Notifications
You must be signed in to change notification settings - Fork 1
/
crypto.go
56 lines (44 loc) · 1.01 KB
/
crypto.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
package main
import (
"crypto"
"crypto/ecdsa"
"crypto/elliptic"
"crypto/rand"
"crypto/x509"
"encoding/pem"
"errors"
"io/ioutil"
"os"
)
func generatePrivateKey(file string) (crypto.PrivateKey, error) {
privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
if err != nil {
return nil, err
}
keyBytes, err := x509.MarshalECPrivateKey(privateKey)
if err != nil {
return nil, err
}
pemKey := pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}
certOut, err := os.Create(file)
if err != nil {
return nil, err
}
pem.Encode(certOut, &pemKey)
certOut.Close()
return privateKey, nil
}
func loadPrivateKey(file string) (crypto.PrivateKey, error) {
keyBytes, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
keyBlock, _ := pem.Decode(keyBytes)
switch keyBlock.Type {
case "RSA PRIVATE KEY":
return x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
case "EC PRIVATE KEY":
return x509.ParseECPrivateKey(keyBlock.Bytes)
}
return nil, errors.New("Unknown private key type.")
}