2019-01-14 20:09:25 +00:00
|
|
|
package storage
|
|
|
|
|
|
|
|
import (
|
2019-12-10 23:45:43 +00:00
|
|
|
"git.openprivacy.ca/openprivacy/libricochet-go/log"
|
2019-12-12 20:21:14 +00:00
|
|
|
"io/ioutil"
|
2019-12-10 23:45:43 +00:00
|
|
|
"os"
|
2019-01-29 20:56:59 +00:00
|
|
|
"path"
|
2019-01-14 20:09:25 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// fileStore stores a cwtchPeer in an encrypted file
|
|
|
|
type fileStore struct {
|
2019-01-29 20:56:59 +00:00
|
|
|
directory string
|
|
|
|
filename string
|
|
|
|
password string
|
2019-01-14 20:09:25 +00:00
|
|
|
}
|
|
|
|
|
2019-01-21 20:11:40 +00:00
|
|
|
// FileStore is a primitive around storing encrypted files
|
2019-01-14 20:09:25 +00:00
|
|
|
type FileStore interface {
|
2019-12-12 20:21:14 +00:00
|
|
|
Write([]byte) error
|
|
|
|
Read() ([]byte, error)
|
2019-12-10 23:45:43 +00:00
|
|
|
Delete()
|
2019-12-12 20:21:14 +00:00
|
|
|
ChangePassword(newpass string)
|
2019-01-14 20:09:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewFileStore instantiates a fileStore given a filename and a password
|
2019-01-29 20:56:59 +00:00
|
|
|
func NewFileStore(directory string, filename string, password string) FileStore {
|
2019-01-14 20:09:25 +00:00
|
|
|
filestore := new(fileStore)
|
|
|
|
filestore.password = password
|
|
|
|
filestore.filename = filename
|
2019-01-29 20:56:59 +00:00
|
|
|
filestore.directory = directory
|
2019-01-14 20:09:25 +00:00
|
|
|
return filestore
|
|
|
|
}
|
|
|
|
|
2019-12-12 20:21:14 +00:00
|
|
|
// write serializes a cwtchPeer to a file
|
|
|
|
func (fps *fileStore) Write(data []byte) error {
|
2019-01-14 20:09:25 +00:00
|
|
|
key, salt, _ := createKey(fps.password)
|
|
|
|
encryptedbytes, err := encryptFileData(data, key)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// the salt for the derived key is appended to the front of the file
|
|
|
|
encryptedbytes = append(salt[:], encryptedbytes...)
|
2019-01-29 20:56:59 +00:00
|
|
|
err = ioutil.WriteFile(path.Join(fps.directory, fps.filename), encryptedbytes, 0600)
|
2019-01-14 20:09:25 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2019-12-12 20:21:14 +00:00
|
|
|
func (fps *fileStore) Read() ([]byte, error) {
|
2019-01-29 20:56:59 +00:00
|
|
|
return readEncryptedFile(fps.directory, fps.filename, fps.password)
|
2019-01-14 20:09:25 +00:00
|
|
|
}
|
2019-12-10 23:45:43 +00:00
|
|
|
|
|
|
|
func (fps *fileStore) Delete() {
|
|
|
|
err := os.Remove(path.Join(fps.directory, fps.filename))
|
|
|
|
if err != nil {
|
|
|
|
log.Errorf("Deleting file %v\n", err)
|
|
|
|
}
|
2019-12-12 20:21:14 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (fps *fileStore) ChangePassword(newpass string) {
|
|
|
|
fps.password = newpass
|
|
|
|
}
|