generateAuthTotpCode function

String generateAuthTotpCode(
  1. String base32Secret, {
  2. int? timestampSeconds,
  3. int period = 30,
  4. int digits = 6,
})

Generates an RFC 6238 TOTP code using the maintained hashlib OTP core.

Implementation

String generateAuthTotpCode(
  String base32Secret, {
  int? timestampSeconds,
  int period = 30,
  int digits = 6,
}) {
  if (period <= 0) throw ArgumentError.value(period, 'period');
  if (digits < 6 || digits > 8) throw ArgumentError.value(digits, 'digits');
  final secret = decodeAuthBase32(base32Secret);
  if (secret == null || secret.isEmpty) {
    throw ArgumentError.value(base32Secret, 'base32Secret');
  }
  final seconds =
      timestampSeconds ?? DateTime.now().toUtc().millisecondsSinceEpoch ~/ 1000;
  final counter = seconds ~/ period;
  final counterBytes = Uint8List(8);
  var value = counter;
  for (var index = counterBytes.length - 1; index >= 0; index--) {
    counterBytes[index] = value & 0xff;
    value >>= 8;
  }
  return HOTP(
    secret,
    counter: counterBytes,
    digits: digits,
    algo: sha1,
  ).valueString();
}