Official cwtch.im peer and server implementations. https://cwtch.im
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.
 
 
 
 

62 lines
1.5 KiB

  1. package storage
  2. import (
  3. "git.openprivacy.ca/openprivacy/libricochet-go/log"
  4. "io/ioutil"
  5. "os"
  6. "path"
  7. )
  8. // fileStore stores a cwtchPeer in an encrypted file
  9. type fileStore struct {
  10. directory string
  11. filename string
  12. password string
  13. }
  14. // FileStore is a primitive around storing encrypted files
  15. type FileStore interface {
  16. Write([]byte) error
  17. Read() ([]byte, error)
  18. Delete()
  19. ChangePassword(newpass string)
  20. }
  21. // NewFileStore instantiates a fileStore given a filename and a password
  22. func NewFileStore(directory string, filename string, password string) FileStore {
  23. filestore := new(fileStore)
  24. filestore.password = password
  25. filestore.filename = filename
  26. filestore.directory = directory
  27. return filestore
  28. }
  29. // write serializes a cwtchPeer to a file
  30. func (fps *fileStore) Write(data []byte) error {
  31. key, salt, _ := createKey(fps.password)
  32. encryptedbytes, err := encryptFileData(data, key)
  33. if err != nil {
  34. return err
  35. }
  36. // the salt for the derived key is appended to the front of the file
  37. encryptedbytes = append(salt[:], encryptedbytes...)
  38. err = ioutil.WriteFile(path.Join(fps.directory, fps.filename), encryptedbytes, 0600)
  39. return err
  40. }
  41. func (fps *fileStore) Read() ([]byte, error) {
  42. return readEncryptedFile(fps.directory, fps.filename, fps.password)
  43. }
  44. func (fps *fileStore) Delete() {
  45. err := os.Remove(path.Join(fps.directory, fps.filename))
  46. if err != nil {
  47. log.Errorf("Deleting file %v\n", err)
  48. }
  49. }
  50. func (fps *fileStore) ChangePassword(newpass string) {
  51. fps.password = newpass
  52. }