cipher_state.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package noiseutil
  2. import (
  3. "fmt"
  4. "github.com/flynn/noise"
  5. )
  6. // CipherState is the post-handshake AEAD cipher used for the data plane.
  7. // Each supported cipher has its own concrete implementation in this package with the nonce endianness hardcoded,
  8. // so the encrypt/decrypt fast path avoids interface dispatch on the byte order.
  9. type CipherState interface {
  10. // EncryptDanger encrypts and authenticates a given payload.
  11. //
  12. // out is a destination slice to hold the output of the EncryptDanger operation.
  13. // - ad is additional data, which will be authenticated and appended to out, but not encrypted.
  14. // - plaintext is encrypted, authenticated and appended to out.
  15. // - n is a nonce value which must never be re-used with this key.
  16. // - nb is a scratch buffer used to assemble the nonce.
  17. EncryptDanger(out, ad, plaintext []byte, n uint64, nb []byte) ([]byte, error)
  18. // DecryptDanger authenticates and decrypts a given payload, with the same argument shape as EncryptDanger.
  19. DecryptDanger(out, ad, ciphertext []byte, n uint64, nb []byte) ([]byte, error)
  20. // Overhead returns the AEAD tag size, or 0 if the receiver is nil.
  21. Overhead() int
  22. }
  23. // NewCipherState wraps the post-handshake noise.CipherState in the per-cipher type that matches cipherFunc.
  24. // cipherFunc must be the same cipher used to build the noise CipherSuite that produced s.
  25. func NewCipherState(s *noise.CipherState, cipherFunc noise.CipherFunc) CipherState {
  26. switch cipherFunc.CipherName() {
  27. case CipherAESGCM.CipherName():
  28. return NewCipherStateAESGCM(s)
  29. case noise.CipherChaChaPoly.CipherName():
  30. return NewCipherStateChaChaPoly(s)
  31. default:
  32. panic(fmt.Sprintf("noiseutil: unsupported cipher %q", cipherFunc.CipherName()))
  33. }
  34. }