aboutsummaryrefslogtreecommitdiff
path: root/models/keypair.go
diff options
context:
space:
mode:
authorJulio Capote <jcapote@gmail.com>2023-01-04 01:29:50 +0000
committerJulio Capote <jcapote@gmail.com>2023-01-04 01:29:50 +0000
commit54b85678185008a4f6b5778460228788e2dd970d (patch)
treebcce8ac619da7c438518801df4a57be2401f7596 /models/keypair.go
parenta40781358984f651214e53ba000ccc288c56d4f1 (diff)
downloadcommunique-54b85678185008a4f6b5778460228788e2dd970d.tar.gz
start of keypair model and persisting keypairs
Diffstat (limited to 'models/keypair.go')
-rw-r--r--models/keypair.go74
1 files changed, 74 insertions, 0 deletions
diff --git a/models/keypair.go b/models/keypair.go
new file mode 100644
index 0000000..bff60cd
--- /dev/null
+++ b/models/keypair.go
@@ -0,0 +1,74 @@
+package models
+
+import (
+ "bytes"
+ "crypto/rand"
+ "crypto/rsa"
+ "encoding/gob"
+ "fmt"
+ "time"
+
+ "git.capotej.com/capotej/communique/config"
+ "github.com/dgraph-io/badger/v3"
+)
+
+type Keypair struct {
+ Handler config.Handler
+ PrivateKey rsa.PrivateKey
+ CreatedAt time.Time
+}
+
+// used for lookup purposes (count, collect, find)
+func NewKeypair(h config.Handler) *Keypair {
+ aso := &Keypair{Handler: h}
+ return aso
+}
+
+func CreateKeypair(h config.Handler) (*Keypair, error) {
+ key, err := rsa.GenerateKey(rand.Reader, 2048)
+ if err != nil {
+ return nil, fmt.Errorf("could not generate private key for %s: %w", h.Name, err)
+ }
+ aso := &Keypair{
+ PrivateKey: *key,
+ Handler: h,
+ }
+ return aso, nil
+}
+
+func (a *Keypair) Name() string {
+ return "Keypair"
+}
+
+func (a *Keypair) Key() string {
+ keyBase := fmt.Sprintf("keypairs:%s", a.Handler.Name)
+ return keyBase
+}
+
+func (a *Keypair) DedupKey() string {
+ return a.Key()
+}
+
+func (a *Keypair) Keybase() string {
+ return a.Key()
+}
+
+func (a *Keypair) SaveDedup(txn *badger.Txn) error {
+ txn.Discard() // nothing to do here
+ return nil
+}
+
+func (a *Keypair) Save(txn *badger.Txn) error {
+ if a.PrivateKey.D == nil {
+ return fmt.Errorf("private key not set")
+ }
+
+ var network bytes.Buffer
+ enc := gob.NewEncoder(&network)
+ err := enc.Encode(a)
+ if err != nil {
+ return fmt.Errorf("could not encode keypair: %w", err)
+ }
+ e := badger.NewEntry([]byte(a.Key()), network.Bytes())
+ return txn.SetEntry(e)
+}