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.

92 lines
1.5 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 = "/tmp/klsadjhflk"
  27. ciphertext, e = ioutil.ReadFile(FilePath)
  28. if e != nil {
  29. return e
  30. }
  31. if len(ciphertext) < aes.BlockSize {
  32. return errors.New("ciphertext too short")
  33. }
  34. plaintext, e = DecryptData(password, ciphertext)
  35. if e != nil {
  36. return e
  37. }
  38. tmpFile, e = os.Create(tmpFilePath)
  39. if e != nil {
  40. return e
  41. }
  42. _, e = io.Copy(tmpFile, bytes.NewReader(plaintext))
  43. if e != nil {
  44. return e
  45. }
  46. e = tmpFile.Close()
  47. if e != nil {
  48. return e
  49. }
  50. cmd = exec.Command(editor, tmpFilePath)
  51. cmd.Stdout = os.Stdout
  52. cmd.Stdin = os.Stdin
  53. cmd.Stderr = os.Stderr
  54. e = cmd.Run()
  55. if (e != nil) {
  56. return e
  57. }
  58. plaintext, e = ioutil.ReadFile(tmpFilePath)
  59. if e != nil {
  60. return e
  61. }
  62. ciphertext, e = EncryptData(password, plaintext)
  63. if e != nil {
  64. return e
  65. }
  66. // open output file
  67. encryptedFile, e = os.OpenFile(FilePath, os.O_RDWR, 0666)
  68. if e != nil {
  69. return e
  70. }
  71. defer func() {
  72. encryptedFile.Close()
  73. SecureDelete(tmpFilePath)
  74. }()
  75. _, e = io.Copy(encryptedFile, bytes.NewReader(ciphertext))
  76. if e != nil {
  77. return e
  78. }
  79. return nil
  80. }