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.

95 lines
1.6 KiB

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