Skip to content

Instantly share code, notes, and snippets.

@hisui
Last active August 29, 2015 14:11
Show Gist options
  • Save hisui/f99309f73e63ae53bd04 to your computer and use it in GitHub Desktop.
Save hisui/f99309f73e63ae53bd04 to your computer and use it in GitHub Desktop.
HOTP
def HMAC_SHA1(key: Array[Byte], text: Array[Byte]): Array[Byte] = {
val mac = Mac.getInstance("HmacSHA1")
mac.init(new SecretKeySpec(key, "RAW"))
mac.doFinal(text)
}
def hton64(n: Long): Array[Byte] =
(0 to 7)
.map(i => (n >>> 8 * (7 - i)) & 0xff)
.map(_.toByte)
.toArray
def generateOTP(key: Array[Byte], movingFactor: Long, digits: Int): String = {
val hash = HMAC_SHA1(key, hton64(movingFactor))
val off = hash.last & 0x0f
var code = hash.slice(off, off+4).foldLeft(0) { (acc, b) => acc << 8 | (b & 0xff) }
code &= 0x7fffffff
code %= Math.pow(10, digits).toInt
("%0" + digits + "d").format(code)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment