dec.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. package main
  2. import (
  3. "encoding/hex"
  4. "fmt"
  5. "io"
  6. "os"
  7. "strings"
  8. "github.com/cheggaaa/pb"
  9. "github.com/codegangsta/cli"
  10. "github.com/cryptix/go/crypt"
  11. "github.com/cryptix/go/logging"
  12. )
  13. func runDec(c *cli.Context) {
  14. inputFname := c.Args().First()
  15. // open the input
  16. input, err := os.Open(inputFname)
  17. logging.CheckFatal(err)
  18. defer input.Close()
  19. inputStat, err := input.Stat()
  20. logging.CheckFatal(err)
  21. ks := c.String("key")
  22. if ks == "" {
  23. logging.CheckFatal(fmt.Errorf("keyfile can't be empty"))
  24. }
  25. key, err := hex.DecodeString(ks)
  26. logging.CheckFatal(err)
  27. dec, err := crypt.NewCrypter(key)
  28. logging.CheckFatal(err)
  29. // prepare the output file
  30. outFname := c.GlobalString("out")
  31. if outFname == "" {
  32. // if input fname ends with .enc
  33. if strings.HasSuffix(inputFname, ".enc") {
  34. // strip it off
  35. outFname = strings.TrimSuffix(inputFname, ".enc")
  36. } else {
  37. // append .clear
  38. outFname = inputFname + ".clear"
  39. }
  40. }
  41. out, err := os.Create(outFname)
  42. logging.CheckFatal(err)
  43. defer out.Close()
  44. // create the decryption pipe
  45. decWriter, err := dec.MakePipe(out)
  46. logging.CheckFatal(err)
  47. // create the progress bar
  48. pbar := pb.New64(inputStat.Size()).SetUnits(pb.U_BYTES)
  49. pbar.ShowSpeed = true
  50. pbar.Start()
  51. // write to both to track progress
  52. multi := io.MultiWriter(decWriter, pbar)
  53. // copy the cipherText through the decWriter into the clear
  54. _, err = io.Copy(multi, input)
  55. logging.CheckFatal(err)
  56. pbar.FinishPrint("Decryption done")
  57. }