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) }