-
Notifications
You must be signed in to change notification settings - Fork 6
/
encoding.go
215 lines (181 loc) · 5.08 KB
/
encoding.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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
package stream
import (
"bytes"
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
)
var (
// ErrMaxNonce indicates the max allowed nonce is reach. If this happends, a
// new stream with different key should be created.
ErrMaxNonce = errors.New("max nonce reached")
// ErrWrongNonceInitiator indicates a nonce with the wrong party is received,
// i.e. initiator receives a nonce from initiator, or responder receives a
// nonce from responder. It is either a configuration error (e.g. both party
// set initiator to the same value), or a middle man is performing reflection
// attack.
ErrWrongNonceInitiator = errors.New("wrong nonce direction")
// ErrWrongNonceSequential indicates a nonce with the wrong value is received.
// It is either a configuration error (e.g. one side set sequentialNonce to
// true, the other side set to false), or a middle man is performing replay,
// re-order or packet drop attack.
ErrWrongNonceSequential = errors.New("wrong nonce value")
)
// Encoder provides encode function of a slice data.
type Encoder struct {
cipher Cipher
initiator bool
sequentialNonce bool
nextNonce []byte
maxNonce []byte
}
// NewEncoder creates a Encoder with given cipher and config.
func NewEncoder(cipher Cipher, initiator, sequentialNonce bool) (*Encoder, error) {
encoder := &Encoder{
cipher: cipher,
initiator: initiator,
sequentialNonce: sequentialNonce,
nextNonce: initNonce(cipher.NonceSize(), initiator),
maxNonce: maxNonce(cipher.NonceSize(), initiator),
}
return encoder, nil
}
// Encode encodes a plaintext to nonce + ciphertext. When sequential nonce is
// true, Encode is not thread safe and should not be called concurrently.
func (e *Encoder) Encode(ciphertext, plaintext []byte) ([]byte, error) {
nonceSize := e.cipher.NonceSize()
if e.sequentialNonce {
if bytes.Compare(e.nextNonce, e.maxNonce) >= 0 {
return nil, ErrMaxNonce
}
copy(ciphertext[:nonceSize], e.nextNonce)
incrementNonce(e.nextNonce)
} else {
_, err := rand.Read(ciphertext[:nonceSize])
if err != nil {
return nil, err
}
if e.initiator {
ciphertext[0] &= 127
} else {
ciphertext[0] |= 128
}
}
encrypted, err := e.cipher.Encrypt(ciphertext[nonceSize:], plaintext, ciphertext[:nonceSize])
if err != nil {
return nil, err
}
return ciphertext[:nonceSize+len(encrypted)], nil
}
// Decoder provides decode function of a slice data.
type Decoder struct {
cipher Cipher
initiator bool
sequentialNonce bool
disableNonceVerification bool
nextNonce []byte
}
// NewDecoder creates a Decoder with given cipher and config.
func NewDecoder(cipher Cipher, initiator, sequentialNonce, disableNonceVerification bool) (*Decoder, error) {
decoder := &Decoder{
cipher: cipher,
initiator: initiator,
sequentialNonce: sequentialNonce,
disableNonceVerification: disableNonceVerification,
nextNonce: initNonce(cipher.NonceSize(), !initiator),
}
return decoder, nil
}
// Decode decodes a nonce + ciphertext to plaintext. When sequential nonce is
// true, Decode is not thread safe and should not be called concurrently.
func (d *Decoder) Decode(plaintext, ciphertext []byte) ([]byte, error) {
nonceSize := d.cipher.NonceSize()
if len(ciphertext) <= nonceSize {
return nil, fmt.Errorf("invalid ciphertext size %d", len(ciphertext))
}
nonce := ciphertext[:nonceSize]
if !d.disableNonceVerification {
if d.initiator {
if nonce[0]>>7 != 1 {
return nil, ErrWrongNonceInitiator
}
} else {
if nonce[0]>>7 != 0 {
return nil, ErrWrongNonceInitiator
}
}
if d.sequentialNonce {
if !bytes.Equal(nonce, d.nextNonce) {
return nil, ErrWrongNonceSequential
}
}
}
plaintext, err := d.cipher.Decrypt(plaintext, ciphertext[nonceSize:], nonce)
if err != nil {
return nil, err
}
if d.sequentialNonce {
incrementNonce(d.nextNonce)
}
return plaintext, nil
}
func initNonce(nonceSize int, initiator bool) []byte {
b := make([]byte, nonceSize)
if !initiator {
b[0] |= 128
}
return b
}
func maxNonce(nonceSize int, initiator bool) []byte {
b := make([]byte, nonceSize)
for i := 0; i < len(b); i++ {
b[i] = 255
}
if initiator {
b[0] &= 127
}
return b
}
func incrementNonce(b []byte) {
for i := len(b) - 1; i >= 0; i-- {
b[i]++
if b[i] > 0 {
break
}
}
}
func readVarBytes(reader io.Reader, b, lenBuf []byte) (int, error) {
if len(lenBuf) < 4 {
lenBuf = make([]byte, 4)
}
_, err := io.ReadFull(reader, lenBuf)
if err != nil {
return 0, err
}
n := int(binary.LittleEndian.Uint32(lenBuf))
if len(b) < n {
return 0, io.ErrShortBuffer
}
return io.ReadFull(reader, b[:n])
}
func writeVarBytes(writer io.Writer, b, lenBuf []byte) error {
if len(b) > math.MaxInt32 {
return errors.New("data size too large")
}
if len(lenBuf) < 4 {
lenBuf = make([]byte, 4)
}
binary.LittleEndian.PutUint32(lenBuf, uint32(len(b)))
_, err := writer.Write(lenBuf)
if err != nil {
return err
}
_, err = writer.Write(b)
if err != nil {
return err
}
return nil
}