github.com/ncruces/go-sqlite3@v0.15.1-0.20240520133447-53eef1510ff0/vfs/adiantum/api.go (about)

     1  // Package adiantum wraps an SQLite VFS to offer encryption at rest.
     2  //
     3  // The "adiantum" [vfs.VFS] wraps the default VFS using the
     4  // Adiantum tweakable, length-preserving encryption.
     5  //
     6  // Importing package adiantum registers that VFS:
     7  //
     8  //	import _ "github.com/ncruces/go-sqlite3/vfs/adiantum"
     9  //
    10  // To open an encrypted database you need to provide key material.
    11  //
    12  // The simplest way to do that is to specify the key through an [URI] parameter:
    13  //
    14  //   - key: key material in binary (32 bytes)
    15  //   - hexkey: key material in hex (64 hex digits)
    16  //   - textkey: key material in text (any length)
    17  //
    18  // However, this makes your key easily accessible to other parts of
    19  // your application (e.g. through [vfs.Filename.URIParameters]).
    20  //
    21  // To avoid this, invoke any of the following PRAGMAs
    22  // immediately after opening a connection:
    23  //
    24  //	PRAGMA key='D41d8cD98f00b204e9800998eCf8427e';
    25  //	PRAGMA hexkey='e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855';
    26  //	PRAGMA textkey='your-secret-key';
    27  //
    28  // For an ATTACH-ed database, you must specify the schema name:
    29  //
    30  //	ATTACH DATABASE 'demo.db' AS demo;
    31  //	PRAGMA demo.textkey='your-secret-key';
    32  //
    33  // [URI]: https://sqlite.org/uri.html
    34  package adiantum
    35  
    36  import (
    37  	"github.com/ncruces/go-sqlite3/vfs"
    38  	"lukechampine.com/adiantum/hbsh"
    39  )
    40  
    41  func init() {
    42  	Register("adiantum", vfs.Find(""), nil)
    43  }
    44  
    45  // Register registers an encrypting VFS, wrapping a base VFS,
    46  // and possibly using a custom HBSH cipher construction.
    47  // To use the default Adiantum construction, set cipher to nil.
    48  func Register(name string, base vfs.VFS, cipher HBSHCreator) {
    49  	if cipher == nil {
    50  		cipher = adiantumCreator{}
    51  	}
    52  	vfs.Register(name, &hbshVFS{
    53  		VFS:  base,
    54  		hbsh: cipher,
    55  	})
    56  }
    57  
    58  // HBSHCreator creates an [hbsh.HBSH] cipher
    59  // given key material.
    60  type HBSHCreator interface {
    61  	// KDF derives an HBSH key from a secret.
    62  	// If no secret is given, a random key is generated.
    63  	KDF(secret string) (key []byte)
    64  
    65  	// HBSH creates an HBSH cipher given a key.
    66  	// If key is not appropriate, nil is returned.
    67  	HBSH(key []byte) *hbsh.HBSH
    68  }