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.

70 lines
2.2 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
  5. import (
  6. "encoding/binary"
  7. "golang.org/x/crypto/chacha20poly1305/internal/chacha20"
  8. "golang.org/x/crypto/poly1305"
  9. )
  10. func roundTo16(n int) int {
  11. return 16 * ((n + 15) / 16)
  12. }
  13. func (c *chacha20poly1305) sealGeneric(dst, nonce, plaintext, additionalData []byte) []byte {
  14. var counter [16]byte
  15. copy(counter[4:], nonce)
  16. var polyKey [32]byte
  17. chacha20.XORKeyStream(polyKey[:], polyKey[:], &counter, &c.key)
  18. ret, out := sliceForAppend(dst, len(plaintext)+poly1305.TagSize)
  19. counter[0] = 1
  20. chacha20.XORKeyStream(out, plaintext, &counter, &c.key)
  21. polyInput := make([]byte, roundTo16(len(additionalData))+roundTo16(len(plaintext))+8+8)
  22. copy(polyInput, additionalData)
  23. copy(polyInput[roundTo16(len(additionalData)):], out[:len(plaintext)])
  24. binary.LittleEndian.PutUint64(polyInput[len(polyInput)-16:], uint64(len(additionalData)))
  25. binary.LittleEndian.PutUint64(polyInput[len(polyInput)-8:], uint64(len(plaintext)))
  26. var tag [poly1305.TagSize]byte
  27. poly1305.Sum(&tag, polyInput, &polyKey)
  28. copy(out[len(plaintext):], tag[:])
  29. return ret
  30. }
  31. func (c *chacha20poly1305) openGeneric(dst, nonce, ciphertext, additionalData []byte) ([]byte, error) {
  32. var tag [poly1305.TagSize]byte
  33. copy(tag[:], ciphertext[len(ciphertext)-16:])
  34. ciphertext = ciphertext[:len(ciphertext)-16]
  35. var counter [16]byte
  36. copy(counter[4:], nonce)
  37. var polyKey [32]byte
  38. chacha20.XORKeyStream(polyKey[:], polyKey[:], &counter, &c.key)
  39. polyInput := make([]byte, roundTo16(len(additionalData))+roundTo16(len(ciphertext))+8+8)
  40. copy(polyInput, additionalData)
  41. copy(polyInput[roundTo16(len(additionalData)):], ciphertext)
  42. binary.LittleEndian.PutUint64(polyInput[len(polyInput)-16:], uint64(len(additionalData)))
  43. binary.LittleEndian.PutUint64(polyInput[len(polyInput)-8:], uint64(len(ciphertext)))
  44. ret, out := sliceForAppend(dst, len(ciphertext))
  45. if !poly1305.Verify(&tag, polyInput, &polyKey) {
  46. for i := range out {
  47. out[i] = 0
  48. }
  49. return nil, errOpen
  50. }
  51. counter[0] = 1
  52. chacha20.XORKeyStream(out, ciphertext, &counter, &c.key)
  53. return ret, nil
  54. }