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.

71 lines
1.4 KiB

  1. package Encryption
  2. import (
  3. "bytes"
  4. "crypto/aes"
  5. "crypto/cipher"
  6. "crypto/rand"
  7. "io"
  8. "io/ioutil"
  9. "os"
  10. )
  11. func EncryptData(password string, data []byte) ([]byte, error) {
  12. var (
  13. hashedKey []byte
  14. ciphertext []byte
  15. iv []byte
  16. block cipher.Block
  17. stream cipher.Stream
  18. e error
  19. )
  20. hashedKey = CreateHash(password)
  21. ciphertext = make([]byte, aes.BlockSize+len(hashedKey)+len(data))
  22. iv = ciphertext[:aes.BlockSize]
  23. if _, e = io.ReadFull(rand.Reader, iv); e != nil {
  24. return []byte{}, e
  25. }
  26. block, e = CreateKey(hashedKey)
  27. if e != nil {
  28. return []byte{}, e
  29. }
  30. stream = cipher.NewCFBEncrypter(block, iv)
  31. stream.XORKeyStream(ciphertext[aes.BlockSize:], []byte(hashedKey))
  32. stream.XORKeyStream(ciphertext[aes.BlockSize+len([]byte(hashedKey)):], data)
  33. return ciphertext, nil
  34. }
  35. func EncryptFile(password string, FilePath string) error {
  36. var (
  37. plaintext []byte
  38. ciphertext []byte
  39. encryptedFile *os.File
  40. e error
  41. )
  42. plaintext, e = ioutil.ReadFile(FilePath)
  43. if e != nil {
  44. return e
  45. }
  46. ciphertext, e = EncryptData(password, plaintext)
  47. if e != nil {
  48. return e
  49. }
  50. // open output file
  51. encryptedFile, e = os.Create(FilePath + ".enc")
  52. if e != nil {
  53. return e
  54. }
  55. defer func() {
  56. encryptedFile.Close()
  57. SecureDelete(FilePath)
  58. }()
  59. _, e = io.Copy(encryptedFile, bytes.NewReader(ciphertext))
  60. if e != nil {
  61. return e
  62. }
  63. return nil
  64. }