This repository has been archived by the owner on Nov 5, 2019. It is now read-only.
/
resource.go
107 lines (88 loc) · 1.79 KB
/
resource.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package esecret
import (
"github.com/Shopify/ejson/crypto"
)
type ctx struct {
publicKey string
publicKeyBytes [32]byte
privateKeyLoaded bool
privateKey string
privateKeyBytes [32]byte
keydir string
removeTags bool
decryptFile bool
file FileInterface
}
type ctxConfig struct {
keydir string
privateKey string
decrypt bool
removeTags bool
}
func newCtx(config ctxConfig) *ctx {
return &ctx{
keydir: config.keydir,
privateKey: config.privateKey,
decryptFile: config.decrypt,
removeTags: config.removeTags,
file: &file{},
}
}
func (c *ctx) loadPublicKey(s string) error {
v, err := extractKey(s)
if err != nil {
return err
}
c.publicKey = s
c.publicKeyBytes = v
return nil
}
func (c *ctx) loadPrivateKey() error {
if c.privateKeyLoaded {
return nil
}
if len(c.privateKey) == 0 {
privkey, err := c.file.ReadPrivateKey(c.keydir, c.publicKey)
if err != nil {
return err
}
v, err := extractKey(privkey)
if err != nil {
return err
}
c.privateKeyLoaded = true
c.privateKeyBytes = v
return nil
}
v, err := extractKey(c.privateKey)
if err != nil {
return err
}
c.privateKeyLoaded = true
c.privateKeyBytes = v
return nil
}
func (c *ctx) encrypt(value string) (string, error) {
var kp crypto.Keypair
if err := kp.Generate(); err != nil {
return "", err
}
encrypter := kp.Encrypter(c.publicKeyBytes)
v, err := encrypter.Encrypt([]byte(value))
if err != nil {
return "", err
}
return string(v), nil
}
func (c *ctx) decrypt(value string) (string, error) {
kp := crypto.Keypair{
Public: c.publicKeyBytes,
Private: c.privateKeyBytes,
}
decrypter := kp.Decrypter()
v, err := decrypter.Decrypt([]byte(value))
if err != nil {
return "", err
}
return string(v), nil
}