-
Notifications
You must be signed in to change notification settings - Fork 51
/
main.go
88 lines (76 loc) · 1.7 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package main
import (
"crypto/rand"
"errors"
"fmt"
"log"
"os"
"github.com/edgelesssys/ego/ecrypto"
"github.com/edgelesssys/estore"
)
const keyFile = "/db/sealed_key"
func main() {
// Open existing DB or create a new one
var db *estore.DB
sealedKey, err := os.ReadFile(keyFile)
if err == nil {
fmt.Println("Found existing DB")
db, err = openExistingDB(sealedKey)
} else if errors.Is(err, os.ErrNotExist) {
fmt.Println("Creating new DB")
db, err = createNewDB()
}
if err != nil {
log.Fatal(err)
}
defer db.Close()
// Get the value of the key
value, closer, err := db.Get([]byte("hello"))
if err != nil {
log.Fatal(err)
}
defer closer.Close()
fmt.Printf("hello=%s\n", value)
}
func createNewDB() (*estore.DB, error) {
// Generate an encryption key
encryptionKey := make([]byte, 16)
_, err := rand.Read(encryptionKey)
if err != nil {
return nil, err
}
// Seal the encryption key
sealedKey, err := ecrypto.SealWithUniqueKey(encryptionKey, nil)
if err != nil {
return nil, err
}
if err := os.Mkdir("/db", 0o700); err != nil {
return nil, err
}
if err := os.WriteFile(keyFile, sealedKey, 0o600); err != nil {
return nil, err
}
// Create an encrypted store
opts := &estore.Options{
EncryptionKey: encryptionKey,
}
db, err := estore.Open("/db", opts)
if err != nil {
return nil, err
}
// Set a key-value pair
if err := db.Set([]byte("hello"), []byte("world"), nil); err != nil {
return nil, err
}
return db, nil
}
func openExistingDB(sealedKey []byte) (*estore.DB, error) {
encryptionKey, err := ecrypto.Unseal(sealedKey, nil)
if err != nil {
return nil, err
}
opts := &estore.Options{
EncryptionKey: encryptionKey,
}
return estore.Open("/db", opts)
}