lthash.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (c) 2021 Tulir Asokan
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this
  5. // file, You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // Package lthash implements a summation based hash algorithm that maintains the
  7. // integrity of a piece of data over a series of mutations. You can add/remove
  8. // mutations, and it'll return a hash equal to if the same series of mutations
  9. // was made sequentially.
  10. package lthash
  11. import (
  12. "encoding/binary"
  13. "git.bobomao.top/joey/testwh/util/hkdfutil"
  14. )
  15. type LTHash struct {
  16. HKDFInfo []byte
  17. HKDFSize uint8
  18. }
  19. // WAPatchIntegrity is a LTHash instance initialized with the details used for verifying integrity of WhatsApp app state sync patches.
  20. var WAPatchIntegrity = LTHash{[]byte("WhatsApp Patch Integrity"), 128}
  21. func (lth LTHash) SubtractThenAdd(base []byte, subtract, add [][]byte) []byte {
  22. output := make([]byte, len(base))
  23. copy(output, base)
  24. lth.SubtractThenAddInPlace(output, subtract, add)
  25. return output
  26. }
  27. func (lth LTHash) SubtractThenAddInPlace(base []byte, subtract, add [][]byte) {
  28. lth.multipleOp(base, subtract, true)
  29. lth.multipleOp(base, add, false)
  30. }
  31. func (lth LTHash) multipleOp(base []byte, input [][]byte, subtract bool) {
  32. for _, item := range input {
  33. performPointwiseWithOverflow(base, hkdfutil.SHA256(item, nil, lth.HKDFInfo, lth.HKDFSize), subtract)
  34. }
  35. }
  36. func performPointwiseWithOverflow(base, input []byte, subtract bool) []byte {
  37. for i := 0; i < len(base); i += 2 {
  38. x := binary.LittleEndian.Uint16(base[i : i+2])
  39. y := binary.LittleEndian.Uint16(input[i : i+2])
  40. var result uint16
  41. if subtract {
  42. result = x - y
  43. } else {
  44. result = x + y
  45. }
  46. binary.LittleEndian.PutUint16(base[i:i+2], result)
  47. }
  48. return base
  49. }