-
Notifications
You must be signed in to change notification settings - Fork 4
/
ring.go
51 lines (43 loc) · 1.28 KB
/
ring.go
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
package macdaddy
import "encoding/binary"
// Ring represents a MAC ring capable of opening
// messages encrypted by MACs from various epochs.
//
// The goal of a ring is to allow keys to be rotated
// while retaining backwards compatibility for keys
// used in previous epochs.
type Ring struct {
primary *MAC
registry map[uint32]*MAC
}
// NewRing creates a suite with a primary MAC,
// which is used for all encoding operations.
func NewRing(primary *MAC) *Ring {
return &Ring{
primary: primary,
registry: map[uint32]*MAC{primary.Epoch(): primary},
}
}
// Register registers an additional MAC. Please note that
// registration is based on the epoch. MACs with clashing epoch values
// may override other, previously registered ones.
func (r *Ring) Register(m *MAC) {
r.registry[m.Epoch()] = m
}
// Encrypt uses the primary MAC to encrypt a message
func (r *Ring) Encrypt(dst, src []byte) []byte {
return r.primary.Encrypt(dst, src)
}
// Decrypt decrypts a message by using the correct
// MAC from the determined message epoch
func (r *Ring) Decrypt(dst, src []byte) ([]byte, error) {
if len(src) < epochSize {
return dst, ErrBadToken
}
epoch := binary.LittleEndian.Uint32(src)
mac, ok := r.registry[epoch]
if !ok {
return dst, ErrUnknownEpoch
}
return mac.Decrypt(dst, src)
}