/
encrypt.go
54 lines (42 loc) · 969 Bytes
/
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
package main
import (
"crypto/rand"
"fmt"
"io"
cli "github.com/urfave/cli/v2"
)
func encryptMain(c *cli.Context) error {
if c.String(passphraseOption) == "" {
return ErrPassEmpty
}
if !c.Args().Present() {
return ErrNoArgs
}
fname := c.Args().First()
plain, err := ReadFile(fname, ExitArgLoadFailed)
if err != nil {
return err
}
pass := c.String(passphraseOption)
gcm, salt, err := NewAESGCM(pass, func() (Salt, error) {
return NewSalt(saltSize)
})
if err != nil {
return err
}
nonce := make([]byte, gcm.NonceSize())
if _, err := io.ReadFull(rand.Reader, nonce); err != nil {
return err
}
cipher := gcm.Seal(nil, nonce, plain, nil)
outb := append(nonce, cipher...)
path := c.Path(outputOption)
if path == "" {
fmt.Println(string(outb))
return nil
}
if err := writeOutput(salt, c.Path(saltOption)); err != nil {
return err
}
return writeOutput(outb, path)
}