You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.3 KiB

  1. // Copyright 2016 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. // Package chacha20poly1305 implements the ChaCha20-Poly1305 AEAD as specified in RFC 7539.
  5. package chacha20poly1305 // import "golang.org/x/crypto/chacha20poly1305"
  6. import (
  7. "crypto/cipher"
  8. "errors"
  9. )
  10. const (
  11. // KeySize is the size of the key used by this AEAD, in bytes.
  12. KeySize = 32
  13. // NonceSize is the size of the nonce used with this AEAD, in bytes.
  14. NonceSize = 12
  15. )
  16. type chacha20poly1305 struct {
  17. key [32]byte
  18. }
  19. // New returns a ChaCha20-Poly1305 AEAD that uses the given, 256-bit key.
  20. func New(key []byte) (cipher.AEAD, error) {
  21. if len(key) != KeySize {
  22. return nil, errors.New("chacha20poly1305: bad key length")
  23. }
  24. ret := new(chacha20poly1305)
  25. copy(ret.key[:], key)
  26. return ret, nil
  27. }
  28. func (c *chacha20poly1305) NonceSize() int {
  29. return NonceSize
  30. }
  31. func (c *chacha20poly1305) Overhead() int {
  32. return 16
  33. }
  34. func (c *chacha20poly1305) Seal(dst, nonce, plaintext, additionalData []byte) []byte {
  35. if len(nonce) != NonceSize {
  36. panic("chacha20poly1305: bad nonce length passed to Seal")
  37. }
  38. if uint64(len(plaintext)) > (1<<38)-64 {
  39. panic("chacha20poly1305: plaintext too large")
  40. }
  41. return c.seal(dst, nonce, plaintext, additionalData)
  42. }
  43. var errOpen = errors.New("chacha20poly1305: message authentication failed")
  44. func (c *chacha20poly1305) Open(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
  45. if len(nonce) != NonceSize {
  46. panic("chacha20poly1305: bad nonce length passed to Open")
  47. }
  48. if len(ciphertext) < 16 {
  49. return nil, errOpen
  50. }
  51. if uint64(len(ciphertext)) > (1<<38)-48 {
  52. panic("chacha20poly1305: ciphertext too large")
  53. }
  54. return c.open(dst, nonce, ciphertext, additionalData)
  55. }
  56. // sliceForAppend takes a slice and a requested number of bytes. It returns a
  57. // slice with the contents of the given slice followed by that many bytes and a
  58. // second slice that aliases into it and contains only the extra bytes. If the
  59. // original slice has sufficient capacity then no allocation is performed.
  60. func sliceForAppend(in []byte, n int) (head, tail []byte) {
  61. if total := len(in) + n; cap(in) >= total {
  62. head = in[:total]
  63. } else {
  64. head = make([]byte, total)
  65. copy(head, in)
  66. }
  67. tail = head[len(in):]
  68. return
  69. }