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 fips140Enforced() {
26 return nil, errors.New("chacha20poly1305: use of ChaCha20Poly1305 is not allowed in FIPS 140-only mode")
27 }
28 if len(key) != KeySize {
29 return nil, errors.New("chacha20poly1305: bad key length")
30 }
31 ret := new(xchacha20poly1305)
32 copy(ret.key[:], key)
33 return ret, nil
34 }
35
36 func (*xchacha20poly1305) NonceSize() int {
37 return NonceSizeX
38 }
39
40 func (*xchacha20poly1305) Overhead() int {
41 return Overhead
42 }
43
44 func (x *xchacha20poly1305) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
45 if len(nonce) != NonceSizeX {
46 panic("chacha20poly1305: bad nonce length passed to Seal")
47 }
48
49
50
51
52
53
54 if uint64(len(plaintext)) > (1<<38)-64 {
55 panic("chacha20poly1305: plaintext too large")
56 }
57
58 c := new(chacha20poly1305)
59 hKey, _ := chacha20.HChaCha20(x.key[:], nonce[0:16])
60 copy(c.key[:], hKey)
61
62
63 cNonce := make([]byte, NonceSize)
64 copy(cNonce[4:12], nonce[16:24])
65
66 return c.seal(dst, cNonce[:], plaintext, additionalData)
67 }
68
69 func (x *xchacha20poly1305) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
70 if len(nonce) != NonceSizeX {
71 panic("chacha20poly1305: bad nonce length passed to Open")
72 }
73 if len(ciphertext) < 16 {
74 return nil, errOpen
75 }
76 if uint64(len(ciphertext)) > (1<<38)-48 {
77 panic("chacha20poly1305: ciphertext too large")
78 }
79
80 c := new(chacha20poly1305)
81 hKey, _ := chacha20.HChaCha20(x.key[:], nonce[0:16])
82 copy(c.key[:], hKey)
83
84
85 cNonce := make([]byte, NonceSize)
86 copy(cNonce[4:12], nonce[16:24])
87
88 return c.open(dst, cNonce[:], ciphertext, additionalData)
89 }
90
View as plain text