...
1
2
3
4
5 package chacha20poly1305
6
7 import (
8 "crypto/cipher"
9 "errors"
10
11 "golang.org/x/crypto/chacha20"
12 )
13
14 type xchacha20poly1305 struct {
15 key [KeySize]byte
16 }
17
18
19
20
21
22
23
24 func NewX(key []byte) (cipher.AEAD, error) {
25 if len(key) != KeySize {
26 return nil, errors.New("chacha20poly1305: bad key length")
27 }
28 ret := new(xchacha20poly1305)
29 copy(ret.key[:], key)
30 return ret, nil
31 }
32
33 func (*xchacha20poly1305) NonceSize() int {
34 return NonceSizeX
35 }
36
37 func (*xchacha20poly1305) Overhead() int {
38 return Overhead
39 }
40
41 func (x *xchacha20poly1305) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
42 if len(nonce) != NonceSizeX {
43 panic("chacha20poly1305: bad nonce length passed to Seal")
44 }
45
46
47
48
49
50
51 if uint64(len(plaintext)) > (1<<38)-64 {
52 panic("chacha20poly1305: plaintext too large")
53 }
54
55 c := new(chacha20poly1305)
56 hKey, _ := chacha20.HChaCha20(x.key[:], nonce[0:16])
57 copy(c.key[:], hKey)
58
59
60 cNonce := make([]byte, NonceSize)
61 copy(cNonce[4:12], nonce[16:24])
62
63 return c.seal(dst, cNonce[:], plaintext, additionalData)
64 }
65
66 func (x *xchacha20poly1305) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
67 if len(nonce) != NonceSizeX {
68 panic("chacha20poly1305: bad nonce length passed to Open")
69 }
70 if len(ciphertext) < 16 {
71 return nil, errOpen
72 }
73 if uint64(len(ciphertext)) > (1<<38)-48 {
74 panic("chacha20poly1305: ciphertext too large")
75 }
76
77 c := new(chacha20poly1305)
78 hKey, _ := chacha20.HChaCha20(x.key[:], nonce[0:16])
79 copy(c.key[:], hKey)
80
81
82 cNonce := make([]byte, NonceSize)
83 copy(cNonce[4:12], nonce[16:24])
84
85 return c.open(dst, cNonce[:], ciphertext, additionalData)
86 }
87
View as plain text