ghash.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. var zeros = new Buffer(16)
  2. zeros.fill(0)
  3. module.exports = GHASH
  4. function GHASH (key) {
  5. this.h = key
  6. this.state = new Buffer(16)
  7. this.state.fill(0)
  8. this.cache = new Buffer('')
  9. }
  10. // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
  11. // by Juho Vähä-Herttua
  12. GHASH.prototype.ghash = function (block) {
  13. var i = -1
  14. while (++i < block.length) {
  15. this.state[i] ^= block[i]
  16. }
  17. this._multiply()
  18. }
  19. GHASH.prototype._multiply = function () {
  20. var Vi = toArray(this.h)
  21. var Zi = [0, 0, 0, 0]
  22. var j, xi, lsb_Vi
  23. var i = -1
  24. while (++i < 128) {
  25. xi = (this.state[~~(i / 8)] & (1 << (7 - i % 8))) !== 0
  26. if (xi) {
  27. // Z_i+1 = Z_i ^ V_i
  28. Zi = xor(Zi, Vi)
  29. }
  30. // Store the value of LSB(V_i)
  31. lsb_Vi = (Vi[3] & 1) !== 0
  32. // V_i+1 = V_i >> 1
  33. for (j = 3; j > 0; j--) {
  34. Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
  35. }
  36. Vi[0] = Vi[0] >>> 1
  37. // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
  38. if (lsb_Vi) {
  39. Vi[0] = Vi[0] ^ (0xe1 << 24)
  40. }
  41. }
  42. this.state = fromArray(Zi)
  43. }
  44. GHASH.prototype.update = function (buf) {
  45. this.cache = Buffer.concat([this.cache, buf])
  46. var chunk
  47. while (this.cache.length >= 16) {
  48. chunk = this.cache.slice(0, 16)
  49. this.cache = this.cache.slice(16)
  50. this.ghash(chunk)
  51. }
  52. }
  53. GHASH.prototype.final = function (abl, bl) {
  54. if (this.cache.length) {
  55. this.ghash(Buffer.concat([this.cache, zeros], 16))
  56. }
  57. this.ghash(fromArray([
  58. 0, abl,
  59. 0, bl
  60. ]))
  61. return this.state
  62. }
  63. function toArray (buf) {
  64. return [
  65. buf.readUInt32BE(0),
  66. buf.readUInt32BE(4),
  67. buf.readUInt32BE(8),
  68. buf.readUInt32BE(12)
  69. ]
  70. }
  71. function fromArray (out) {
  72. out = out.map(fixup_uint32)
  73. var buf = new Buffer(16)
  74. buf.writeUInt32BE(out[0], 0)
  75. buf.writeUInt32BE(out[1], 4)
  76. buf.writeUInt32BE(out[2], 8)
  77. buf.writeUInt32BE(out[3], 12)
  78. return buf
  79. }
  80. var uint_max = Math.pow(2, 32)
  81. function fixup_uint32 (x) {
  82. var ret, x_pos
  83. ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x
  84. return ret
  85. }
  86. function xor (a, b) {
  87. return [
  88. a[0] ^ b[0],
  89. a[1] ^ b[1],
  90. a[2] ^ b[2],
  91. a[3] ^ b[3]
  92. ]
  93. }