Projekt

Obecné

Profil

Stáhnout (1.91 KB) Statistiky
| Větev: | Revize:
1
var Buffer = require('safe-buffer').Buffer
2
var ZEROES = Buffer.alloc(16, 0)
3

    
4
function toArray (buf) {
5
  return [
6
    buf.readUInt32BE(0),
7
    buf.readUInt32BE(4),
8
    buf.readUInt32BE(8),
9
    buf.readUInt32BE(12)
10
  ]
11
}
12

    
13
function fromArray (out) {
14
  var buf = Buffer.allocUnsafe(16)
15
  buf.writeUInt32BE(out[0] >>> 0, 0)
16
  buf.writeUInt32BE(out[1] >>> 0, 4)
17
  buf.writeUInt32BE(out[2] >>> 0, 8)
18
  buf.writeUInt32BE(out[3] >>> 0, 12)
19
  return buf
20
}
21

    
22
function GHASH (key) {
23
  this.h = key
24
  this.state = Buffer.alloc(16, 0)
25
  this.cache = Buffer.allocUnsafe(0)
26
}
27

    
28
// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
29
// by Juho Vähä-Herttua
30
GHASH.prototype.ghash = function (block) {
31
  var i = -1
32
  while (++i < block.length) {
33
    this.state[i] ^= block[i]
34
  }
35
  this._multiply()
36
}
37

    
38
GHASH.prototype._multiply = function () {
39
  var Vi = toArray(this.h)
40
  var Zi = [0, 0, 0, 0]
41
  var j, xi, lsbVi
42
  var i = -1
43
  while (++i < 128) {
44
    xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
45
    if (xi) {
46
      // Z_i+1 = Z_i ^ V_i
47
      Zi[0] ^= Vi[0]
48
      Zi[1] ^= Vi[1]
49
      Zi[2] ^= Vi[2]
50
      Zi[3] ^= Vi[3]
51
    }
52

    
53
    // Store the value of LSB(V_i)
54
    lsbVi = (Vi[3] & 1) !== 0
55

    
56
    // V_i+1 = V_i >> 1
57
    for (j = 3; j > 0; j--) {
58
      Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
59
    }
60
    Vi[0] = Vi[0] >>> 1
61

    
62
    // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
63
    if (lsbVi) {
64
      Vi[0] = Vi[0] ^ (0xe1 << 24)
65
    }
66
  }
67
  this.state = fromArray(Zi)
68
}
69

    
70
GHASH.prototype.update = function (buf) {
71
  this.cache = Buffer.concat([this.cache, buf])
72
  var chunk
73
  while (this.cache.length >= 16) {
74
    chunk = this.cache.slice(0, 16)
75
    this.cache = this.cache.slice(16)
76
    this.ghash(chunk)
77
  }
78
}
79

    
80
GHASH.prototype.final = function (abl, bl) {
81
  if (this.cache.length) {
82
    this.ghash(Buffer.concat([this.cache, ZEROES], 16))
83
  }
84

    
85
  this.ghash(fromArray([0, abl, 0, bl]))
86
  return this.state
87
}
88

    
89
module.exports = GHASH
(9-9/13)