-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
79 lines (70 loc) · 1.84 KB
/
util.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
package ezlicense
import (
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/json"
"encoding/pem"
"time"
)
func toBase64Json(data interface{}) (string, error) {
inJson, err := json.Marshal(data)
if err != nil {
return "", err
}
encoded := base64.StdEncoding.EncodeToString(inJson)
return encoded, nil
}
func fromBase64Json(input string, out any) error {
decoded, err := base64.StdEncoding.DecodeString(input)
if err != nil {
return err
}
err = json.Unmarshal(decoded, &out)
if err != nil {
return err
}
return nil
}
// Read a pem-encoded public key
func ReadPemPublicKey(input string) (*rsa.PublicKey, error) {
decoded, _ := pem.Decode([]byte(input))
return x509.ParsePKCS1PublicKey(decoded.Bytes)
}
// Read a pem-encoded private key
func ReadPemPrivateKey(input string) (*rsa.PrivateKey, error) {
decoded, _ := pem.Decode([]byte(input))
return x509.ParsePKCS1PrivateKey(decoded.Bytes)
}
// Export a public key to pem
func ExportPublicKey(pub rsa.PublicKey) string {
marshalled := x509.MarshalPKCS1PublicKey(&pub)
block := pem.Block{
Type: "PUBLIC KEY",
Bytes: marshalled,
}
encoded := pem.EncodeToMemory(&block)
return string(encoded)
}
// Export a private key to pem
func ExportPrivateKey(private rsa.PrivateKey) string {
marshalled := x509.MarshalPKCS1PrivateKey(&private)
block := pem.Block{
Type: "PRIVATE KEY",
Bytes: marshalled,
}
encoded := pem.EncodeToMemory(&block)
return string(encoded)
}
// The useful data of a license, decoded and without a signature
type LicenseData struct {
Expires time.Time `json:"expires"`
AdditionalData map[string]interface{} `json:"additional_data"`
}
// An intermediate struct to represent the contents of the license
type LicenseDataSigned struct {
// base64 encoded json
Data string `json:"data"`
// base64 signature
Signature string `json:"signature"`
}