summaryrefslogtreecommitdiff
path: root/cmd/goaes/commands/encrypt.go
blob: 223502b73a2c06cb206d43d83ca977ef7d28adb0 (plain)
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
package commands

import (
	"bytes"
	"context"
	"encoding/gob"
	"os"
	"path/filepath"

	"github.com/nerdsec/goaes/internal"
	"github.com/urfave/cli/v3"
)

func Encrypt(ctx context.Context, cmd *cli.Command) error {
	source := cmd.StringArg("source")
	destination := cmd.StringArg("destination")

	if destination == "" {
		destination = source + ".goaes"
	}

	source = filepath.Clean(source)
	plaintext, err := os.ReadFile(source)
	if err != nil {
		return err
	}

	passphrase := os.Getenv(PassphraseEnvVar)

	payload, err := internal.Encrypt(passphrase, plaintext)
	if err != nil {
		return err
	}

	var dataBuffer bytes.Buffer
	enc := gob.NewEncoder(&dataBuffer)

	err = enc.Encode(payload)
	if err != nil {
		return err
	}

	err = os.WriteFile(destination, dataBuffer.Bytes(), fileMode)
	if err != nil {
		return err
	}

	return nil
}