Last active
August 29, 2015 14:11
-
-
Save hisui/f99309f73e63ae53bd04 to your computer and use it in GitHub Desktop.
HOTP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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