sum_generic.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. // Copyright 2018 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. // This file provides the generic implementation of Sum and MAC. Other files
  5. // might provide optimized assembly implementations of some of this code.
  6. package poly1305
  7. import "encoding/binary"
  8. // Poly1305 [RFC 7539] is a relatively simple algorithm: the authentication tag
  9. // for a 64 bytes message is approximately
  10. //
  11. // s + m[0:16] * r⁴ + m[16:32] * r³ + m[32:48] * r² + m[48:64] * r mod 2¹³⁰ - 5
  12. //
  13. // for some secret r and s. It can be computed sequentially like
  14. //
  15. // for len(msg) > 0:
  16. // h += read(msg, 16)
  17. // h *= r
  18. // h %= 2¹³⁰ - 5
  19. // return h + s
  20. //
  21. // All the complexity is about doing performant constant-time math on numbers
  22. // larger than any available numeric type.
  23. func sumGeneric(out *[TagSize]byte, msg []byte, key *[32]byte) {
  24. h := newMACGeneric(key)
  25. h.Write(msg)
  26. h.Sum(out)
  27. }
  28. func newMACGeneric(key *[32]byte) (h macGeneric) {
  29. initialize(key, &h.r, &h.s)
  30. return
  31. }
  32. // macState holds numbers in saturated 64-bit little-endian limbs. That is,
  33. // the value of [x0, x1, x2] is x[0] + x[1] * 2⁶⁴ + x[2] * 2¹²⁸.
  34. type macState struct {
  35. // h is the main accumulator. It is to be interpreted modulo 2¹³⁰ - 5, but
  36. // can grow larger during and after rounds.
  37. h [3]uint64
  38. // r and s are the private key components.
  39. r [2]uint64
  40. s [2]uint64
  41. }
  42. type macGeneric struct {
  43. macState
  44. buffer [TagSize]byte
  45. offset int
  46. }
  47. // Write splits the incoming message into TagSize chunks, and passes them to
  48. // update. It buffers incomplete chunks.
  49. func (h *macGeneric) Write(p []byte) (int, error) {
  50. nn := len(p)
  51. if h.offset > 0 {
  52. n := copy(h.buffer[h.offset:], p)
  53. if h.offset+n < TagSize {
  54. h.offset += n
  55. return nn, nil
  56. }
  57. p = p[n:]
  58. h.offset = 0
  59. updateGeneric(&h.macState, h.buffer[:])
  60. }
  61. if n := len(p) - (len(p) % TagSize); n > 0 {
  62. updateGeneric(&h.macState, p[:n])
  63. p = p[n:]
  64. }
  65. if len(p) > 0 {
  66. h.offset += copy(h.buffer[h.offset:], p)
  67. }
  68. return nn, nil
  69. }
  70. // Sum flushes the last incomplete chunk from the buffer, if any, and generates
  71. // the MAC output. It does not modify its state, in order to allow for multiple
  72. // calls to Sum, even if no Write is allowed after Sum.
  73. func (h *macGeneric) Sum(out *[TagSize]byte) {
  74. state := h.macState
  75. if h.offset > 0 {
  76. updateGeneric(&state, h.buffer[:h.offset])
  77. }
  78. finalize(out, &state.h, &state.s)
  79. }
  80. // [rMask0, rMask1] is the specified Poly1305 clamping mask in little-endian. It
  81. // clears some bits of the secret coefficient to make it possible to implement
  82. // multiplication more efficiently.
  83. const (
  84. rMask0 = 0x0FFFFFFC0FFFFFFF
  85. rMask1 = 0x0FFFFFFC0FFFFFFC
  86. )
  87. func initialize(key *[32]byte, r, s *[2]uint64) {
  88. r[0] = binary.LittleEndian.Uint64(key[0:8]) & rMask0
  89. r[1] = binary.LittleEndian.Uint64(key[8:16]) & rMask1
  90. s[0] = binary.LittleEndian.Uint64(key[16:24])
  91. s[1] = binary.LittleEndian.Uint64(key[24:32])
  92. }
  93. // uint128 holds a 128-bit number as two 64-bit limbs, for use with the
  94. // bits.Mul64 and bits.Add64 intrinsics.
  95. type uint128 struct {
  96. lo, hi uint64
  97. }
  98. func mul64(a, b uint64) uint128 {
  99. hi, lo := bitsMul64(a, b)
  100. return uint128{lo, hi}
  101. }
  102. func add128(a, b uint128) uint128 {
  103. lo, c := bitsAdd64(a.lo, b.lo, 0)
  104. hi, c := bitsAdd64(a.hi, b.hi, c)
  105. if c != 0 {
  106. panic("poly1305: unexpected overflow")
  107. }
  108. return uint128{lo, hi}
  109. }
  110. func shiftRightBy2(a uint128) uint128 {
  111. a.lo = a.lo>>2 | (a.hi&3)<<62
  112. a.hi = a.hi >> 2
  113. return a
  114. }
  115. // updateGeneric absorbs msg into the state.h accumulator. For each chunk m of
  116. // 128 bits of message, it computes
  117. //
  118. // h₊ = (h + m) * r mod 2¹³⁰ - 5
  119. //
  120. // If the msg length is not a multiple of TagSize, it assumes the last
  121. // incomplete chunk is the final one.
  122. func updateGeneric(state *macState, msg []byte) {
  123. h0, h1, h2 := state.h[0], state.h[1], state.h[2]
  124. r0, r1 := state.r[0], state.r[1]
  125. for len(msg) > 0 {
  126. var c uint64
  127. // For the first step, h + m, we use a chain of bits.Add64 intrinsics.
  128. // The resulting value of h might exceed 2¹³⁰ - 5, but will be partially
  129. // reduced at the end of the multiplication below.
  130. //
  131. // The spec requires us to set a bit just above the message size, not to
  132. // hide leading zeroes. For full chunks, that's 1 << 128, so we can just
  133. // add 1 to the most significant (2¹²⁸) limb, h2.
  134. if len(msg) >= TagSize {
  135. h0, c = bitsAdd64(h0, binary.LittleEndian.Uint64(msg[0:8]), 0)
  136. h1, c = bitsAdd64(h1, binary.LittleEndian.Uint64(msg[8:16]), c)
  137. h2 += c + 1
  138. msg = msg[TagSize:]
  139. } else {
  140. var buf [TagSize]byte
  141. copy(buf[:], msg)
  142. buf[len(msg)] = 1
  143. h0, c = bitsAdd64(h0, binary.LittleEndian.Uint64(buf[0:8]), 0)
  144. h1, c = bitsAdd64(h1, binary.LittleEndian.Uint64(buf[8:16]), c)
  145. h2 += c
  146. msg = nil
  147. }
  148. // Multiplication of big number limbs is similar to elementary school
  149. // columnar multiplication. Instead of digits, there are 64-bit limbs.
  150. //
  151. // We are multiplying a 3 limbs number, h, by a 2 limbs number, r.
  152. //
  153. // h2 h1 h0 x
  154. // r1 r0 =
  155. // ----------------
  156. // h2r0 h1r0 h0r0 <-- individual 128-bit products
  157. // + h2r1 h1r1 h0r1
  158. // ------------------------
  159. // m3 m2 m1 m0 <-- result in 128-bit overlapping limbs
  160. // ------------------------
  161. // m3.hi m2.hi m1.hi m0.hi <-- carry propagation
  162. // + m3.lo m2.lo m1.lo m0.lo
  163. // -------------------------------
  164. // t4 t3 t2 t1 t0 <-- final result in 64-bit limbs
  165. //
  166. // The main difference from pen-and-paper multiplication is that we do
  167. // carry propagation in a separate step, as if we wrote two digit sums
  168. // at first (the 128-bit limbs), and then carried the tens all at once.
  169. h0r0 := mul64(h0, r0)
  170. h1r0 := mul64(h1, r0)
  171. h2r0 := mul64(h2, r0)
  172. h0r1 := mul64(h0, r1)
  173. h1r1 := mul64(h1, r1)
  174. h2r1 := mul64(h2, r1)
  175. // Since h2 is known to be at most 7 (5 + 1 + 1), and r0 and r1 have their
  176. // top 4 bits cleared by rMask{0,1}, we know that their product is not going
  177. // to overflow 64 bits, so we can ignore the high part of the products.
  178. //
  179. // This also means that the product doesn't have a fifth limb (t4).
  180. if h2r0.hi != 0 {
  181. panic("poly1305: unexpected overflow")
  182. }
  183. if h2r1.hi != 0 {
  184. panic("poly1305: unexpected overflow")
  185. }
  186. m0 := h0r0
  187. m1 := add128(h1r0, h0r1) // These two additions don't overflow thanks again
  188. m2 := add128(h2r0, h1r1) // to the 4 masked bits at the top of r0 and r1.
  189. m3 := h2r1
  190. t0 := m0.lo
  191. t1, c := bitsAdd64(m1.lo, m0.hi, 0)
  192. t2, c := bitsAdd64(m2.lo, m1.hi, c)
  193. t3, _ := bitsAdd64(m3.lo, m2.hi, c)
  194. // Now we have the result as 4 64-bit limbs, and we need to reduce it
  195. // modulo 2¹³⁰ - 5. The special shape of this Crandall prime lets us do
  196. // a cheap partial reduction according to the reduction identity
  197. //
  198. // c * 2¹³⁰ + n = c * 5 + n mod 2¹³⁰ - 5
  199. //
  200. // because 2¹³⁰ = 5 mod 2¹³⁰ - 5. Partial reduction since the result is
  201. // likely to be larger than 2¹³⁰ - 5, but still small enough to fit the
  202. // assumptions we make about h in the rest of the code.
  203. //
  204. // See also https://speakerdeck.com/gtank/engineering-prime-numbers?slide=23
  205. // We split the final result at the 2¹³⁰ mark into h and cc, the carry.
  206. // Note that the carry bits are effectively shifted left by 2, in other
  207. // words, cc = c * 4 for the c in the reduction identity.
  208. h0, h1, h2 = t0, t1, t2&maskLow2Bits
  209. cc := uint128{t2 & maskNotLow2Bits, t3}
  210. // To add c * 5 to h, we first add cc = c * 4, and then add (cc >> 2) = c.
  211. h0, c = bitsAdd64(h0, cc.lo, 0)
  212. h1, c = bitsAdd64(h1, cc.hi, c)
  213. h2 += c
  214. cc = shiftRightBy2(cc)
  215. h0, c = bitsAdd64(h0, cc.lo, 0)
  216. h1, c = bitsAdd64(h1, cc.hi, c)
  217. h2 += c
  218. // h2 is at most 3 + 1 + 1 = 5, making the whole of h at most
  219. //
  220. // 5 * 2¹²⁸ + (2¹²⁸ - 1) = 6 * 2¹²⁸ - 1
  221. }
  222. state.h[0], state.h[1], state.h[2] = h0, h1, h2
  223. }
  224. const (
  225. maskLow2Bits uint64 = 0x0000000000000003
  226. maskNotLow2Bits uint64 = ^maskLow2Bits
  227. )
  228. // select64 returns x if v == 1 and y if v == 0, in constant time.
  229. func select64(v, x, y uint64) uint64 { return ^(v-1)&x | (v-1)&y }
  230. // [p0, p1, p2] is 2¹³⁰ - 5 in little endian order.
  231. const (
  232. p0 = 0xFFFFFFFFFFFFFFFB
  233. p1 = 0xFFFFFFFFFFFFFFFF
  234. p2 = 0x0000000000000003
  235. )
  236. // finalize completes the modular reduction of h and computes
  237. //
  238. // out = h + s mod 2¹²⁸
  239. //
  240. func finalize(out *[TagSize]byte, h *[3]uint64, s *[2]uint64) {
  241. h0, h1, h2 := h[0], h[1], h[2]
  242. // After the partial reduction in updateGeneric, h might be more than
  243. // 2¹³⁰ - 5, but will be less than 2 * (2¹³⁰ - 5). To complete the reduction
  244. // in constant time, we compute t = h - (2¹³⁰ - 5), and select h as the
  245. // result if the subtraction underflows, and t otherwise.
  246. hMinusP0, b := bitsSub64(h0, p0, 0)
  247. hMinusP1, b := bitsSub64(h1, p1, b)
  248. _, b = bitsSub64(h2, p2, b)
  249. // h = h if h < p else h - p
  250. h0 = select64(b, h0, hMinusP0)
  251. h1 = select64(b, h1, hMinusP1)
  252. // Finally, we compute the last Poly1305 step
  253. //
  254. // tag = h + s mod 2¹²⁸
  255. //
  256. // by just doing a wide addition with the 128 low bits of h and discarding
  257. // the overflow.
  258. h0, c := bitsAdd64(h0, s[0], 0)
  259. h1, _ = bitsAdd64(h1, s[1], c)
  260. binary.LittleEndian.PutUint64(out[0:8], h0)
  261. binary.LittleEndian.PutUint64(out[8:16], h1)
  262. }