-
Notifications
You must be signed in to change notification settings - Fork 211
/
aead.go
50 lines (38 loc) · 973 Bytes
/
aead.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
package noise
import (
"crypto/cipher"
"io"
"math/rand"
)
func extendFront(buf []byte, n int) []byte {
if len(buf) < n {
clone := make([]byte, n+len(buf))
copy(clone[n:], buf)
return clone
}
return append(buf[:n], buf...)
}
func extendBack(buf []byte, n int) []byte {
n += len(buf)
if nn := n - cap(buf); nn > 0 {
buf = append(buf[:cap(buf)], make([]byte, nn)...)
}
return buf[:n]
}
func encryptAEAD(suite cipher.AEAD, buf []byte) ([]byte, error) {
a, b := suite.NonceSize(), len(buf)
buf = extendFront(buf, a)
buf = extendBack(buf, b)
if _, err := rand.Read(buf[:a]); err != nil {
return nil, err
}
return append(buf[:a], suite.Seal(buf[a:a], buf[:a], buf[a:a+b], nil)...), nil
}
func decryptAEAD(suite cipher.AEAD, buf []byte) ([]byte, error) {
if len(buf) < suite.NonceSize() {
return nil, io.ErrUnexpectedEOF
}
nonce := buf[:suite.NonceSize()]
text := buf[suite.NonceSize():]
return suite.Open(text[:0], nonce, text, nil)
}