summaryrefslogtreecommitdiff
path: root/cmd/goaes/commands/decrypt.go
blob: 1ebf85cd18ce3184a9008b13ab8cfc8a66995b4f (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
50
51
52
53
54
55
56
57
58
59
60
61
package commands

import (
	"context"
	"encoding/gob"
	"log/slog"
	"os"
	"path/filepath"

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

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

	if source == "" {
		return cli.Exit("missing source", invalidArgsExit)
	}

	if destination == "" {
		return cli.Exit("missing destination", invalidArgsExit)
	}

	source = filepath.Clean(source)
	file, err := os.Open(source)
	if err != nil {
		return err
	}
	defer func() {
		err := file.Close()
		if err != nil {
			slog.Error("failed to close file", "error", err)
		}
	}()

	enc := gob.NewDecoder(file)

	var encryptedPayload internal.EncryptedDataPayload

	err = enc.Decode(&encryptedPayload)
	if err != nil {
		return err
	}

	passphrase := os.Getenv(PassphraseEnvVar)

	plaintext, err := internal.Decrypt(passphrase, encryptedPayload.DEK, encryptedPayload.Payload, encryptedPayload.Salt)
	if err != nil {
		return err
	}

	destination = filepath.Clean(destination)
	err = os.WriteFile(destination, plaintext, fileMode)
	if err != nil {
		return err
	}

	return nil
}