package com.infendro.otp import com.infendro.hash.HashFunction import com.infendro.hash.sha1.SHA1 import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds import kotlin.time.Instant class TOTP( val function: HashFunction = SHA1(), val length: Int = 6, val period: Duration = 30.seconds, ) { private val hotp = HOTP(function, length) fun generate(secret: ByteArray, instant: Instant): String { return hotp.generate(secret, counter(instant)) } fun verify(secret: ByteArray, instant: Instant, otp: String): Boolean { return generate(secret, instant) == otp } private fun counter(instant: Instant): Long { val ms = instant.toEpochMilliseconds() val d = period.inWholeMilliseconds return ms / d } }