ghash.js 1.9 KB

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