-
Notifications
You must be signed in to change notification settings - Fork 2
/
decrypt.go
95 lines (84 loc) · 2.02 KB
/
decrypt.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
package agemobile
import (
"bufio"
"bytes"
"io"
"os"
"strings"
"filippo.io/age"
"filippo.io/age/armor"
)
// Decrypt decrypts an input for provided keys seperated with new lines
func Decrypt(keys string, input string) (string, error) {
ids, err := age.ParseIdentities(strings.NewReader(keys))
if err != nil {
return "", err
}
buff := bytes.NewBuffer(nil)
decrypt(ids, strings.NewReader(input), buff)
return buff.String(), nil
}
// Decrypt decrypts an input for provided keys seperated with new lines
func DecryptPass(pass string, input string) (string, error) {
id, err := age.NewScryptIdentity(pass)
if err != nil {
return "", err
}
buff := bytes.NewBuffer(nil)
decryptPass(id, strings.NewReader(input), buff)
return buff.String(), nil
}
// Decrypt decrypts an input file path to output file path for provided keys seperated with new lines
func DecryptFile(keys string, input, output string) error {
ids, err := age.ParseIdentities(strings.NewReader(keys))
if err != nil {
return err
}
fdin, err := os.Open(input)
if err != nil {
return err
}
defer fdin.Close()
if len(output) == 0 {
output = strings.Replace(input, ".age", "", -1)
}
fdout, err := os.Create(output)
if err != nil {
return err
}
defer fdout.Close()
return decrypt(ids, fdin, fdout)
}
// decrypt internal helper
func decrypt(keys []age.Identity, in io.Reader, out io.Writer) error {
rr := bufio.NewReader(in)
if start, _ := rr.Peek(len(armor.Header)); string(start) == armor.Header {
in = armor.NewReader(rr)
} else {
in = rr
}
r, err := age.Decrypt(in, keys...)
if err != nil {
return err
}
if _, err := io.Copy(out, r); err != nil {
return err
}
return nil
}
func decryptPass(keys *age.ScryptIdentity, in io.Reader, out io.Writer) error {
rr := bufio.NewReader(in)
if start, _ := rr.Peek(len(armor.Header)); string(start) == armor.Header {
in = armor.NewReader(rr)
} else {
in = rr
}
r, err := age.Decrypt(in, keys)
if err != nil {
return err
}
if _, err := io.Copy(out, r); err != nil {
return err
}
return nil
}