aboutsummaryrefslogtreecommitdiff
path: root/models/keypair.go
diff options
context:
space:
mode:
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)
+}