Yet Another OTP generator
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Hotp.kt 819B

1234567891011121314151617
  1. package com.chameth.yaotp.algos
  2. import java.nio.ByteBuffer
  3. import kotlin.experimental.and
  4. import kotlin.math.pow
  5. data class HotpParams(val key: ByteArray, val length: Int = 6, val hmacFunc: HmacFunc = ::hmacSha1)
  6. fun hotp(params: HotpParams, counter: ByteArray) = newOtp(hmacToHotp(params.hmacFunc(params.key, counter), params.length), params.length)
  7. internal fun offsetValue(bytes: ByteArray) = (bytes[bytes.size - 1] and 0x0F).toInt()
  8. internal fun offset(bytes: ByteArray) = offsetValue(bytes).let { bytes.sliceArray(IntRange(it, it + 3)) }
  9. internal fun mask(bytes: ByteArray) = ByteArray(bytes.size) { pos -> if (pos == 0) bytes[pos] and 0x7f else bytes[pos] }
  10. internal fun hmacToHotp(bytes: ByteArray, length: Int = 6) = (ByteBuffer.wrap(mask(offset(bytes))).int % 10.0.pow(length)).toInt()