gocrypt/main.go
2019-06-25 20:57:03 +02:00

84 lines
1.6 KiB
Go

// Copyright (C) 2019 Marius Schellenberger
package main
import (
"flag"
"fmt"
"git.giftfish.de/ston1th/gocrypt/pkg/crypto"
"git.giftfish.de/ston1th/godrop/v2"
"io"
"io/ioutil"
"os"
)
var (
encMode bool
decMode bool
input string
output string
)
func fatal(err error) {
if err != nil {
fatals(err.Error())
}
}
func fatals(s string) {
stderr("error: " + s + "\n")
os.Exit(1)
}
func stderr(s string) {
fmt.Fprintf(os.Stderr, s)
}
func init() {
fatal(godrop.PledgePromises("stdio rpath wpath cpath tty unveil"))
fatal(godrop.Unveil("/", ""))
flag.BoolVar(&encMode, "enc", false, "encryption mode - password is read from stdin")
flag.BoolVar(&decMode, "dec", false, "decryption mode - password is read from stdin")
flag.StringVar(&input, "f", "", "input file")
flag.StringVar(&output, "o", "-", "output file (default stdout)")
flag.Parse()
}
func main() {
var (
in []byte
out io.WriteCloser
err error
)
if input == "" {
fatals("input file is empty")
} else {
fatal(godrop.Unveil(input, "r"))
in, err = ioutil.ReadFile(input)
fatal(err)
}
if output == "" {
fatals("output file is empty")
} else if output == "-" {
out = os.Stdout
} else {
fatal(godrop.Unveil(output, "wc"))
out, err = os.OpenFile(output, os.O_WRONLY|os.O_CREATE, 0640)
fatal(err)
}
fatal(godrop.PledgePromises("stdio tty"))
stderr("Enter password: ")
pass, err := crypto.Password()
stderr("\n")
fatal(err)
fatal(godrop.PledgePromises("stdio"))
switch {
case encMode == true:
err = crypto.Encrypt(pass, in, out)
fatal(err)
case decMode == true:
err = crypto.Decrypt(pass, in, out)
fatal(err)
}
fatal(out.Close())
}