aboutsummaryrefslogtreecommitdiff
path: root/account.go
blob: c0f76a1b1e492352c578782c37f33e1d6604ccd6 (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
75
76
package acme

import (
	"crypto/rand"
	"crypto/rsa"
	"fmt"
	"net/mail"

	"github.com/square/go-jose"
)

// KeySize is a default RSA key size
const KeySize = 2048

// Account ...
type Account struct {
	Contact []Contact       `json:"contact"`
	PrivKey *rsa.PrivateKey `json:"key"`
	signer  jose.Signer
	nonce   chan string
}

func newMail(email string) (Mail, error) {
	m, err := mail.ParseAddress(email)
	if err != nil {
		return "", err
	}
	return Mail(m.Address), nil
}

// NewAccount ...
func NewAccount(email string, bits int) (*Account, error) {
	m, err := newMail(email)
	if err != nil {
		return nil, err
	}
	key, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return nil, err
	}
	return &Account{
		Contact: []Contact{m},
		PrivKey: key,
	}, nil
}

func LoadAccount(email string) (*Account, error) {
	return nil, nil
}

// Signer describes a signing interface
type Signer interface {
	Sign([]byte, jose.NonceSource) ([]byte, error)
}

func (a *Account) Sign(msg []byte, n jose.NonceSource) ([]byte, error) {
	if a.signer == nil {
		var err error
		a.signer, err = jose.NewSigner(jose.RS256, a.PrivKey)
		if err != nil {
			return nil, err
		}
		a.signer.SetNonceSource(n)
	}
	obj, err := a.signer.Sign(msg)
	return []byte(obj.FullSerialize()), err
}

func (a *Account) ParseSigned(msg []byte) ([]byte, error) {
	fmt.Println("MSG", string(msg))
	obj, err := jose.ParseSigned(string(msg))
	if err != nil {
		return nil, err
	}
	return obj.Verify(&a.PrivKey.PublicKey)
}