newMacSink method

  1. @override
Future<MacSink> newMacSink({
  1. required SecretKey secretKey,
  2. List<int> nonce = const <int>[],
  3. List<int> aad = const <int>[],
})
override

Constructs a sink for calculating a Mac.

The parameter secretKey must be non-empty.

The parameter nonce can be const <int>[].

The parameter aad is Associated Authenticated Data (AAD). It can be empty. If it's non-empty and the algorithm does not support AAD, the the method throws ArgumentError.

Example

import 'package:better_cryptography/better_cryptography.dart';

void main() {
  final secretKey = SecretKey([1,2,3]);

  // Create a sink
  final sink = await Hmac.sha256().newMacSink(
    secretKey: secretKey,
  );

  // Add chunks of data
  sink.add([4,5,6]);
  sink.add([7,8]);

  // Close
  sink.close();

  // We now have a MAC
  final mac = await sink.mac();

  print('MAC: ${mac.bytes');
}

Implementation

@override
Future<MacSink> newMacSink({
  required SecretKey secretKey,
  List<int> nonce = const <int>[],
  List<int> aad = const <int>[],
}) async {
  if (aad.isNotEmpty) {
    throw ArgumentError.value(
      aad,
      'aad',
      'AAD is not supported',
    );
  }
  final secretKeyBytes = await secretKey.extractBytes();

  // RFC variable `r`
  final r = ByteData(20);
  for (var i = 0; i < 16; i++) {
    r.setUint8(i, secretKeyBytes[i]);
  }
  r.setUint8(3, 15 & r.getUint8(3));
  r.setUint8(4, 252 & r.getUint8(4));
  r.setUint8(7, 15 & r.getUint8(7));
  r.setUint8(8, 252 & r.getUint8(8));
  r.setUint8(11, 15 & r.getUint8(11));
  r.setUint8(12, 252 & r.getUint8(12));
  r.setUint8(15, 15 & r.getUint8(15));

  // RFC variable `s`
  final s = ByteData(20);
  for (var i = 0; i < 16; i++) {
    s.setUint8(i, secretKeyBytes[16 + i]);
  }

  return _Poly1305Sink(r, s);
}