aboutsummaryrefslogtreecommitdiff
path: root/account.go
blob: 6a4e123eba451e7ee92db7620be3ae83f56c8e72 (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
77
78
79
80
81
82
83
84
85
86
87
88
package acme

import (
	"crypto/rand"
	"crypto/rsa"
	"encoding/json"
	"io"
	"io/ioutil"
	"net/mail"
	"strings"

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

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

// Account ...
type Account struct {
	Contact Contacts        `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
	}
	mm := Mail(m.Address)
	return mm, 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: Contacts{m},
		PrivKey: key,
	}, nil
}

func LoadAccount(fname string) (*Account, error) {
	body, err := ioutil.ReadFile(fname)
	if err != nil {
		return nil, err
	}
	a := new(Account)
	err = json.Unmarshal(body, a)
	return a, err
}

func (a Account) SaveAccount(fname string) error {
	body, err := json.MarshalIndent(a, "", "\t")
	if err != nil {
		return err
	}
	return ioutil.WriteFile(fname, body, 0600)
}

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

func (a *Account) Sign(msg []byte, n jose.NonceSource) (io.Reader, 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)
	if err != nil {
		return nil, err
	}
	return strings.NewReader(obj.FullSerialize()), nil
}