-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathencrypt.go
82 lines (75 loc) · 1.81 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
package agemobile
import (
"bytes"
"fmt"
"io"
"os"
"strings"
"filippo.io/age"
"filippo.io/age/armor"
)
// Encrypt encryptes an input for provided recipients seperated with new lines
func Encrypt(recipients string, input string, withArmor bool) (string, error) {
buff := bytes.NewBuffer(nil)
ids, err := age.ParseRecipients(strings.NewReader(recipients))
if err != nil {
return "", err
}
err = encrypt(ids, strings.NewReader(input), buff, withArmor)
return buff.String(), err
}
// EncryptPass
func EncryptPass(pass string, input string, withArmor bool) (string, error) {
buff := bytes.NewBuffer(nil)
r, err := age.NewScryptRecipient(pass)
if err != nil {
return "", err
}
err = encrypt([]age.Recipient{r}, strings.NewReader(input), buff, withArmor)
return buff.String(), err
}
// EncryptFile encryptes an input file path to output file path for provided recipients seperated with new lines
func EncryptFile(recipients string, input, output string, withArmor bool) error {
fdin, err := os.Open(input)
if err != nil {
return err
}
defer fdin.Close()
if len(output) == 0 {
output = fmt.Sprintf("%s.age", input)
}
fdout, err := os.Create(output)
if err != nil {
return err
}
defer fdout.Close()
ids, err := age.ParseRecipients(strings.NewReader(recipients))
if err != nil {
return err
}
return encrypt(ids, fdin, fdout, withArmor)
}
// 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
}