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.

101 lines
2.0 KiB

  1. package Encryption
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "errors"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. )
  11. func DecryptData(password string, ciphertext []byte) ([]byte, error) {
  12. var (
  13. hashedKey []byte
  14. iv []byte
  15. encKey []byte
  16. block cipher.Block
  17. stream cipher.Stream
  18. e error
  19. )
  20. hashedKey = CreateHash(password)
  21. if len(ciphertext) == 0 {
  22. return []byte{}, errors.New("Invalid length")
  23. }
  24. iv = ciphertext[:aes.BlockSize]
  25. encKey = ciphertext[:32+aes.BlockSize][aes.BlockSize:]
  26. ciphertext = ciphertext[aes.BlockSize+32:]
  27. block, e = CreateKey(hashedKey)
  28. if e != nil {
  29. return []byte{}, e
  30. }
  31. stream = cipher.NewCFBDecrypter(block, iv)
  32. stream.XORKeyStream(encKey, encKey)
  33. for i := range encKey {
  34. if encKey[i] != hashedKey[i] {
  35. return []byte{}, errors.New("Incorrect Password")
  36. }
  37. }
  38. stream.XORKeyStream(ciphertext, ciphertext)
  39. return ciphertext, nil
  40. }
  41. func DecryptFile(password string, FilePath string) error {
  42. var (
  43. OldFilePath string
  44. ciphertext []byte
  45. plaintext []byte
  46. plaintextFile *os.File
  47. e error
  48. )
  49. OldFilePath = FilePath[:(len(FilePath) - 4)]
  50. ciphertext, e = ioutil.ReadFile(FilePath)
  51. if e != nil {
  52. return e
  53. }
  54. if len(ciphertext) < aes.BlockSize {
  55. return errors.New("ciphertext too short")
  56. }
  57. plaintext, e = DecryptData(password, ciphertext)
  58. if e != nil {
  59. return e
  60. }
  61. plaintextFile, e = os.Create(OldFilePath)
  62. if e != nil {
  63. return e
  64. }
  65. _, e = io.Copy(plaintextFile, bytes.NewReader(plaintext))
  66. if e != nil {
  67. return e
  68. }
  69. os.Remove(FilePath)
  70. return nil
  71. }
  72. func DecryptAndReadFile(password string, FilePath string) (string, error) {
  73. var (
  74. ciphertext []byte
  75. plaintext []byte
  76. e error
  77. )
  78. ciphertext, e = ioutil.ReadFile(FilePath)
  79. if e != nil {
  80. return "", e
  81. }
  82. if len(ciphertext) < aes.BlockSize {
  83. return "", errors.New("ciphertext too short")
  84. }
  85. plaintext, e = DecryptData(password, ciphertext)
  86. if e != nil {
  87. return "", e
  88. }
  89. return string(plaintext), nil
  90. }