chachapoly refactor.

This commit is contained in:
Christopher Jeffrey 2016-06-18 17:42:35 -07:00
parent c02b93adae
commit 75aad4e771
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD

View File

@ -94,7 +94,7 @@ ChaCha20.prototype.encrypt = function encrypt(data) {
for (j = 0; j < 16; j++) {
this.stream[j] += this.state[j];
this.bytes.writeUInt32LE(this.stream[j], j * 4);
this.bytes.writeUInt32LE(this.stream[j], j * 4, true);
}
this.state[12]++;
@ -150,10 +150,17 @@ ChaCha20.prototype.getCounter = function getCounter() {
*/
function qround(x, a, b, c, d) {
x[a] += x[b]; x[d] = rotl32(x[d] ^ x[a], 16);
x[c] += x[d]; x[b] = rotl32(x[b] ^ x[c], 12);
x[a] += x[b]; x[d] = rotl32(x[d] ^ x[a], 8);
x[c] += x[d]; x[b] = rotl32(x[b] ^ x[c], 7);
x[a] += x[b];
x[d] = rotl32(x[d] ^ x[a], 16);
x[c] += x[d];
x[b] = rotl32(x[b] ^ x[c], 12);
x[a] += x[b];
x[d] = rotl32(x[d] ^ x[a], 8);
x[c] += x[d];
x[b] = rotl32(x[b] ^ x[c], 7);
}
function rotl32(w, b) {
@ -203,7 +210,7 @@ Poly1305.prototype.init = function init(key) {
this.r[2] = ((t1 >>> 10) | (t2 << 6)) & 0x1f03;
this.r[3] = ((t2 >>> 7) | (t3 << 9)) & 0x1fff;
this.r[4] = ((t3 >>> 4) | (t4 << 12)) & 0x00ff;
this.r[5] = (t4 >>> 1) & 0x1ffe;
this.r[5] = (t4 >>> 1) & 0x1ffe;
this.r[6] = ((t4 >>> 14) | (t5 << 2)) & 0x1fff;
this.r[7] = ((t5 >>> 11) | (t6 << 5)) & 0x1f81;
this.r[8] = ((t6 >>> 8) | (t7 << 8)) & 0x1fff;
@ -259,24 +266,24 @@ Poly1305.prototype.blocks = function blocks(data, bytes, m) {
for (i = 0, c = 0; i < 10; i++) {
d[i] = c;
for (j = 0; j < 10; j++) {
d[i] += this.h[j] * ((j <= i)
d[i] += this.h[j] * (j <= i
? this.r[i - j]
: (5 * this.r[i + 10 - j]));
: 5 * this.r[i + 10 - j]);
// Sum(h[i] * r[i] * 5) will overflow slightly
// above 6 products with an unclamped r, so
// carry at 5
if (j === 4) {
c = (d[i] >>> 13);
c = d[i] >>> 13;
d[i] &= 0x1fff;
}
}
c += (d[i] >>> 13);
c += d[i] >>> 13;
d[i] &= 0x1fff;
}
c = ((c << 2) + c); // c *= 5
c = (c << 2) + c; // c *= 5
c += d[0];
d[0] = (c & 0x1fff);
c = (c >>> 13);
c = c >>> 13;
d[1] += c;
for (i = 0; i < 10; i++)
@ -300,7 +307,7 @@ Poly1305.prototype.update = function update(data) {
// handle leftover
if (this.leftover) {
want = (16 - this.leftover);
want = 16 - this.leftover;
if (want > bytes)
want = bytes;
for (i = 0; i < want; i++)
@ -316,7 +323,7 @@ Poly1305.prototype.update = function update(data) {
// process full blocks
if (bytes >= 16) {
want = (bytes & ~(16 - 1));
want = bytes & ~(16 - 1);
this.blocks(data, want, m);
m += want;
bytes -= want;
@ -358,7 +365,7 @@ Poly1305.prototype.finish = function finish() {
c = this.h[i] >>> 13;
this.h[i] &= 0x1fff;
}
this.h[0] += (c * 5);
this.h[0] += c * 5;
c = this.h[0] >>> 13;
this.h[0] &= 0x1fff;
this.h[1] += c;