Files
otp.kt/src/commonMain/kotlin/com/infendro/otp/TOTP.kt
2026-03-12 11:25:47 +01:00

30 lines
796 B
Kotlin

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
}
}