sha1block.go 2.3 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. package sha1
  5. const (
  6. _K0 = 0x5A827999
  7. _K1 = 0x6ED9EBA1
  8. _K2 = 0x8F1BBCDC
  9. _K3 = 0xCA62C1D6
  10. )
  11. // blockGeneric is a portable, pure Go version of the SHA1 block step.
  12. // It's used by sha1block_generic.go and tests.
  13. func blockGeneric(dig *digest, p []byte) {
  14. var w [16]uint32
  15. h0, h1, h2, h3, h4 := dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4]
  16. for len(p) >= chunk {
  17. // Can interlace the computation of w with the
  18. // rounds below if needed for speed.
  19. for i := 0; i < 16; i++ {
  20. j := i * 4
  21. w[i] = uint32(p[j])<<24 | uint32(p[j+1])<<16 | uint32(p[j+2])<<8 | uint32(p[j+3])
  22. }
  23. a, b, c, d, e := h0, h1, h2, h3, h4
  24. // Each of the four 20-iteration rounds
  25. // differs only in the computation of f and
  26. // the choice of K (_K0, _K1, etc).
  27. i := 0
  28. for ; i < 16; i++ {
  29. f := b&c | (^b)&d
  30. a5 := a<<5 | a>>(32-5)
  31. b30 := b<<30 | b>>(32-30)
  32. t := a5 + f + e + w[i&0xf] + _K0
  33. a, b, c, d, e = t, a, b30, c, d
  34. }
  35. for ; i < 20; i++ {
  36. tmp := w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf]
  37. w[i&0xf] = tmp<<1 | tmp>>(32-1)
  38. f := b&c | (^b)&d
  39. a5 := a<<5 | a>>(32-5)
  40. b30 := b<<30 | b>>(32-30)
  41. t := a5 + f + e + w[i&0xf] + _K0
  42. a, b, c, d, e = t, a, b30, c, d
  43. }
  44. for ; i < 40; i++ {
  45. tmp := w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf]
  46. w[i&0xf] = tmp<<1 | tmp>>(32-1)
  47. f := b ^ c ^ d
  48. a5 := a<<5 | a>>(32-5)
  49. b30 := b<<30 | b>>(32-30)
  50. t := a5 + f + e + w[i&0xf] + _K1
  51. a, b, c, d, e = t, a, b30, c, d
  52. }
  53. for ; i < 60; i++ {
  54. tmp := w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf]
  55. w[i&0xf] = tmp<<1 | tmp>>(32-1)
  56. f := ((b | c) & d) | (b & c)
  57. a5 := a<<5 | a>>(32-5)
  58. b30 := b<<30 | b>>(32-30)
  59. t := a5 + f + e + w[i&0xf] + _K2
  60. a, b, c, d, e = t, a, b30, c, d
  61. }
  62. for ; i < 80; i++ {
  63. tmp := w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf]
  64. w[i&0xf] = tmp<<1 | tmp>>(32-1)
  65. f := b ^ c ^ d
  66. a5 := a<<5 | a>>(32-5)
  67. b30 := b<<30 | b>>(32-30)
  68. t := a5 + f + e + w[i&0xf] + _K3
  69. a, b, c, d, e = t, a, b30, c, d
  70. }
  71. h0 += a
  72. h1 += b
  73. h2 += c
  74. h3 += d
  75. h4 += e
  76. p = p[chunk:]
  77. }
  78. dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4] = h0, h1, h2, h3, h4
  79. }