generateTOTPCode static method
Generates an OTP code based on the provided secret and interval.
secretKey
is the secret key in string, length limit 16 to 255.interval
is the time interval in seconds, recommended to use 30 secs
Implementation
static String generateTOTPCode(
{required String secretKey, required int interval}) {
if (secretKey.length < 16 || secretKey.length > 255) {
throw ArgumentError('The length of the secret must be 16 to 255.');
}
final time = DateTime.now().millisecondsSinceEpoch ~/ 1000 ~/ interval;
// Remove espaço e traço da chave secreta
secretKey = secretKey.replaceAll(RegExp(r'[ -]'), '');
final secretBytes = _base32Decode(secretKey);
// Simular a operação de setInt64 com duas operações de 32 bits
final timeBytes = Uint8List(8);
_writeInt64Compat(timeBytes, 0, time);
final hmac = Hmac(sha1, secretBytes);
final hash = hmac.convert(timeBytes).bytes;
final offset = hash[hash.length - 1] & 0xf;
final binary = ((hash[offset] & 0x7f) << 24) |
((hash[offset + 1] & 0xff) << 16) |
((hash[offset + 2] & 0xff) << 8) |
(hash[offset + 3] & 0xff);
final code = binary % 1000000;
return code.toString().padLeft(6, '0');
}