You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

96 lines
1.6 KiB

  1. package Encryption
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "errors"
  6. "os"
  7. "os/exec"
  8. "io/ioutil"
  9. "io"
  10. )
  11. func EditEncryptedFile(password string, FilePath string) (error) {
  12. var (
  13. editor string
  14. tmpFilePath string
  15. ciphertext []byte
  16. plaintext []byte
  17. tmpFile *os.File
  18. encryptedFile *os.File
  19. cmd *exec.Cmd
  20. e error
  21. )
  22. editor = os.Getenv("EDITOR")
  23. if editor == "" {
  24. return errors.New("EDITOR variable cannot be blank")
  25. }
  26. tmpFilePath = os.Getenv("TMPDIR")
  27. if tmpFilePath == "" {
  28. tmpFilePath = "/tmp"
  29. }
  30. ciphertext, e = ioutil.ReadFile(FilePath)
  31. if e != nil {
  32. return e
  33. }
  34. if len(ciphertext) < aes.BlockSize {
  35. return errors.New("ciphertext too short")
  36. }
  37. plaintext, e = DecryptData(password, ciphertext)
  38. if e != nil {
  39. return e
  40. }
  41. tmpFile, e = ioutil.TempFile(tmpFilePath, "")
  42. if e != nil {
  43. return e
  44. }
  45. _, e = io.Copy(tmpFile, bytes.NewReader(plaintext))
  46. if e != nil {
  47. return e
  48. }
  49. e = tmpFile.Close()
  50. if e != nil {
  51. return e
  52. }
  53. cmd = exec.Command(editor, tmpFile.Name())
  54. cmd.Stdout = os.Stdout
  55. cmd.Stdin = os.Stdin
  56. cmd.Stderr = os.Stderr
  57. e = cmd.Run()
  58. if (e != nil) {
  59. return e
  60. }
  61. plaintext, e = ioutil.ReadFile(tmpFile.Name())
  62. if e != nil {
  63. return e
  64. }
  65. ciphertext, e = EncryptData(password, plaintext)
  66. if e != nil {
  67. return e
  68. }
  69. // open output file
  70. encryptedFile, e = os.OpenFile(FilePath, os.O_RDWR, 0666)
  71. if e != nil {
  72. return e
  73. }
  74. defer func() {
  75. encryptedFile.Close()
  76. SecureDelete(tmpFile.Name())
  77. }()
  78. _, e = io.Copy(encryptedFile, bytes.NewReader(ciphertext))
  79. if e != nil {
  80. return e
  81. }
  82. return nil
  83. }