Skip to content

Instantly share code, notes, and snippets.

@d1rtym0nk3y
Created March 11, 2013 15:48
Show Gist options
  • Save d1rtym0nk3y/5135188 to your computer and use it in GitHub Desktop.
Save d1rtym0nk3y/5135188 to your computer and use it in GitHub Desktop.
private static long getCode(byte[] secret, long timeIndex)
throws NoSuchAlgorithmException, InvalidKeyException {
SecretKeySpec signKey = new SecretKeySpec(secret, "HmacSHA1");
ByteBuffer buffer = ByteBuffer.allocate(8);
buffer.putLong(timeIndex);
byte[] timeBytes = buffer.array();
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signKey);
byte[] hash = mac.doFinal(timeBytes);
int offset = hash[19] & 0xf;
long truncatedHash = hash[offset] & 0x7f;
for (int i = 1; i < 4; i++) {
truncatedHash <<= 8;
truncatedHash |= hash[offset + i] & 0xff;
}
return (truncatedHash %= 1000000);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment