md4block.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Copyright 2009 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. // MD4 block step.
  5. // In its own file so that a faster assembly or C version
  6. // can be substituted easily.
  7. package md4
  8. import "math/bits"
  9. var shift1 = []int{3, 7, 11, 19}
  10. var shift2 = []int{3, 5, 9, 13}
  11. var shift3 = []int{3, 9, 11, 15}
  12. var xIndex2 = []uint{0, 4, 8, 12, 1, 5, 9, 13, 2, 6, 10, 14, 3, 7, 11, 15}
  13. var xIndex3 = []uint{0, 8, 4, 12, 2, 10, 6, 14, 1, 9, 5, 13, 3, 11, 7, 15}
  14. func _Block(dig *digest, p []byte) int {
  15. a := dig.s[0]
  16. b := dig.s[1]
  17. c := dig.s[2]
  18. d := dig.s[3]
  19. n := 0
  20. var X [16]uint32
  21. for len(p) >= _Chunk {
  22. aa, bb, cc, dd := a, b, c, d
  23. j := 0
  24. for i := 0; i < 16; i++ {
  25. X[i] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24
  26. j += 4
  27. }
  28. // If this needs to be made faster in the future,
  29. // the usual trick is to unroll each of these
  30. // loops by a factor of 4; that lets you replace
  31. // the shift[] lookups with constants and,
  32. // with suitable variable renaming in each
  33. // unrolled body, delete the a, b, c, d = d, a, b, c
  34. // (or you can let the optimizer do the renaming).
  35. //
  36. // The index variables are uint so that % by a power
  37. // of two can be optimized easily by a compiler.
  38. // Round 1.
  39. for i := uint(0); i < 16; i++ {
  40. x := i
  41. s := shift1[i%4]
  42. f := ((c ^ d) & b) ^ d
  43. a += f + X[x]
  44. a = bits.RotateLeft32(a, s)
  45. a, b, c, d = d, a, b, c
  46. }
  47. // Round 2.
  48. for i := uint(0); i < 16; i++ {
  49. x := xIndex2[i]
  50. s := shift2[i%4]
  51. g := (b & c) | (b & d) | (c & d)
  52. a += g + X[x] + 0x5a827999
  53. a = bits.RotateLeft32(a, s)
  54. a, b, c, d = d, a, b, c
  55. }
  56. // Round 3.
  57. for i := uint(0); i < 16; i++ {
  58. x := xIndex3[i]
  59. s := shift3[i%4]
  60. h := b ^ c ^ d
  61. a += h + X[x] + 0x6ed9eba1
  62. a = bits.RotateLeft32(a, s)
  63. a, b, c, d = d, a, b, c
  64. }
  65. a += aa
  66. b += bb
  67. c += cc
  68. d += dd
  69. p = p[_Chunk:]
  70. n += _Chunk
  71. }
  72. dig.s[0] = a
  73. dig.s[1] = b
  74. dig.s[2] = c
  75. dig.s[3] = d
  76. return n
  77. }