aboutsummaryrefslogtreecommitdiffstats
path: root/enc
diff options
context:
space:
mode:
Diffstat (limited to 'enc')
-rw-r--r--enc/enc.go57
-rw-r--r--enc/enc_test.go147
2 files changed, 186 insertions, 18 deletions
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)
+ }
+ })
+ }
+}