-
Notifications
You must be signed in to change notification settings - Fork 0
/
certificate.go
51 lines (43 loc) · 1.11 KB
/
certificate.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
package certify
import (
"crypto/ecdsa"
"crypto/x509"
"encoding/json"
"encoding/pem"
"log"
)
type Certificate struct {
Cert *x509.Certificate `json:"cert"`
Pkey *ecdsa.PrivateKey `json:"fkey"`
}
func (c *Certificate) Json() ([]byte, error) {
encodedCert, err := json.Marshal(map[string][]byte{
"cert": c.pemEncoded(),
"pkey": c.pemEncodedPrivateKey()})
if err != nil {
return nil, err
}
return encodedCert, nil
}
func (c *Certificate) pemEncoded() []byte {
return pem.EncodeToMemory(&pem.Block{
Type: "CERTIFICATE", Bytes: c.Cert.Raw})
}
func (c *Certificate) pemEncodedPrivateKey() []byte {
return pem.EncodeToMemory(&pem.Block{
Type: "EC PRIVATE KEY", Bytes: c.getPrivateKeyBytes()})
}
func (c *Certificate) getPrivateKeyBytes() []byte {
privKeyBytes, err := x509.MarshalECPrivateKey(c.Pkey)
if err != nil {
log.Fatalf("Failed to marshal EC private key: %s\n", err)
}
return privKeyBytes
}
func CertificateFromRawBytes(rawCert []byte) (*Certificate, error) {
cert, err := x509.ParseCertificate(rawCert)
if err != nil {
return nil, err
}
return &Certificate{Cert: cert, Pkey: nil}, nil
}