initial commit
All checks were successful
/ publish (push) Successful in 3m9s

This commit is contained in:
2025-07-12 20:04:39 +02:00
commit 1300e1d728
14 changed files with 776 additions and 0 deletions

View File

@@ -0,0 +1,58 @@
package com.infendro.otp
import com.infendro.hash.HashFunction
import com.infendro.hash.SHA1
import com.infendro.mac.HMAC
import com.infendro.otp.util.toByteArray
import com.infendro.otp.util.toInt
import kotlin.experimental.and
import kotlin.math.pow
class HOTP(
val function: HashFunction = SHA1,
val length: Int = 6,
) {
fun verify(
secret: ByteArray,
counter: Long,
otp: String,
): Boolean {
return generate(secret, counter) == otp
}
fun generate(
secret: ByteArray,
counter: Long,
): String {
if (counter < 0)
throw Exception()
val hash = generateHash(
secret,
counter.toByteArray()
)
return otp(hash)
}
private fun generateHash(
secret: ByteArray,
value: ByteArray,
): ByteArray {
return HMAC(function).hash(secret, value)
}
private fun otp(
hash: ByteArray,
): String {
val offset = (hash.last() and 0xF).toInt()
var truncatedHash = hash
.drop(offset)
.take(4)
.toInt() and 0x7FFFFFFF
truncatedHash %= 10.0.pow(length).toInt()
return truncatedHash.toString()
.padStart(length, '0')
}
}