This commit is contained in:
43
src/commonMain/kotlin/com/infendro/otp/TOTP.kt
Normal file
43
src/commonMain/kotlin/com/infendro/otp/TOTP.kt
Normal file
@@ -0,0 +1,43 @@
|
||||
package com.infendro.otp
|
||||
|
||||
import com.infendro.hash.HashFunction
|
||||
import com.infendro.hash.SHA1
|
||||
import kotlin.time.Duration
|
||||
import kotlin.time.Duration.Companion.seconds
|
||||
import kotlin.time.ExperimentalTime
|
||||
import kotlin.time.Instant
|
||||
|
||||
@ExperimentalTime
|
||||
class TOTP(
|
||||
function: HashFunction = SHA1,
|
||||
length: Int = 6,
|
||||
val period: Duration = 30.seconds,
|
||||
) {
|
||||
val hotp = HOTP(function, length)
|
||||
|
||||
fun verify(
|
||||
secret: ByteArray,
|
||||
instant: Instant,
|
||||
otp: String,
|
||||
): Boolean {
|
||||
return generate(secret, instant) == otp
|
||||
}
|
||||
|
||||
fun generate(
|
||||
secret: ByteArray,
|
||||
instant: Instant,
|
||||
): String {
|
||||
return hotp.generate(
|
||||
secret,
|
||||
counter(instant)
|
||||
)
|
||||
}
|
||||
|
||||
private fun counter(
|
||||
instant: Instant,
|
||||
): Long {
|
||||
val ms = instant.toEpochMilliseconds()
|
||||
val d = period.inWholeMilliseconds
|
||||
return ms / d
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user