| 1 |
package noiseutil |
| 2 |
|
| 3 |
import ( |
| 4 |
"crypto/cipher" |
| 5 |
"encoding/binary" |
| 6 |
"errors" |
| 7 |
|
| 8 |
"github.com/flynn/noise" |
| 9 |
) |
| 10 |
|
| 11 |
// CipherStateChaChaPoly is the data-plane wrapper for the ChaCha20-Poly1305 AEAD cipher. |
| 12 |
// ChaCha20-Poly1305 uses little-endian nonce encoding per the Noise spec. |
| 13 |
type CipherStateChaChaPoly struct { |
| 14 |
c cipher.AEAD |
| 15 |
} |
| 16 |
|
| 17 |
// NewCipherStateChaChaPoly extracts the underlying AEAD from the post-handshake noise.CipherState. |
| 18 |
// The caller is responsible for ensuring the noise cipher is actually ChaCha20-Poly1305. |
| 19 |
func NewCipherStateChaChaPoly(s *noise.CipherState) *CipherStateChaChaPoly { |
| 20 |
return &CipherStateChaChaPoly{c: s.Cipher().(cipher.AEAD)} |
| 21 |
} |
| 22 |
|
| 23 |
func (s *CipherStateChaChaPoly) EncryptDanger(out, ad, plaintext []byte, n uint64, nb []byte) ([]byte, error) { |
| 24 |
if s == nil { |
| 25 |
return nil, errors.New("no cipher state available to encrypt") |
| 26 |
} |
| 27 |
nb[0] = 0 |
| 28 |
nb[1] = 0 |
| 29 |
nb[2] = 0 |
| 30 |
nb[3] = 0 |
| 31 |
binary.LittleEndian.PutUint64(nb[4:], n) |
| 32 |
return s.c.Seal(out, nb, plaintext, ad), nil |
| 33 |
} |
| 34 |
|
| 35 |
func (s *CipherStateChaChaPoly) DecryptDanger(out, ad, ciphertext []byte, n uint64, nb []byte) ([]byte, error) { |
| 36 |
if s == nil { |
| 37 |
return []byte{}, nil |
| 38 |
} |
| 39 |
nb[0] = 0 |
| 40 |
nb[1] = 0 |
| 41 |
nb[2] = 0 |
| 42 |
nb[3] = 0 |
| 43 |
binary.LittleEndian.PutUint64(nb[4:], n) |
| 44 |
return s.c.Open(out, nb, ciphertext, ad) |
| 45 |
} |
| 46 |
|
| 47 |
func (s *CipherStateChaChaPoly) Overhead() int { |
| 48 |
if s == nil { |
| 49 |
return 0 |
| 50 |
} |
| 51 |
return s.c.Overhead() |
| 52 |
} |