generateOTP method

String generateOTP({
  1. required int input,
  2. OTPAlgorithm? algorithm,
})
inherited

When class HOTP or TOTP pass the input params to this function, it will generate the OTP object with params, the params may be counter or time.

input parameter is mandatory, and algorithm defaults to value passed to the constructor (OTP.algorithm).

Implementation

String generateOTP({
  required int input,
  OTPAlgorithm? algorithm,
}) {
  /// base32 decode the secret
  var hmacKey = base32.decode(this.secret);

  /// initial the HMAC-SHA1 object
  var hmacSha = AlgorithmUtil.createHmacFor(
    algorithm: algorithm ?? this.algorithm,
    key: hmacKey,
  )!;

  /// get hmac answer
  var hmac = hmacSha.convert(Util.intToBytelist(input)).bytes;

  /// calculate the init offset
  int offset = hmac[hmac.length - 1] & 0xf;

  /// calculate the code
  int code = ((hmac[offset] & 0x7f) << 24 |
      (hmac[offset + 1] & 0xff) << 16 |
      (hmac[offset + 2] & 0xff) << 8 |
      (hmac[offset + 3] & 0xff));

  /// get the initial string code
  var strCode = (code % pow(10, this.digits)).toString();
  strCode = strCode.padLeft(this.digits, '0');

  return strCode;
}