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

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

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

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

func NewAccount(email string, bits int) (Account, error) {
	m, err := mail.ParseAddress(email)
	if err != nil {
		return Account{}, err
	}
	key, err := rsa.GenerateKey(rand.Reader, bits)
	if err != nil {
		return Account{}, err
	}
	return Account{
		Contact: []string{"mailto:" + m.Address},
		PrivKey: key,
	}, nil
}

func (a *Account) Sign(msg []byte) ([]byte, error) {
	if a.Signer == nil {
		signer, err := jose.NewSigner(jose.RS256, a.PrivKey)
		if err != nil {
			return nil, err
		}
		signer.SetNonceSource(nonces)
		a.Signer = signer
	}
	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)
}