-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstringencrypt.go
More file actions
360 lines (317 loc) · 8.7 KB
/
Copy pathstringencrypt.go
File metadata and controls
360 lines (317 loc) · 8.7 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
/******************************************************************************
* StringEncrypt WebApi interface
*
* Version : v1.0.1
* Language : Go
* Author : Bartosz Wójcik
* Project page : https://www.stringencrypt.com
* Web page : https://www.pelock.com
*
*****************************************************************************/
package stringencrypt
import (
"bytes"
"compress/zlib"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
const APIURL = "https://www.stringencrypt.com/api.php"
// Client is a stateful StringEncrypt Web API client.
type Client struct {
APIKey string
APIURL string
UserAgent string
HTTPClient *http.Client
DecompressEncryptSource bool
Command Command
Label string
inputString *string
inputBytes []byte
Compression bool
Language Language
Highlight string
CmdMin int
CmdMax int
Local bool
Unicode bool
LangLocale string
ANSIEncoding string
NewLines NewLine
Template *string
ReturnTemplate bool
IncludeTags bool
IncludeExample bool
IncludeDebugComments bool
}
// New creates a client. An empty key runs demo mode.
func New(apiKey string) *Client {
return &Client{
APIKey: apiKey,
APIURL: APIURL,
UserAgent: "pelock/stringencrypt (+https://www.stringencrypt.com)",
HTTPClient: &http.Client{Timeout: 120 * time.Second},
DecompressEncryptSource: true,
Label: "Label",
Language: LanguagePHP,
CmdMin: 1,
CmdMax: 3,
Unicode: true,
LangLocale: "en_US.utf8",
ANSIEncoding: "WINDOWS-1250",
NewLines: NewLineLF,
}
}
// IsDemo returns activation status and limits for the constructor key.
func (c *Client) IsDemo(ctx context.Context) (*Result, error) {
prev := c.Command
c.Command = CommandIsDemo
result, err := c.Send(ctx)
c.Command = prev
return result, err
}
// Info returns engine version and supported languages.
func (c *Client) Info(ctx context.Context) (*Result, error) {
prev := c.Command
c.Command = CommandInfo
result, err := c.Send(ctx)
c.Command = prev
return result, err
}
// EncryptFileContents encrypts raw file bytes using the current encrypt options.
func (c *Client) EncryptFileContents(ctx context.Context, filePath, label string) (*Result, error) {
raw, err := os.ReadFile(filePath)
if err != nil || len(raw) == 0 {
return nil, fmt.Errorf("file missing, unreadable, or empty")
}
savedCmd, savedString, savedBytes, savedLabel := c.Command, c.inputString, c.inputBytes, c.Label
c.SetCommand(CommandEncrypt).SetBytes(raw).SetLabel(label)
result, err := c.Send(ctx)
c.Command, c.inputString, c.inputBytes, c.Label = savedCmd, savedString, savedBytes, savedLabel
return result, err
}
// EncryptString encrypts a UTF-8 string using the current encrypt options.
func (c *Client) EncryptString(ctx context.Context, s, label string) (*Result, error) {
savedCmd, savedString, savedBytes, savedLabel := c.Command, c.inputString, c.inputBytes, c.Label
c.SetCommand(CommandEncrypt).SetString(s).SetLabel(label)
result, err := c.Send(ctx)
c.Command, c.inputString, c.inputBytes, c.Label = savedCmd, savedString, savedBytes, savedLabel
return result, err
}
func (c *Client) SetCommand(command Command) *Client {
c.Command = command
return c
}
func (c *Client) SetLabel(label string) *Client {
c.Label = label
return c
}
func (c *Client) SetString(s string) *Client {
c.inputString = &s
c.inputBytes = nil
return c
}
func (c *Client) SetBytes(b []byte) *Client {
c.inputBytes = append([]byte(nil), b...)
c.inputString = nil
return c
}
func (c *Client) SetCompression(compression bool) *Client {
c.Compression = compression
return c
}
func (c *Client) SetLanguage(language Language) *Client {
c.Language = language
return c
}
func (c *Client) SetHighlight(highlight string) *Client {
c.Highlight = highlight
return c
}
func (c *Client) SetCmdMin(cmdMin int) *Client {
c.CmdMin = cmdMin
return c
}
func (c *Client) SetCmdMax(cmdMax int) *Client {
c.CmdMax = cmdMax
return c
}
func (c *Client) SetLocal(local bool) *Client {
c.Local = local
return c
}
func (c *Client) SetUnicode(unicode bool) *Client {
c.Unicode = unicode
return c
}
func (c *Client) SetLangLocale(locale string) *Client {
c.LangLocale = locale
return c
}
func (c *Client) SetANSIEncoding(encoding string) *Client {
c.ANSIEncoding = encoding
return c
}
func (c *Client) SetNewLines(newLines NewLine) *Client {
c.NewLines = newLines
return c
}
func (c *Client) SetTemplate(template string) *Client {
c.Template = &template
return c
}
func (c *Client) SetReturnTemplate(returnTemplate bool) *Client {
c.ReturnTemplate = returnTemplate
return c
}
func (c *Client) SetIncludeTags(includeTags bool) *Client {
c.IncludeTags = includeTags
return c
}
func (c *Client) SetIncludeExample(includeExample bool) *Client {
c.IncludeExample = includeExample
return c
}
func (c *Client) SetIncludeDebugComments(includeDebugComments bool) *Client {
c.IncludeDebugComments = includeDebugComments
return c
}
func (c *Client) SetDecompressEncryptSource(decompress bool) *Client {
c.DecompressEncryptSource = decompress
return c
}
// Reset restores request fields to defaults (keeps the activation key).
func (c *Client) Reset() *Client {
c.Command = ""
c.Label = "$label"
c.inputString = nil
c.inputBytes = nil
c.Compression = false
c.Language = LanguagePHP
c.Highlight = ""
c.CmdMin = 1
c.CmdMax = 3
c.Local = false
c.Unicode = true
c.LangLocale = "en_US.utf8"
c.ANSIEncoding = "WINDOWS-1250"
c.NewLines = NewLineLF
c.Template = nil
c.ReturnTemplate = false
c.IncludeTags = false
c.IncludeExample = false
c.IncludeDebugComments = false
return c
}
// ToRequestValues builds the POST body the client would send.
func (c *Client) ToRequestValues() (url.Values, error) {
if c.Command == "" {
return nil, fmt.Errorf("command must be set (use SetCommand)")
}
v := url.Values{}
v.Set("command", string(c.Command))
v.Set("code", c.APIKey)
if c.Command == CommandEncrypt {
v.Set("label", c.Label)
v.Set("compression", bool01(c.Compression))
v.Set("lang", string(c.Language))
v.Set("cmd_min", strconv.Itoa(c.CmdMin))
v.Set("cmd_max", strconv.Itoa(c.CmdMax))
v.Set("local", bool01(c.Local))
v.Set("unicode", bool01(c.Unicode))
v.Set("lang_locale", c.LangLocale)
v.Set("ansi_encoding", c.ANSIEncoding)
v.Set("new_lines", string(c.NewLines))
v.Set("return_template", bool01(c.ReturnTemplate))
v.Set("include_tags", bool01(c.IncludeTags))
v.Set("include_example", bool01(c.IncludeExample))
v.Set("include_debug_comments", bool01(c.IncludeDebugComments))
if c.inputString != nil {
v.Set("string", *c.inputString)
} else if c.inputBytes != nil {
v.Set("bytes", string(c.inputBytes))
}
if c.Highlight != "" {
v.Set("highlight", c.Highlight)
}
if c.Template != nil {
v.Set("template", *c.Template)
}
}
return v, nil
}
// Send posts the current command and returns decoded JSON.
func (c *Client) Send(ctx context.Context) (*Result, error) {
params, err := c.ToRequestValues()
if err != nil {
return nil, err
}
apiURL := c.APIURL
if apiURL == "" {
apiURL = APIURL
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, strings.NewReader(params.Encode()))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
httpClient := c.HTTPClient
if httpClient == nil {
httpClient = http.DefaultClient
}
resp, err := httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if len(body) == 0 {
return nil, fmt.Errorf("empty API response")
}
var result Result
if err := json.Unmarshal(body, &result); err != nil {
return nil, err
}
if c.Command == CommandEncrypt && c.Compression && c.DecompressEncryptSource && result.Error == ErrorSuccess && result.Source != "" {
if plain, err := zlibDecompressBase64(result.Source); err == nil {
result.Source = plain
}
}
return &result, nil
}
func bool01(v bool) string {
if v {
return "1"
}
return "0"
}
func zlibDecompressBase64(s string) (string, error) {
raw, err := base64.StdEncoding.DecodeString(s)
if err != nil {
return "", err
}
zr, err := zlib.NewReader(bytes.NewReader(raw))
if err != nil {
return "", err
}
defer zr.Close()
plain, err := io.ReadAll(zr)
if err != nil {
return "", err
}
return string(plain), nil
}