aboutsummaryrefslogtreecommitdiff
path: root/models/keypair.go
blob: bff60cd675914b42413423108ec1787f081de501 (plain)
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
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)
}