47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
package v0
|
|
|
|
import (
|
|
"io/ioutil"
|
|
"path"
|
|
)
|
|
|
|
// fileStore stores a cwtchPeer in an encrypted file
|
|
type fileStore struct {
|
|
directory string
|
|
filename string
|
|
password string
|
|
}
|
|
|
|
// FileStore is a primitive around storing encrypted files
|
|
type FileStore interface {
|
|
Read() ([]byte, error)
|
|
Write(data []byte) error
|
|
}
|
|
|
|
// NewFileStore instantiates a fileStore given a filename and a password
|
|
func NewFileStore(directory string, filename string, password string) FileStore {
|
|
filestore := new(fileStore)
|
|
filestore.password = password
|
|
filestore.filename = filename
|
|
filestore.directory = directory
|
|
return filestore
|
|
}
|
|
|
|
func (fps *fileStore) Read() ([]byte, error) {
|
|
return readEncryptedFile(fps.directory, fps.filename, fps.password)
|
|
}
|
|
|
|
// write serializes a cwtchPeer to a file
|
|
func (fps *fileStore) Write(data []byte) error {
|
|
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...)
|
|
err = ioutil.WriteFile(path.Join(fps.directory, fps.filename), encryptedbytes, 0600)
|
|
return err
|
|
}
|