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 |
|
11 |
|
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 |
|
20 | GHASH.prototype._multiply = function () {
|
21 | var Vi = toArray(this.h);
|
22 | var Zi = [0, 0, 0, 0];
|
23 | var j, xi, lsb_Vi;
|
24 | var i = -1;
|
25 | while (++i < 128) {
|
26 | xi = (this.state[~~(i/8)] & (1 << (7-i%8))) !== 0;
|
27 | if (xi) {
|
28 |
|
29 | Zi = xor(Zi, Vi);
|
30 | }
|
31 |
|
32 |
|
33 | lsb_Vi = (Vi[3] & 1) !== 0;
|
34 |
|
35 |
|
36 | for (j=3; j>0; j--) {
|
37 | Vi[j] = (Vi[j] >>> 1) | ((Vi[j-1]&1) << 31);
|
38 | }
|
39 | Vi[0] = Vi[0] >>> 1;
|
40 |
|
41 |
|
42 | if (lsb_Vi) {
|
43 | Vi[0] = Vi[0] ^ (0xe1 << 24);
|
44 | }
|
45 | }
|
46 | this.state = fromArray(Zi);
|
47 | };
|
48 | GHASH.prototype.update = function (buf) {
|
49 | this.cache = Buffer.concat([this.cache, buf]);
|
50 | var chunk;
|
51 | while (this.cache.length >= 16) {
|
52 | chunk = this.cache.slice(0, 16);
|
53 | this.cache = this.cache.slice(16);
|
54 | this.ghash(chunk);
|
55 | }
|
56 | };
|
57 | GHASH.prototype.final = function (abl, bl) {
|
58 | if (this.cache.length) {
|
59 | this.ghash(Buffer.concat([this.cache, zeros], 16));
|
60 | }
|
61 | this.ghash(fromArray([
|
62 | 0, abl,
|
63 | 0, bl
|
64 | ]));
|
65 | return this.state;
|
66 | };
|
67 |
|
68 | function toArray(buf) {
|
69 | return [
|
70 | buf.readUInt32BE(0),
|
71 | buf.readUInt32BE(4),
|
72 | buf.readUInt32BE(8),
|
73 | buf.readUInt32BE(12)
|
74 | ];
|
75 | }
|
76 | function fromArray(out) {
|
77 | out = out.map(fixup_uint32);
|
78 | var buf = new Buffer(16);
|
79 | buf.writeUInt32BE(out[0], 0);
|
80 | buf.writeUInt32BE(out[1], 4);
|
81 | buf.writeUInt32BE(out[2], 8);
|
82 | buf.writeUInt32BE(out[3], 12);
|
83 | return buf;
|
84 | }
|
85 | var uint_max = Math.pow(2, 32);
|
86 | function fixup_uint32(x) {
|
87 | var ret, x_pos;
|
88 | ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x;
|
89 | return ret;
|
90 | }
|
91 | function xor(a, b) {
|
92 | return [
|
93 | a[0] ^ b[0],
|
94 | a[1] ^ b[1],
|
95 | a[2] ^ b[2],
|
96 | a[3] ^ b[3],
|
97 | ];
|
98 | } |
\ | No newline at end of file |