Last active
August 29, 2015 14:16
-
-
Save kei2100/4326111466f76fc589c1 to your computer and use it in GitHub Desktop.
RFC4226 HOTP generator
This file contains 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
import org.apache.commons.codec.digest.HmacUtils; | |
import java.nio.ByteBuffer; | |
public class HotpUtil { | |
private static final int LONG_BYTE_SIZE = Long.SIZE / Byte.SIZE; | |
private static final int MAX_DIGITS = 9; | |
private static final int[] MODULO_OPERANDS = new int[]{ | |
1, | |
10, | |
100, | |
1000, | |
10000, | |
100000, | |
1000000, | |
10000000, | |
100000000, | |
1000000000, | |
}; | |
public static int generate(byte[] key, long factor, int digits) { | |
if (digits < 1 || digits > MAX_DIGITS) { | |
throw new IllegalArgumentException("digits must be 1-" + MAX_DIGITS); | |
} | |
byte[] hash = HmacUtils.hmacSha1(key, ByteBuffer.allocate(LONG_BYTE_SIZE).putLong(factor).array()); | |
// hash to integer | |
int offset = hash[hash.length - 1] & 0xf; | |
int binary = ((hash[offset] & 0x7f) << 24) | | |
((hash[offset + 1] & 0xff) << 16) | | |
((hash[offset + 2] & 0xff) << 8) | | |
(hash[offset + 3] & 0xff); | |
return binary % MODULO_OPERANDS[digits]; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment