aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--dec/dec.go33
-rw-r--r--dec/dec_test.go96
-rw-r--r--enc/enc.go57
-rw-r--r--enc/enc_test.go147
-rw-r--r--internal/sym/dec.go25
-rw-r--r--internal/sym/enc.go41
-rw-r--r--internal/sym/oae.go3
-rw-r--r--internal/sym/shared_options.go20
-rw-r--r--internal/sym/sym_test.go188
9 files changed, 561 insertions, 49 deletions
diff --git a/dec/dec.go b/dec/dec.go
index ce0a719..049bc74 100644
--- a/dec/dec.go
+++ b/dec/dec.go
@@ -3,22 +3,34 @@ package main
import (
"flag"
"fmt"
+ "io"
"os"
"golang.org/x/term"
"roseh.moe/cmd/sym/internal/sym"
)
-var passwordFlag = flag.String("p", "", "use the specified password; if not provided, dec will prompt for a password")
+type options struct {
+ password string
+ force bool
-func dec() error {
- args := flag.Args()
- if len(args) == 0 && *passwordFlag == "" {
+ stdin io.Reader
+ stdout io.Writer
+}
+
+func (o *options) dec(args ...string) error {
+ if o.stdin == nil {
+ o.stdin = os.Stdin
+ }
+ if o.stdout == nil {
+ o.stdout = os.Stdout
+ }
+ if len(args) == 0 && o.password == "" {
return fmt.Errorf("-p is required when reading from stdin")
}
var password string
- if *passwordFlag != "" {
- password = *passwordFlag
+ if o.password != "" {
+ password = o.password
} else {
fmt.Fprint(os.Stderr, "Enter password: ")
pw, err := term.ReadPassword(int(os.Stdin.Fd()))
@@ -29,10 +41,10 @@ func dec() error {
password = string(pw)
}
if len(args) == 0 {
- return sym.Decrypt(os.Stdout, os.Stdin, password)
+ return sym.Decrypt(o.stdout, o.stdin, password)
}
for _, fileName := range args {
- if err := sym.DecryptFile(fileName, password); err != nil {
+ if err := sym.DecryptFile(fileName, password, sym.Force(o.force)); err != nil {
return err
}
}
@@ -40,8 +52,11 @@ func dec() error {
}
func main() {
+ o := new(options)
+ flag.StringVar(&o.password, "p", "", "use the specified password; if not provided, dec will prompt for a password")
+ flag.BoolVar(&o.force, "f", false, "overwrite output files even if they already exist")
flag.Parse()
- if err := dec(); err != nil {
+ if err := o.dec(flag.Args()...); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
diff --git a/dec/dec_test.go b/dec/dec_test.go
new file mode 100644
index 0000000..823ab68
--- /dev/null
+++ b/dec/dec_test.go
@@ -0,0 +1,96 @@
+package main
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "roseh.moe/cmd/sym/internal/sym"
+)
+
+func mustWriteFile(t *testing.T, path string, content []byte) {
+ t.Helper()
+ if err := os.WriteFile(path, content, 0600); err != nil {
+ t.Fatalf("Failed to write test file: %s", err)
+ }
+}
+
+func mustReadFile(t *testing.T, path string) []byte {
+ t.Helper()
+ content, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("Failed to read file: %s", err)
+ }
+ return content
+}
+
+func mustRemove(t *testing.T, path string) {
+ t.Helper()
+ if err := os.Remove(path); err != nil {
+ t.Fatalf("Failed to remove file: %s", err)
+ }
+}
+
+func TestDec(t *testing.T) {
+ t.Parallel()
+
+ const password = "asdf"
+ fileContent := []byte("test file content")
+ fileName := filepath.Join(t.TempDir(), "file")
+ mustWriteFile(t, fileName, fileContent)
+ if err := sym.EncryptFile(fileName, password); err != nil {
+ t.Errorf("EncryptFile failed: %s", err)
+ }
+ mustRemove(t, fileName)
+ err := (&options{password: password}).dec(fileName + ".enc")
+ if err != nil {
+ t.Errorf("dec failed: %s", err)
+ }
+ gotFileContents := mustReadFile(t, fileName)
+ if !bytes.Equal(gotFileContents, fileContent) {
+ t.Errorf("dec returned incorrect contents %q, want %q", gotFileContents, fileContent)
+ }
+}
+
+func TestDec_UsageError(t *testing.T) {
+ t.Parallel()
+
+ err := (&options{}).dec()
+ if err == nil {
+ t.Errorf("dec without -p when reading from stdin, want error")
+ }
+}
+
+func TestDec_NotFound(t *testing.T) {
+ t.Parallel()
+
+ err := (&options{password: "asdf"}).dec("my-nonexistent-file-name.txt")
+ if err == nil {
+ t.Errorf("dec succeeded with nonexistent file, want error")
+ }
+}
+
+func TestDec_Stdin(t *testing.T) {
+ t.Parallel()
+
+ const password = "asdf"
+ content := []byte("test contents")
+ encrypted := new(bytes.Buffer)
+ if err := sym.EncryptBinary(encrypted, bytes.NewReader(content), password); err != nil {
+ t.Fatalf("Failed to encrypt: %s", err)
+ }
+ gotContentBuf := new(bytes.Buffer)
+ opts := &options{
+ password: password,
+ stdin: bytes.NewReader(encrypted.Bytes()),
+ stdout: gotContentBuf,
+ }
+ if err := opts.dec(); err != nil {
+ t.Fatalf("dec failed: %s", err)
+ }
+ gotContent := gotContentBuf.Bytes()
+ if !bytes.Equal(gotContent, content) {
+ t.Errorf("dec returned incorrect contents %q, want %q", gotContent, content)
+ }
+}
diff --git a/enc/enc.go b/enc/enc.go
index ac24bef..5fb382e 100644
--- a/enc/enc.go
+++ b/enc/enc.go
@@ -5,6 +5,7 @@ import (
"encoding/binary"
"flag"
"fmt"
+ "io"
"os"
"strings"
@@ -13,24 +14,37 @@ import (
"roseh.moe/pkg/wordlist"
)
-var (
- generatePassword = flag.Bool("g", false, "generate a secure password automatically (password will be printed to stderr)")
- passwordFlag = flag.String("p", "", "use the specified password; if not provided, enc will prompt for a password")
- asciiOutput = flag.Bool("a", false, "Output in base64, default is binary output")
-)
+type options struct {
+ generatePassword bool
+ password string
+ asciiOutput bool
+ force bool
+
+ passwordOut io.Writer
+ stdin io.Reader
+ stdout io.Writer
+}
-func enc() error {
- if *generatePassword && *passwordFlag != "" {
+func (o *options) enc(args ...string) error {
+ if o.passwordOut == nil {
+ o.passwordOut = os.Stderr
+ }
+ if o.stdin == nil {
+ o.stdin = os.Stdin
+ }
+ if o.stdout == nil {
+ o.stdout = os.Stdout
+ }
+ if o.generatePassword && o.password != "" {
return fmt.Errorf("-g and -p cannot be used together")
}
- args := flag.Args()
- if len(args) == 0 && !*generatePassword && *passwordFlag == "" {
+ if len(args) == 0 && !o.generatePassword && o.password == "" {
return fmt.Errorf("must use -g or -p when reading from stdin")
}
var password string
- if *passwordFlag != "" {
- password = *passwordFlag
- } else if *generatePassword {
+ if o.password != "" {
+ password = o.password
+ } else if o.generatePassword {
const nWords = 10
buf := make([]byte, 2*nWords)
rand.Read(buf)
@@ -39,7 +53,9 @@ func enc() error {
words[i] = wordlist.Words[binary.NativeEndian.Uint16(buf[2*i:])&0x1fff]
}
password = strings.Join(words, " ")
- fmt.Fprintf(os.Stderr, "Your password: %s\n", password)
+ fmt.Fprint(os.Stderr, "Your password: ")
+ fmt.Fprint(o.passwordOut, password)
+ fmt.Fprintln(os.Stderr)
} else {
fmt.Fprint(os.Stderr, "Enter password: ")
pw, err := term.ReadPassword(int(os.Stdin.Fd()))
@@ -50,13 +66,13 @@ func enc() error {
password = string(pw)
}
if len(args) == 0 {
- if *asciiOutput {
- return sym.EncryptBase64(os.Stdout, os.Stdin, password)
+ if o.asciiOutput {
+ return sym.EncryptBase64(o.stdout, o.stdin, password)
}
- return sym.EncryptBinary(os.Stdout, os.Stdin, password)
+ return sym.EncryptBinary(o.stdout, o.stdin, password)
}
for _, fileName := range args {
- if err := sym.EncryptFile(fileName, password, *asciiOutput); err != nil {
+ if err := sym.EncryptFile(fileName, password, sym.WithASCIIOutput(o.asciiOutput), sym.Force(o.force)); err != nil {
return err
}
}
@@ -64,8 +80,13 @@ func enc() error {
}
func main() {
+ o := new(options)
+ flag.BoolVar(&o.generatePassword, "g", false, "generate a secure password automatically (password will be printed to stderr)")
+ flag.StringVar(&o.password, "p", "", "use the specified password; if not provided, enc will prompt for a password")
+ flag.BoolVar(&o.asciiOutput, "a", false, "output in base64, default is binary output")
+ flag.BoolVar(&o.force, "f", false, "overwrite output files even if they already exist")
flag.Parse()
- if err := enc(); err != nil {
+ if err := o.enc(flag.Args()...); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
diff --git a/enc/enc_test.go b/enc/enc_test.go
new file mode 100644
index 0000000..e133b04
--- /dev/null
+++ b/enc/enc_test.go
@@ -0,0 +1,147 @@
+package main
+
+import (
+ "bytes"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "roseh.moe/cmd/sym/internal/sym"
+)
+
+func mustWriteFile(t *testing.T, path string, content []byte) {
+ t.Helper()
+ if err := os.WriteFile(path, content, 0600); err != nil {
+ t.Fatalf("Failed to write test file: %s", err)
+ }
+}
+
+func mustReadFile(t *testing.T, path string) []byte {
+ t.Helper()
+ content, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("Failed to read file: %s", err)
+ }
+ return content
+}
+
+func TestEnc(t *testing.T) {
+ t.Parallel()
+
+ const password = "asdf"
+ fileContent := []byte("test file content")
+ fileName := filepath.Join(t.TempDir(), "file")
+ mustWriteFile(t, fileName, fileContent)
+ if err := (&options{password: password}).enc(fileName); err != nil {
+ t.Fatalf("enc failed: %s", err)
+ }
+ if err := sym.DecryptFile(fileName+".enc", password, sym.Force(true)); err != nil {
+ t.Fatalf("Failed to decrypt encrypted file: %s", err)
+ }
+ gotFileContents := mustReadFile(t, fileName)
+ if !bytes.Equal(gotFileContents, fileContent) {
+ t.Errorf("encrypt round trip returned incorrect contents %q, want %q", gotFileContents, fileContent)
+ }
+}
+
+func TestEnc_UsageError(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ desc string
+ generatePassword bool
+ password string
+ files []string
+ }{{
+ desc: "GeneratePasswordAndPassword",
+ generatePassword: true,
+ password: "asdf",
+ }, {
+ desc: "MissingPasswordStdin",
+ generatePassword: false,
+ password: "",
+ }, {
+ desc: "NonexistentFile",
+ password: "asdf",
+ files: []string{"my-nonexistent-file.txt"},
+ }} {
+ t.Run(tc.desc, func(t *testing.T) {
+ t.Parallel()
+
+ opts := &options{
+ generatePassword: tc.generatePassword,
+ password: tc.password,
+ }
+ if err := opts.enc(tc.files...); err == nil {
+ t.Errorf("enc(%+v) succeeded, want error", opts)
+ }
+ })
+ }
+}
+
+func TestEnc_GeneratePassword(t *testing.T) {
+ t.Parallel()
+
+ fileContent := []byte("test file content")
+ fileName := filepath.Join(t.TempDir(), "file")
+ mustWriteFile(t, fileName, fileContent)
+
+ password := new(strings.Builder)
+ opts := &options{
+ generatePassword: true,
+ passwordOut: password,
+ }
+ if err := opts.enc(fileName); err != nil {
+ t.Fatalf("enc(%+v) failed: %s", opts, err)
+ }
+ pw := password.String()
+ if err := sym.DecryptFile(fileName+".enc", pw, sym.Force(true)); err != nil {
+ t.Fatalf("Failed to decrypt encrypted file with generated password %q: %s", pw, err)
+ }
+ gotFileContents := mustReadFile(t, fileName)
+ if !bytes.Equal(gotFileContents, fileContent) {
+ t.Errorf("encrypt round trip returned incorrect contents %q, want %q", gotFileContents, fileContent)
+ }
+}
+
+func TestEnc_Stdin(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ desc string
+ ascii bool
+ }{{
+ desc: "Binary",
+ ascii: false,
+ }, {
+ desc: "ASCII",
+ ascii: true,
+ }} {
+ t.Run(tc.desc, func(t *testing.T) {
+ t.Parallel()
+
+ const (
+ input = "test input"
+ password = "asdf"
+ )
+ stdout := new(strings.Builder)
+ opts := &options{
+ password: password,
+ asciiOutput: tc.ascii,
+ stdin: strings.NewReader(input),
+ stdout: stdout,
+ }
+ if err := opts.enc(); err != nil {
+ t.Errorf("enc(+%v) failed: %s", opts, err)
+ }
+ got := new(strings.Builder)
+ if err := sym.Decrypt(got, strings.NewReader(stdout.String()), password); err != nil {
+ t.Errorf("Failed to decrypt stdout content: %s", err)
+ }
+ if got, want := got.String(), input; got != want {
+ t.Errorf("Encrypt round-trip to stdout returned incorrect contents: %q, want %q", got, want)
+ }
+ })
+ }
+}
diff --git a/internal/sym/dec.go b/internal/sym/dec.go
index 31c4ed0..086bd44 100644
--- a/internal/sym/dec.go
+++ b/internal/sym/dec.go
@@ -63,7 +63,20 @@ func Decrypt(w io.Writer, r io.Reader, password string) error {
return err
}
-func DecryptFile(fileName string, password string) (err error) {
+type decryptOptions struct {
+ force bool
+}
+
+type DecryptFileOption interface {
+ decryptOpt(*decryptOptions)
+}
+
+func DecryptFile(fileName string, password string, options ...DecryptFileOption) (err error) {
+ opts := new(decryptOptions)
+ for _, o := range options {
+ o.decryptOpt(opts)
+ }
+
var outFileName string
if name, ok := strings.CutSuffix(fileName, ".enc"); ok {
outFileName = name
@@ -77,7 +90,13 @@ func DecryptFile(fileName string, password string) (err error) {
return err
}
defer fIn.Close()
- fOut, err := os.Create(outFileName)
+ fileOpts := os.O_CREATE | os.O_WRONLY
+ if opts.force {
+ fileOpts |= os.O_TRUNC
+ } else {
+ fileOpts |= os.O_EXCL
+ }
+ fOut, err := os.OpenFile(outFileName, fileOpts, 0644)
if err != nil {
return err
}
@@ -88,7 +107,7 @@ func DecryptFile(fileName string, password string) (err error) {
}
}()
if err := Decrypt(fOut, fIn, password); err != nil {
- return err
+ return fmt.Errorf("decrypt %q: %s", fileName, err)
}
return fOut.Close()
}
diff --git a/internal/sym/enc.go b/internal/sym/enc.go
index 33ec7ca..18b7de7 100644
--- a/internal/sym/enc.go
+++ b/internal/sym/enc.go
@@ -3,6 +3,7 @@ package sym
import (
"bufio"
"encoding/base64"
+ "fmt"
"io"
"os"
)
@@ -68,17 +69,47 @@ func EncryptBase64(w io.Writer, r io.Reader, password string) error {
return bufWriter.Flush()
}
-func EncryptFile(fileName string, password string, asciiOutput bool) (err error) {
+type encryptOptions struct {
+ asciiOutput bool
+ force bool
+}
+
+type EncryptFileOption interface {
+ encryptOpt(*encryptOptions)
+}
+
+type encryptFileOptionFunc func(*encryptOptions)
+
+func (f encryptFileOptionFunc) encryptOpt(opts *encryptOptions) { f(opts) }
+
+func WithASCIIOutput(asciiOutput bool) EncryptFileOption {
+ return encryptFileOptionFunc(func(opts *encryptOptions) {
+ opts.asciiOutput = asciiOutput
+ })
+}
+
+func EncryptFile(fileName string, password string, options ...EncryptFileOption) (err error) {
+ opts := new(encryptOptions)
+ for _, o := range options {
+ o.encryptOpt(opts)
+ }
+
f, err := os.Open(fileName)
if err != nil {
return err
}
defer f.Close()
ext := ".enc"
- if asciiOutput {
+ if opts.asciiOutput {
ext = ".enc.txt"
}
- fOut, err := os.Create(fileName + ext)
+ fileOpts := os.O_CREATE | os.O_WRONLY
+ if opts.force {
+ fileOpts |= os.O_TRUNC
+ } else {
+ fileOpts |= os.O_EXCL
+ }
+ fOut, err := os.OpenFile(fileName+ext, fileOpts, 0644)
if err != nil {
return err
}
@@ -88,13 +119,13 @@ func EncryptFile(fileName string, password string, asciiOutput bool) (err error)
os.Remove(fOut.Name())
}
}()
- if asciiOutput {
+ if opts.asciiOutput {
err = EncryptBase64(fOut, f, password)
} else {
err = EncryptBinary(fOut, f, password)
}
if err != nil {
- return err
+ return fmt.Errorf("encrypt %q: %s", fileName, err)
}
return fOut.Close()
}
diff --git a/internal/sym/oae.go b/internal/sym/oae.go
index 0ff9540..72fbf64 100644
--- a/internal/sym/oae.go
+++ b/internal/sym/oae.go
@@ -183,9 +183,6 @@ func (r *decryptingReader) fillBuf() error {
buf := r.buf.AvailableBuffer()[:encryptedSegmentSize]
n, err := io.ReadFull(r.r, buf)
if n == 0 {
- if err == io.ErrUnexpectedEOF {
- return io.EOF
- }
return err
}
buf = buf[:n]
diff --git a/internal/sym/shared_options.go b/internal/sym/shared_options.go
new file mode 100644
index 0000000..74c3210
--- /dev/null
+++ b/internal/sym/shared_options.go
@@ -0,0 +1,20 @@
+package sym
+
+type Option interface {
+ EncryptFileOption
+ DecryptFileOption
+}
+
+type forceOption bool
+
+func (force forceOption) encryptOpt(opts *encryptOptions) {
+ opts.force = bool(force)
+}
+
+func (force forceOption) decryptOpt(opts *decryptOptions) {
+ opts.force = bool(force)
+}
+
+func Force(force bool) Option {
+ return forceOption(force)
+}
diff --git a/internal/sym/sym_test.go b/internal/sym/sym_test.go
index c5f136c..43f29fd 100644
--- a/internal/sym/sym_test.go
+++ b/internal/sym/sym_test.go
@@ -4,13 +4,43 @@ import (
"bytes"
"os"
"path/filepath"
+ "slices"
"testing"
)
+func mustWriteFile(t *testing.T, path string, content []byte) {
+ t.Helper()
+ if err := os.WriteFile(path, content, 0600); err != nil {
+ t.Fatalf("Failed to write test file: %s", err)
+ }
+}
+
+func mustReadFile(t *testing.T, path string) []byte {
+ t.Helper()
+ content, err := os.ReadFile(path)
+ if err != nil {
+ t.Fatalf("Failed to read file: %s", err)
+ }
+ return content
+}
+
+func mustRename(t *testing.T, src, dst string) {
+ t.Helper()
+ if err := os.Rename(src, dst); err != nil {
+ t.Fatalf("Failed to rename: %s", err)
+ }
+}
+
+func mustRemove(t *testing.T, path string) {
+ t.Helper()
+ if err := os.Remove(path); err != nil {
+ t.Fatalf("Failed to remove file: %s", err)
+ }
+}
+
func TestEncryptDecrypt(t *testing.T) {
t.Parallel()
- const password = "karp cache tidal mars fed rajah uses graze pobox flew"
buf := make([]byte, 10*1024*1024)
for i := range buf {
buf[i] = byte(i)
@@ -19,22 +49,22 @@ func TestEncryptDecrypt(t *testing.T) {
desc string
ascii bool
}{{
- desc: "binary",
+ desc: "Binary",
ascii: false,
}, {
- desc: "ascii",
+ desc: "ASCII",
ascii: true,
}} {
t.Run(tc.desc, func(t *testing.T) {
t.Parallel()
fileName := filepath.Join(t.TempDir(), "file")
- if err := os.WriteFile(fileName, buf, 0600); err != nil {
- t.Fatalf("Failed to write test file: %s", err)
- }
- if err := EncryptFile(fileName, password, tc.ascii); err != nil {
+ mustWriteFile(t, fileName, buf)
+ const password = "karp cache tidal mars fed rajah uses graze pobox flew"
+ if err := EncryptFile(fileName, password, WithASCIIOutput(tc.ascii)); err != nil {
t.Fatalf("EncryptFile failed: %s", err)
}
+ mustRemove(t, fileName)
ext := ".enc"
if tc.ascii {
ext = ".enc.txt"
@@ -42,13 +72,149 @@ func TestEncryptDecrypt(t *testing.T) {
if err := DecryptFile(fileName+ext, password); err != nil {
t.Fatalf("DecryptFile failed: %s", err)
}
- gotContents, err := os.ReadFile(fileName)
- if err != nil {
- t.Fatalf("Failed to read file: %s", err)
- }
+ gotContents := mustReadFile(t, fileName)
if !bytes.Equal(gotContents, buf) {
t.Errorf("contents differ")
}
})
}
}
+
+func TestEncryptFile_Force(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ desc string
+ force bool
+ wantErr bool
+ }{{
+ desc: "OutputExists",
+ force: false,
+ wantErr: true,
+ }, {
+ desc: "Force",
+ force: true,
+ wantErr: false,
+ }} {
+ t.Run(tc.desc, func(t *testing.T) {
+ t.Parallel()
+
+ fileName := filepath.Join(t.TempDir(), "file")
+ mustWriteFile(t, fileName, []byte("test file content"))
+ mustWriteFile(t, fileName+".enc", []byte("file already exists"))
+ err := EncryptFile(fileName, "asdf", Force(tc.force))
+ if gotErr := err != nil; gotErr != tc.wantErr {
+ t.Errorf("EncryptFile(force=%t) returned returned error %v when output file exists, want error? %t", tc.force, err, tc.wantErr)
+ }
+ })
+ }
+}
+
+func TestDecryptFile_Force(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ desc string
+ force bool
+ wantErr bool
+ }{{
+ desc: "OutputExists",
+ force: false,
+ wantErr: true,
+ }, {
+ desc: "Force",
+ force: true,
+ wantErr: false,
+ }} {
+ t.Run(tc.desc, func(t *testing.T) {
+ t.Parallel()
+
+ const password = "asdf"
+ fileName := filepath.Join(t.TempDir(), "file")
+ mustWriteFile(t, fileName, []byte("test file content"))
+ if err := EncryptFile(fileName, password); err != nil {
+ t.Fatalf("Failed to encrypt file: %s", err)
+ }
+ err := DecryptFile(fileName+".enc", password, Force(tc.force))
+ if gotErr := err != nil; gotErr != tc.wantErr {
+ t.Errorf("DecryptFile(force=%t) returned returned error %v when output file exists, want error? %t", tc.force, err, tc.wantErr)
+ }
+ })
+ }
+}
+
+func TestDecrypt_BadFileFormat(t *testing.T) {
+ t.Parallel()
+
+ for _, tc := range []struct {
+ desc string
+ fileContent []byte
+ }{{
+ desc: "Empty",
+ fileContent: nil,
+ }, {
+ desc: "Short",
+ fileContent: []byte{0x80},
+ }, {
+ desc: "BadHeader",
+ fileContent: []byte{0x80, 'a', 's', 'd', 'f'},
+ }, {
+ desc: "BadFormat",
+ fileContent: []byte("bad file format"),
+ }, {
+ desc: "BadContent",
+ fileContent: []byte("\x80symasdfasdf"),
+ }, {
+ desc: "BadContentLong",
+ fileContent: slices.Concat([]byte("\x80sym"), bytes.Repeat([]byte("asdf"), 100)),
+ }} {
+ t.Run(tc.desc, func(t *testing.T) {
+ t.Parallel()
+
+ fileName := filepath.Join(t.TempDir(), "file")
+ mustWriteFile(t, fileName, tc.fileContent)
+ err := DecryptFile(fileName, "asdf")
+ if err == nil {
+ t.Errorf("DecryptFile succeeded for incorrect file format, want error")
+ }
+ })
+ }
+}
+
+func TestDecryptFile_WeirdName(t *testing.T) {
+ t.Parallel()
+
+ const password = "asdf"
+ fileContent := []byte("file content")
+ fileName := filepath.Join(t.TempDir(), "file")
+ mustWriteFile(t, fileName, fileContent)
+ if err := EncryptFile(fileName, password); err != nil {
+ t.Fatalf("EncryptFile failed: %s", err)
+ }
+ mustRename(t, fileName+".enc", fileName+".encrypted")
+ if err := DecryptFile(fileName+".encrypted", password); err != nil {
+ t.Fatalf("DecryptFile failed: %s", err)
+ }
+ gotContents := mustReadFile(t, fileName+".encrypted.dec")
+ if !bytes.Equal(gotContents, fileContent) {
+ t.Errorf("contents differ")
+ }
+}
+
+func TestEncryptFile_NotFound(t *testing.T) {
+ t.Parallel()
+
+ err := EncryptFile("my-nonexistent-file.txt", "asdf")
+ if err == nil {
+ t.Fatal("EncryptFile succeeded for nonexistent file, want error")
+ }
+}
+
+func TestDecryptFile_NotFound(t *testing.T) {
+ t.Parallel()
+
+ err := DecryptFile("my-nonexistent-file.txt", "asdf")
+ if err == nil {
+ t.Fatal("DecryptFile succeeded for nonexistent file, want error")
+ }
+}