github.com/keybase/client/go@v0.0.0-20241007131713-f10651d043c8/encrypteddb/file.go (about)

     1  package encrypteddb
     2  
     3  import (
     4  	"os"
     5  
     6  	"github.com/keybase/client/go/libkb"
     7  	"golang.org/x/net/context"
     8  )
     9  
    10  type EncryptedFile struct {
    11  	libkb.Contextified
    12  
    13  	getSecretBoxKey KeyFn
    14  	path            string
    15  }
    16  
    17  func NewFile(g *libkb.GlobalContext, path string, getSecretBoxKey KeyFn) *EncryptedFile {
    18  	return &EncryptedFile{
    19  		Contextified:    libkb.NewContextified(g),
    20  		path:            path,
    21  		getSecretBoxKey: getSecretBoxKey,
    22  	}
    23  }
    24  
    25  func (f *EncryptedFile) Get(ctx context.Context, res interface{}) error {
    26  	enc, err := os.ReadFile(f.path)
    27  	if err != nil {
    28  		return err
    29  	}
    30  	if err = DecodeBox(ctx, enc, f.getSecretBoxKey, res); err != nil {
    31  		return err
    32  	}
    33  	return nil
    34  }
    35  
    36  func (f *EncryptedFile) Put(ctx context.Context, data interface{}) error {
    37  	b, err := EncodeBox(ctx, data, f.getSecretBoxKey)
    38  	if err != nil {
    39  		return err
    40  	}
    41  	return os.WriteFile(f.path, b, 0644)
    42  }
    43  
    44  func (f *EncryptedFile) Remove(ctx context.Context) error {
    45  	return os.Remove(f.path)
    46  }