finish method

Poly1305 finish(
  1. Uint8List mac,
  2. int macpos
)

Implementation

Poly1305 finish(Uint8List mac, int macpos) {
  final g = Int32List(10);
  int i;
  int c, mask, f;

  if (_leftover != 0) {
    i = _leftover;
    _buffer[i++] = 1;
    for (; i < 16; i++) {
      _buffer[i] = 0;
    }
    _fin = 1;
    _blocks(_buffer, 0, 16);
  }

  c = _h[1] >> 13;
  _h[1] &= 0x1fff;
  for (i = 2; i < 10; i++) {
    _h[i] += c;
    c = _h[i] >> 13;
    _h[i] &= 0x1fff;
  }
  _h[0] += (c * 5);
  c = _h[0] >> 13;
  _h[0] &= 0x1fff;
  _h[1] += c;
  c = _h[1] >> 13;
  _h[1] &= 0x1fff;
  _h[2] += c;

  g[0] = _h[0] + 5;
  c = g[0] >> 13;
  g[0] &= 0x1fff;
  for (i = 1; i < 10; i++) {
    g[i] = _h[i] + c;
    c = g[i] >> 13;
    g[i] &= 0x1fff;
  }
  g[9] -= (1 << 13);
  g[9] &= 0xffff;

  /// BACKPORT from [tweetnacl-fast.js ](https://github.com/dchest/tweetnacl-js/releases/tag/v0.14.3)
  ///
  ///  "The issue was not properly detecting if st->h was >= 2^130 - 5,
  ///  coupled with [testing mistake] not catching the failure.
  ///  The chance of the bug affecting anything in the real world is essentially zero luckily,
  ///  but it's good to have it fixed."
  ///
  /// change mask = (g[9] >>> ((2 * 8) - 1)) - 1; to as
  mask = (c ^ 1) - 1;
  mask &= 0xffff;

  /// END OF BACKPORT

  for (i = 0; i < 10; i++) {
    g[i] &= mask;
  }
  mask = ~mask;
  for (i = 0; i < 10; i++) {
    _h[i] = (_h[i] & mask) | g[i];
  }

  _h[0] = _h[0] | (_h[1] << 13) & 0xffff;
  _h[1] = (_h[1] >> 3) | (_h[2] << 10) & 0xffff;
  _h[2] = (_h[2] >> 6) | (_h[3] << 7) & 0xffff;
  _h[3] = (_h[3] >> 9) | (_h[4] << 4) & 0xffff;
  _h[4] = (_h[4] >> 12) | (_h[5] << 1) | (_h[6] << 14) & 0xffff;
  _h[5] = (_h[6] >> 2) | (_h[7] << 11) & 0xffff;
  _h[6] = (_h[7] >> 5) | (_h[8] << 8) & 0xffff;
  _h[7] = (_h[8] >> 8) | (_h[9] << 5) & 0xffff;

  f = _h[0] + _pad[0];
  _h[0] = f & 0xffff;
  for (i = 1; i < 8; i++) {
    f = (((_h[i] + _pad[i]) | 0) + (f >> 16)) | 0;
    _h[i] = f & 0xffff;
  }

  mac[macpos + 0] = (_h[0] >> 0) & 0xff;
  mac[macpos + 1] = (_h[0] >> 8) & 0xff;
  mac[macpos + 2] = (_h[1] >> 0) & 0xff;
  mac[macpos + 3] = (_h[1] >> 8) & 0xff;
  mac[macpos + 4] = (_h[2] >> 0) & 0xff;
  mac[macpos + 5] = (_h[2] >> 8) & 0xff;
  mac[macpos + 6] = (_h[3] >> 0) & 0xff;
  mac[macpos + 7] = (_h[3] >> 8) & 0xff;
  mac[macpos + 8] = (_h[4] >> 0) & 0xff;
  mac[macpos + 9] = (_h[4] >> 8) & 0xff;
  mac[macpos + 10] = (_h[5] >> 0) & 0xff;
  mac[macpos + 11] = (_h[5] >> 8) & 0xff;
  mac[macpos + 12] = (_h[6] >> 0) & 0xff;
  mac[macpos + 13] = (_h[6] >> 8) & 0xff;
  mac[macpos + 14] = (_h[7] >> 0) & 0xff;
  mac[macpos + 15] = (_h[7] >> 8) & 0xff;

  return this;
}