-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathencrypt.go
85 lines (76 loc) · 1.78 KB
/
encrypt.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
package main
import (
"bytes"
"fmt"
"io"
"strings"
"syscall/js"
"filippo.io/age"
"filippo.io/age/armor"
)
func Encrypt(this js.Value, args []js.Value) interface{} {
output := make(map[string]interface{})
if len(args) != 2 {
output["error"] = "invalid arguments. expected: recipients, input"
return output
}
var recipients = args[0].String()
var input = args[1].String()
buff := bytes.NewBuffer(nil)
ids, err := age.ParseRecipients(strings.NewReader(recipients))
if err != nil {
output["error"] = err.Error()
return output
}
err = encrypt(ids, strings.NewReader(input), buff, true)
if err != nil {
output["error"] = err.Error()
return output
}
output["output"] = buff.String()
return output
}
func EncryptBinary(this js.Value, args []js.Value) interface{} {
if len(args) != 2 {
return fmt.Errorf("invalid arguments. expected: recipients, input")
}
var recipients = args[0].String()
ids, err := age.ParseRecipients(strings.NewReader(recipients))
if err != nil {
return err.Error()
}
input := make([]byte, args[1].Length())
js.CopyBytesToGo(input, args[1])
buff := bytes.NewBuffer(nil)
err = encrypt(ids, bytes.NewReader(input), buff, false)
if err != nil {
return err.Error()
}
result := js.Global().Get("Uint8Array").New(buff.Len())
js.CopyBytesToJS(result, buff.Bytes())
return result
}
// encrypt internal helper
func encrypt(recipients []age.Recipient, in io.Reader, out io.Writer, withArmor bool) error {
var a io.WriteCloser
if withArmor {
a = armor.NewWriter(out)
out = a
}
w, err := age.Encrypt(out, recipients...)
if err != nil {
return err
}
if _, err := io.Copy(w, in); err != nil {
return err
}
if err := w.Close(); err != nil {
return err
}
if a != nil {
if err := a.Close(); err != nil {
return err
}
}
return nil
}